Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.146
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.146! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.145 2022/01/03 01:51:09 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);
1257: if (!$uhome) {
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");
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.923 raeburn 2274: }
1.912 raeburn 2275: if ($response ne 'refused') {
2276: my @pairs=split(/\&/,$response);
2277: foreach my $item (@pairs) {
2278: my ($key,$value)=split(/=/,$item,2);
2279: $key = &unescape($key);
2280: next if ($key =~ /^error: 2 /);
2281: $returnhash{$key}=&thaw_unescape($value);
2282: }
2283: }
2284: }
2285: }
2286: }
2287: return %returnhash;
2288: }
2289:
2290: sub inst_userrules {
1.923 raeburn 2291: my ($udom,$check) = @_;
1.912 raeburn 2292: my (%ruleshash,@ruleorder);
2293: if ($udom ne '') {
2294: my $homeserver=&domain($udom,'primary');
2295: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2296: my $response;
2297: if ($check eq 'id') {
2298: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2299: $homeserver);
1.943 raeburn 2300: } elsif ($check eq 'email') {
2301: $response=&reply('instemailrules:'.&escape($udom),
2302: $homeserver);
1.923 raeburn 2303: } else {
2304: $response=&reply('instuserrules:'.&escape($udom),
2305: $homeserver);
2306: }
1.912 raeburn 2307: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2308: ($response ne 'unknown_cmd') &&
1.912 raeburn 2309: ($response ne 'no_such_host')) {
2310: my ($hashitems,$orderitems) = split(/:/,$response);
2311: my @pairs=split(/\&/,$hashitems);
2312: foreach my $item (@pairs) {
2313: my ($key,$value)=split(/=/,$item,2);
2314: $key = &unescape($key);
2315: next if ($key =~ /^error: 2 /);
2316: $ruleshash{$key}=&thaw_unescape($value);
2317: }
2318: my @esc_order = split(/\&/,$orderitems);
2319: foreach my $item (@esc_order) {
2320: push(@ruleorder,&unescape($item));
2321: }
2322: }
2323: }
2324: }
2325: return (\%ruleshash,\@ruleorder);
2326: }
2327:
1.976 raeburn 2328: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2329:
2330: sub get_domain_defaults {
1.1172.2.35 raeburn 2331: my ($domain,$ignore_cache) = @_;
2332: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2333: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2334: unless ($ignore_cache) {
2335: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2336: if (defined($cached)) {
2337: if (ref($result) eq 'HASH') {
2338: return %{$result};
2339: }
1.943 raeburn 2340: }
2341: }
2342: my %domdefaults;
2343: my %domconfig =
1.989 raeburn 2344: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2345: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2346: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2347: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2348: 'coursecategories','autoenroll',
1.1172.2.146! raeburn 2349: 'helpsettings','wafproxy'],$domain);
1.1172.2.41 raeburn 2350: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2351: if (ref($domconfig{'defaults'}) eq 'HASH') {
2352: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2353: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2354: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2355: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2356: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2357: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2358: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2359: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2360: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2361: } else {
2362: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2363: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2364: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2365: }
1.976 raeburn 2366: if (ref($domconfig{'quotas'}) eq 'HASH') {
2367: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2368: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2369: } else {
2370: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2371: }
1.1172.2.6 raeburn 2372: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2373: foreach my $item (@usertools) {
2374: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2375: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2376: }
2377: }
1.1172.2.29 raeburn 2378: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2379: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2380: }
1.976 raeburn 2381: }
1.985 raeburn 2382: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2383: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2384: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2385: }
2386: }
1.1172.2.9 raeburn 2387: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2388: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2389: }
1.989 raeburn 2390: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2391: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2392: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2393: }
2394: }
1.1047 raeburn 2395: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2396: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144 raeburn 2397: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60 raeburn 2398: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2399: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2400: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2401: }
1.1172.2.41 raeburn 2402: foreach my $type (@coursetypes) {
2403: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2404: unless ($type eq 'community') {
2405: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2406: }
2407: }
2408: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2409: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2410: }
1.1172.2.60 raeburn 2411: if ($domdefaults{'postsubmit'} eq 'on') {
2412: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2413: $domdefaults{$type.'postsubtimeout'} =
2414: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2415: }
2416: }
1.1172.2.30 raeburn 2417: }
1.1172.2.67 raeburn 2418: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2419: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2420: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2421: if (@clonecodes) {
2422: $domdefaults{'canclone'} = join('+',@clonecodes);
2423: }
2424: }
2425: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2426: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2427: }
1.1172.2.103 raeburn 2428: if ($domconfig{'coursedefaults'}{'texengine'}) {
2429: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2430: }
1.1047 raeburn 2431: }
1.1073 raeburn 2432: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2433: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2434: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2435: }
2436: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2437: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2438: }
1.1172.2.62 raeburn 2439: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2440: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2441: }
1.1172.2.137 raeburn 2442: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2443: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2444: }
1.1073 raeburn 2445: }
1.1172.2.41 raeburn 2446: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2447: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2448: my @settings = ('types','registered','enroll_dates','access_dates','section',
2449: 'approval','limit');
2450: foreach my $type (@coursetypes) {
2451: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2452: my @mgrdc = ();
2453: foreach my $item (@settings) {
2454: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2455: push(@mgrdc,$item);
2456: }
2457: }
2458: if (@mgrdc) {
2459: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2460: }
2461: }
2462: }
2463: }
2464: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2465: foreach my $type (@coursetypes) {
2466: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2467: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2468: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2469: }
2470: }
2471: }
2472: }
2473: }
1.1172.2.46 raeburn 2474: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2475: $domdefaults{'catauth'} = 'std';
2476: $domdefaults{'catunauth'} = 'std';
2477: if ($domconfig{'coursecategories'}{'auth'}) {
2478: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2479: }
2480: if ($domconfig{'coursecategories'}{'unauth'}) {
2481: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2482: }
2483: }
1.1172.2.76 raeburn 2484: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2485: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146! raeburn 2486: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76 raeburn 2487: }
1.1172.2.89 raeburn 2488: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2489: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2490: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2491: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2492: }
2493: }
1.1172.2.142 raeburn 2494: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2495: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2496: if ($domconfig{'wafproxy'}{$item}) {
2497: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2498: }
2499: }
2500: }
1.1172.2.23 raeburn 2501: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2502: return %domdefaults;
2503: }
2504:
1.1172.2.106 raeburn 2505: sub get_dom_cats {
2506: my ($dom) = @_;
2507: return unless (&domain($dom));
2508: my ($cats,$cached)=&is_cached_new('cats',$dom);
2509: unless (defined($cached)) {
2510: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2511: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2512: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2513: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2514: } else {
2515: $cats = {};
2516: }
2517: } else {
2518: $cats = {};
2519: }
2520: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2521: }
2522: return $cats;
2523: }
2524:
2525: sub get_dom_instcats {
2526: my ($dom) = @_;
2527: return unless (&domain($dom));
2528: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2529: unless (defined($cached)) {
2530: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2531: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2532: if ($totcodes > 0) {
2533: my $caller = 'global';
2534: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2535: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2536: $instcats = {
2537: codes => \%codes,
2538: codetitles => \@codetitles,
2539: cat_titles => \%cat_titles,
2540: cat_order => \%cat_order,
2541: };
2542: &do_cache_new('instcats',$dom,$instcats,3600);
2543: }
2544: }
2545: }
2546: return $instcats;
2547: }
2548:
2549: sub retrieve_instcodes {
2550: my ($coursecodes,$dom) = @_;
2551: my $totcodes;
2552: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2553: foreach my $course (keys(%courses)) {
2554: if (ref($courses{$course}) eq 'HASH') {
2555: if ($courses{$course}{'inst_code'} ne '') {
2556: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2557: $totcodes ++;
2558: }
2559: }
2560: }
2561: return $totcodes;
2562: }
2563:
1.1172.2.113 raeburn 2564: # --------------------------------------------- Get domain config for passwords
2565:
2566: sub get_passwdconf {
2567: my ($dom) = @_;
2568: my (%passwdconf,$gotconf,$lookup);
2569: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2570: if (defined($cached)) {
2571: if (ref($result) eq 'HASH') {
2572: %passwdconf = %{$result};
2573: $gotconf = 1;
2574: }
2575: }
2576: unless ($gotconf) {
2577: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2578: if (ref($domconfig{'passwords'}) eq 'HASH') {
2579: %passwdconf = %{$domconfig{'passwords'}};
2580: }
2581: my $cachetime = 24*60*60;
2582: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2583: }
2584: return %passwdconf;
2585: }
2586:
1.344 www 2587: # --------------------------------------------------- Assign a key to a student
2588:
2589: sub assign_access_key {
1.364 www 2590: #
2591: # a valid key looks like uname:udom#comments
2592: # comments are being appended
2593: #
1.498 www 2594: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2595: $kdom=
1.620 albertel 2596: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2597: $knum=
1.620 albertel 2598: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2599: $cdom=
1.620 albertel 2600: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2601: $cnum=
1.620 albertel 2602: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2603: $udom=$env{'user.name'} unless (defined($udom));
2604: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2605: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2606: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2607: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2608: # assigned to this person
2609: # - this should not happen,
1.345 www 2610: # unless something went wrong
2611: # the first time around
2612: # ready to assign
1.364 www 2613: $logentry=$1.'; '.$logentry;
1.496 www 2614: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2615: $kdom,$knum) eq 'ok') {
1.345 www 2616: # key now belongs to user
1.346 www 2617: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2618: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2619: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2620: return 'ok';
2621: } else {
2622: return
2623: 'error: Count not permanently assign key, will need to be re-entered later.';
2624: }
2625: } else {
2626: return 'error: Could not assign key, try again later.';
2627: }
1.364 www 2628: } elsif (!$existing{$ckey}) {
1.345 www 2629: # the key does not exist
2630: return 'error: The key does not exist';
2631: } else {
2632: # the key is somebody else's
2633: return 'error: The key is already in use';
2634: }
1.344 www 2635: }
2636:
1.364 www 2637: # ------------------------------------------ put an additional comment on a key
2638:
2639: sub comment_access_key {
2640: #
2641: # a valid key looks like uname:udom#comments
2642: # comments are being appended
2643: #
2644: my ($ckey,$cdom,$cnum,$logentry)=@_;
2645: $cdom=
1.620 albertel 2646: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2647: $cnum=
1.620 albertel 2648: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2649: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2650: if ($existing{$ckey}) {
2651: $existing{$ckey}.='; '.$logentry;
2652: # ready to assign
1.367 www 2653: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2654: $cdom,$cnum) eq 'ok') {
2655: return 'ok';
2656: } else {
2657: return 'error: Count not store comment.';
2658: }
2659: } else {
2660: # the key does not exist
2661: return 'error: The key does not exist';
2662: }
2663: }
2664:
1.344 www 2665: # ------------------------------------------------------ Generate a set of keys
2666:
2667: sub generate_access_keys {
1.364 www 2668: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2669: $cdom=
1.620 albertel 2670: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2671: $cnum=
1.620 albertel 2672: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2673: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2674: unless (($cdom) && ($cnum)) { return 0; }
2675: if ($number>10000) { return 0; }
2676: sleep(2); # make sure don't get same seed twice
2677: srand(time()^($$+($$<<15))); # from "Programming Perl"
2678: my $total=0;
2679: for (my $i=1;$i<=$number;$i++) {
2680: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2681: sprintf("%lx",int(100000*rand)).'-'.
2682: sprintf("%lx",int(100000*rand));
2683: $newkey=~s/1/g/g; # folks mix up 1 and l
2684: $newkey=~s/0/h/g; # and also 0 and O
2685: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2686: if ($existing{$newkey}) {
2687: $i--;
2688: } else {
1.364 www 2689: if (&put('accesskeys',
2690: { $newkey => '# generated '.localtime().
1.620 albertel 2691: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2692: '; '.$logentry },
2693: $cdom,$cnum) eq 'ok') {
1.344 www 2694: $total++;
2695: }
2696: }
2697: }
1.620 albertel 2698: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2699: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2700: return $total;
2701: }
2702:
2703: # ------------------------------------------------------- Validate an accesskey
2704:
2705: sub validate_access_key {
2706: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2707: $cdom=
1.620 albertel 2708: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2709: $cnum=
1.620 albertel 2710: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2711: $udom=$env{'user.domain'} unless (defined($udom));
2712: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2713: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2714: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2715: }
2716:
2717: # ------------------------------------- Find the section of student in a course
1.652 albertel 2718: sub devalidate_getsection_cache {
2719: my ($udom,$unam,$courseid)=@_;
2720: my $hashid="$udom:$unam:$courseid";
2721: &devalidate_cache_new('getsection',$hashid);
2722: }
1.298 matthew 2723:
1.815 albertel 2724: sub courseid_to_courseurl {
2725: my ($courseid) = @_;
2726: #already url style courseid
2727: return $courseid if ($courseid =~ m{^/});
2728:
2729: if (exists($env{'course.'.$courseid.'.num'})) {
2730: my $cnum = $env{'course.'.$courseid.'.num'};
2731: my $cdom = $env{'course.'.$courseid.'.domain'};
2732: return "/$cdom/$cnum";
2733: }
2734:
2735: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2736: if (exists($courseinfo{'num'})) {
2737: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2738: }
2739:
2740: return undef;
2741: }
2742:
1.298 matthew 2743: sub getsection {
2744: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2745: my $cachetime=1800;
1.551 albertel 2746:
2747: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2748: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2749: if (defined($cached)) { return $result; }
2750:
1.298 matthew 2751: my %Pending;
2752: my %Expired;
2753: #
2754: # Each role can either have not started yet (pending), be active,
2755: # or have expired.
2756: #
2757: # If there is an active role, we are done.
2758: #
2759: # If there is more than one role which has not started yet,
2760: # choose the one which will start sooner
2761: # If there is one role which has not started yet, return it.
2762: #
2763: # If there is more than one expired role, choose the one which ended last.
2764: # If there is a role which has expired, return it.
2765: #
1.815 albertel 2766: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2767: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2768: foreach my $key (keys(%roleshash)) {
1.479 albertel 2769: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2770: my $section=$1;
2771: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2772: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2773: my $now=time;
1.548 albertel 2774: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2775: $Expired{$end}=$section;
2776: next;
2777: }
1.548 albertel 2778: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2779: $Pending{$start}=$section;
2780: next;
2781: }
1.599 albertel 2782: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2783: }
2784: #
2785: # Presumedly there will be few matching roles from the above
2786: # loop and the sorting time will be negligible.
2787: if (scalar(keys(%Pending))) {
2788: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2789: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2790: }
2791: if (scalar(keys(%Expired))) {
2792: my @sorted = sort {$a <=> $b} keys(%Expired);
2793: my $time = pop(@sorted);
1.599 albertel 2794: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2795: }
1.599 albertel 2796: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2797: }
1.70 www 2798:
1.599 albertel 2799: sub save_cache {
2800: &purge_remembered();
1.722 albertel 2801: #&Apache::loncommon::validate_page();
1.620 albertel 2802: undef(%env);
1.780 albertel 2803: undef($env_loaded);
1.599 albertel 2804: }
1.452 albertel 2805:
1.599 albertel 2806: my $to_remember=-1;
2807: my %remembered;
2808: my %accessed;
2809: my $kicks=0;
2810: my $hits=0;
1.849 albertel 2811: sub make_key {
2812: my ($name,$id) = @_;
1.872 albertel 2813: if (length($id) > 65
2814: && length(&escape($id)) > 200) {
2815: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2816: }
1.849 albertel 2817: return &escape($name.':'.$id);
2818: }
2819:
1.599 albertel 2820: sub devalidate_cache_new {
2821: my ($name,$id,$debug) = @_;
2822: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2823: my $remembered_id=$name.':'.$id;
1.849 albertel 2824: $id=&make_key($name,$id);
1.599 albertel 2825: $memcache->delete($id);
1.1172.2.81 raeburn 2826: delete($remembered{$remembered_id});
2827: delete($accessed{$remembered_id});
1.599 albertel 2828: }
2829:
2830: sub is_cached_new {
2831: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2832: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2833: # keys in %remembered hash, which persists for
2834: # duration of request (no restriction on key length).
2835: if (exists($remembered{$remembered_id})) {
2836: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2837: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2838: $hits++;
1.1172.2.81 raeburn 2839: return ($remembered{$remembered_id},1);
1.599 albertel 2840: }
1.1172.2.81 raeburn 2841: $id=&make_key($name,$id);
1.599 albertel 2842: my $value = $memcache->get($id);
2843: if (!(defined($value))) {
2844: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2845: return (undef,undef);
1.416 albertel 2846: }
1.599 albertel 2847: if ($value eq '__undef__') {
2848: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2849: $value=undef;
2850: }
1.1172.2.81 raeburn 2851: &make_room($remembered_id,$value,$debug);
1.599 albertel 2852: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2853: return ($value,1);
2854: }
2855:
2856: sub do_cache_new {
2857: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2858: my $remembered_id=$name.':'.$id;
1.849 albertel 2859: $id=&make_key($name,$id);
1.599 albertel 2860: my $setvalue=$value;
2861: if (!defined($setvalue)) {
2862: $setvalue='__undef__';
2863: }
1.623 albertel 2864: if (!defined($time) ) {
2865: $time=600;
2866: }
1.599 albertel 2867: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2868: my $result = $memcache->set($id,$setvalue,$time);
2869: if (! $result) {
1.872 albertel 2870: &logthis("caching of id -> $id failed");
1.910 albertel 2871: $memcache->disconnect_all();
1.872 albertel 2872: }
1.600 albertel 2873: # need to make a copy of $value
1.1172.2.81 raeburn 2874: &make_room($remembered_id,$value,$debug);
1.599 albertel 2875: return $value;
2876: }
2877:
2878: sub make_room {
1.1172.2.81 raeburn 2879: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2880:
1.1172.2.81 raeburn 2881: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2882: : $value;
1.599 albertel 2883: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2884: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2885: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2886: my $to_kick;
2887: my $max_time=0;
2888: foreach my $other (keys(%accessed)) {
2889: if (&tv_interval($accessed{$other}) > $max_time) {
2890: $to_kick=$other;
2891: $max_time=&tv_interval($accessed{$other});
2892: }
2893: }
2894: delete($remembered{$to_kick});
2895: delete($accessed{$to_kick});
2896: $kicks++;
2897: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2898: return;
2899: }
2900:
1.599 albertel 2901: sub purge_remembered {
1.604 albertel 2902: #&logthis("Tossing ".scalar(keys(%remembered)));
2903: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2904: undef(%remembered);
2905: undef(%accessed);
1.428 albertel 2906: }
1.70 www 2907: # ------------------------------------- Read an entry from a user's environment
2908:
2909: sub userenvironment {
2910: my ($udom,$unam,@what)=@_;
1.976 raeburn 2911: my $items;
2912: foreach my $item (@what) {
2913: $items.=&escape($item).'&';
2914: }
2915: $items=~s/\&$//;
1.70 www 2916: my %returnhash=();
1.1009 raeburn 2917: my $uhome = &homeserver($unam,$udom);
2918: unless ($uhome eq 'no_host') {
2919: my @answer=split(/\&/,
2920: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2921: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2922: return %returnhash;
2923: }
1.1009 raeburn 2924: my $i;
2925: for ($i=0;$i<=$#what;$i++) {
2926: $returnhash{$what[$i]}=&unescape($answer[$i]);
2927: }
1.70 www 2928: }
2929: return %returnhash;
1.1 albertel 2930: }
2931:
1.617 albertel 2932: # ---------------------------------------------------------- Get a studentphoto
2933: sub studentphoto {
2934: my ($udom,$unam,$ext) = @_;
2935: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2936: if (defined($env{'request.course.id'})) {
1.708 raeburn 2937: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2938: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2939: return(&retrievestudentphoto($udom,$unam,$ext));
2940: } else {
2941: my ($result,$perm_reqd)=
1.707 albertel 2942: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2943: if ($result eq 'ok') {
2944: if (!($perm_reqd eq 'yes')) {
2945: return(&retrievestudentphoto($udom,$unam,$ext));
2946: }
2947: }
2948: }
2949: }
2950: } else {
2951: my ($result,$perm_reqd) =
1.707 albertel 2952: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2953: if ($result eq 'ok') {
2954: if (!($perm_reqd eq 'yes')) {
2955: return(&retrievestudentphoto($udom,$unam,$ext));
2956: }
2957: }
2958: }
2959: return '/adm/lonKaputt/lonlogo_broken.gif';
2960: }
2961:
2962: sub retrievestudentphoto {
2963: my ($udom,$unam,$ext,$type) = @_;
2964: my $home=&Apache::lonnet::homeserver($unam,$udom);
2965: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2966: if ($ret eq 'ok') {
2967: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2968: if ($type eq 'thumbnail') {
2969: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2970: }
2971: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2972: return $tokenurl;
2973: } else {
2974: if ($type eq 'thumbnail') {
2975: return '/adm/lonKaputt/genericstudent_tn.gif';
2976: } else {
2977: return '/adm/lonKaputt/lonlogo_broken.gif';
2978: }
1.617 albertel 2979: }
2980: }
2981:
1.263 www 2982: # -------------------------------------------------------------------- New chat
2983:
2984: sub chatsend {
1.724 raeburn 2985: my ($newentry,$anon,$group)=@_;
1.620 albertel 2986: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2987: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2988: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2989: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2990: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2991: &escape($newentry)).':'.$group,$chome);
1.292 www 2992: }
2993:
2994: # ------------------------------------------ Find current version of a resource
2995:
2996: sub getversion {
2997: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2998: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2999: return ¤tversion(&filelocation('',$fname));
3000: }
3001:
3002: sub currentversion {
3003: my $fname=shift;
3004: my $author=$fname;
3005: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3006: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3007: my $home=&homeserver($uname,$udom);
1.292 www 3008: if ($home eq 'no_host') {
3009: return -1;
3010: }
1.1112 www 3011: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3012: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3013: return -1;
3014: }
1.1112 www 3015: return $answer;
1.263 www 3016: }
3017:
1.1111 www 3018: #
3019: # Return special version number of resource if set by override, empty otherwise
3020: #
3021: sub usedversion {
3022: my $fname=shift;
3023: unless ($fname) { $fname=$env{'request.uri'}; }
3024: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3025: if ($urlversion) { return $urlversion; }
3026: return '';
3027: }
3028:
1.1 albertel 3029: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3030:
1.1 albertel 3031: sub subscribe {
3032: my $fname=shift;
1.761 raeburn 3033: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3034: $fname=~s/[\n\r]//g;
1.1 albertel 3035: my $author=$fname;
3036: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3037: my ($udom,$uname)=split(/\//,$author);
3038: my $home=homeserver($uname,$udom);
1.335 albertel 3039: if ($home eq 'no_host') {
3040: return 'not_found';
1.1 albertel 3041: }
3042: my $answer=reply("sub:$fname",$home);
1.64 www 3043: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3044: $answer.=' by '.$home;
3045: }
1.1 albertel 3046: return $answer;
3047: }
3048:
1.8 www 3049: # -------------------------------------------------------------- Replicate file
3050:
3051: sub repcopy {
3052: my $filename=shift;
1.23 www 3053: $filename=~s/\/+/\//g;
1.1142 raeburn 3054: my $londocroot = $perlvar{'lonDocRoot'};
3055: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3056: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3057: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3058: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3059: return &repcopy_userfile($filename);
3060: }
1.532 albertel 3061: $filename=~s/[\n\r]//g;
1.8 www 3062: my $transname="$filename.in.transfer";
1.828 www 3063: # FIXME: this should flock
1.607 raeburn 3064: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3065: my $remoteurl=subscribe($filename);
1.64 www 3066: if ($remoteurl =~ /^con_lost by/) {
3067: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3068: return 'unavailable';
1.8 www 3069: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3070: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3071: return 'not_found';
1.64 www 3072: } elsif ($remoteurl =~ /^rejected by/) {
3073: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3074: return 'forbidden';
1.20 www 3075: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3076: return 'ok';
1.8 www 3077: } else {
1.290 www 3078: my $author=$filename;
3079: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3080: my ($udom,$uname)=split(/\//,$author);
3081: my $home=homeserver($uname,$udom);
3082: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3083: my @parts=split(/\//,$filename);
3084: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3085: if ($path ne "$londocroot/res") {
1.8 www 3086: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3087: return 'bad_request';
1.8 www 3088: }
3089: my $count;
3090: for ($count=5;$count<$#parts;$count++) {
3091: $path.="/$parts[$count]";
3092: if ((-e $path)!=1) {
3093: mkdir($path,0777);
3094: }
3095: }
3096: my $ua=new LWP::UserAgent;
3097: my $request=new HTTP::Request('GET',"$remoteurl");
3098: my $response=$ua->request($request,$transname);
3099: if ($response->is_error()) {
3100: unlink($transname);
3101: my $message=$response->status_line;
1.672 albertel 3102: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3103: ." LWP get: $message: $filename</font>");
1.607 raeburn 3104: return 'unavailable';
1.8 www 3105: } else {
1.16 www 3106: if ($remoteurl!~/\.meta$/) {
3107: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3108: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3109: if ($mresponse->is_error()) {
3110: unlink($filename.'.meta');
3111: &logthis(
1.672 albertel 3112: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3113: }
3114: }
1.8 www 3115: rename($transname,$filename);
1.607 raeburn 3116: return 'ok';
1.8 www 3117: }
1.290 www 3118: }
1.8 www 3119: }
1.330 www 3120: }
3121:
1.1172.2.124 raeburn 3122: # ------------------------------------------------- Unsubscribe from a resource
3123:
3124: sub unsubscribe {
3125: my ($fname) = @_;
3126: my $answer;
3127: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3128: $fname=~s/[\n\r]//g;
3129: my $author=$fname;
3130: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3131: my ($udom,$uname)=split(/\//,$author);
3132: my $home=homeserver($uname,$udom);
3133: if ($home eq 'no_host') {
3134: $answer = 'no_host';
3135: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3136: $answer = 'home';
3137: } else {
1.1172.2.125 raeburn 3138: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3139: }
3140: return $answer;
3141: }
3142:
1.330 www 3143: # ------------------------------------------------ Get server side include body
3144: sub ssi_body {
1.381 albertel 3145: my ($filelink,%form)=@_;
1.606 matthew 3146: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3147: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3148: }
1.953 www 3149: my $output='';
3150: my $response;
1.980 raeburn 3151: if ($filelink=~/^https?\:/) {
1.954 raeburn 3152: ($output,$response)=&externalssi($filelink);
1.953 www 3153: } else {
1.1004 droeschl 3154: $filelink .= $filelink=~/\?/ ? '&' : '?';
3155: $filelink .= 'inhibitmenu=yes';
1.953 www 3156: ($output,$response)=&ssi($filelink,%form);
3157: }
1.778 albertel 3158: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3159: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3160: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3161: if (wantarray) {
3162: return ($output, $response);
3163: } else {
3164: return $output;
3165: }
1.8 www 3166: }
3167:
1.15 www 3168: # --------------------------------------------------------- Server Side Include
3169:
1.782 albertel 3170: sub absolute_url {
1.1172.2.145 raeburn 3171: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3172: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3173: if ($host_name eq '') {
3174: $host_name = $ENV{'SERVER_NAME'};
3175: }
1.1172.2.145 raeburn 3176: if ($unalias) {
3177: my $alias = &get_proxy_alias();
3178: if ($alias eq $host_name) {
3179: my $lonhost = $perlvar{'lonHostID'};
3180: my $hostname = &hostname($lonhost);
3181: my $lcproto;
3182: if (($keep_proto) || ($hostname eq '')) {
3183: $lcproto = $protocol;
3184: } else {
3185: $lcproto = $protocol{$lonhost};
3186: $lcproto = 'http' if ($lcproto ne 'https');
3187: $lcproto .= '://';
3188: }
3189: unless ($hostname eq '') {
3190: return $lcproto.$hostname;
3191: }
3192: }
3193: }
1.782 albertel 3194: return $protocol.$host_name;
3195: }
3196:
1.942 foxr 3197: #
3198: # Server side include.
3199: # Parameters:
3200: # fn Possibly encrypted resource name/id.
3201: # form Hash that describes how the rendering should be done
3202: # and other things.
1.944 foxr 3203: # Returns:
1.950 raeburn 3204: # Scalar context: The content of the response.
3205: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3206: #
1.15 www 3207: sub ssi {
3208:
1.944 foxr 3209: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3210: my ($host,$request,$response);
3211: $host = &absolute_url('',1);
1.711 albertel 3212:
3213: $form{'no_update_last_known'}=1;
1.895 albertel 3214: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3215: if (%form) {
1.1172.2.145 raeburn 3216: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3217: $request->content(join('&',map {
3218: my $name = escape($_);
3219: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3220: ? join("&$name=", map {escape($_) } @{$form{$_}})
3221: : &escape($form{$_}) );
3222: } keys(%form)));
1.23 www 3223: } else {
1.1172.2.145 raeburn 3224: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3225: }
3226:
1.15 www 3227: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3228:
1.1172.2.101 raeburn 3229: if (($env{'request.course.id'}) &&
3230: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3231: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3232: ($form{'grade_symb'} ne '') &&
3233: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3234: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3235: if (LWP::UserAgent->VERSION >= 5.834) {
3236: my $ua=new LWP::UserAgent;
3237: $ua->local_address('127.0.0.1');
3238: $response = $ua->request($request);
3239: } else {
3240: {
3241: require LWP::Protocol::http;
3242: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3243: my $ua=new LWP::UserAgent;
3244: $response = $ua->request($request);
3245: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3246: }
3247: }
3248: } else {
3249: my $ua=new LWP::UserAgent;
3250: $response = $ua->request($request);
3251: }
1.944 foxr 3252: if (wantarray) {
1.1172.2.3 raeburn 3253: return ($response->content, $response);
1.944 foxr 3254: } else {
1.1172.2.3 raeburn 3255: return $response->content;
1.942 foxr 3256: }
1.324 www 3257: }
3258:
3259: sub externalssi {
3260: my ($url)=@_;
3261: my $ua=new LWP::UserAgent;
3262: my $request=new HTTP::Request('GET',$url);
3263: my $response=$ua->request($request);
1.954 raeburn 3264: if (wantarray) {
3265: return ($response->content, $response);
3266: } else {
3267: return $response->content;
3268: }
1.15 www 3269: }
1.254 www 3270:
1.1172.2.98 raeburn 3271: # If the local copy of a replicated resource is outdated, trigger a
3272: # connection from the homeserver to flush the delayed queue. If no update
3273: # happens, remove local copies of outdated resource (and corresponding
3274: # metadata file).
3275:
3276: sub remove_stale_resfile {
3277: my ($url) = @_;
3278: my $removed;
3279: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3280: my $audom = $1;
3281: my $auname = $2;
3282: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3283: my $homeserver = &homeserver($auname,$audom);
3284: unless (($homeserver eq 'no_host') ||
3285: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3286: my $fname = &filelocation('',$url);
3287: if (-e $fname) {
3288: my $hostname = &hostname($homeserver);
3289: if ($hostname) {
1.1172.2.120 raeburn 3290: my $protocol = $protocol{$homeserver};
3291: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3292: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3293: my $ua=new LWP::UserAgent;
3294: $ua->timeout(5);
1.1172.2.98 raeburn 3295: my $request=new HTTP::Request('HEAD',$uri);
3296: my $response=$ua->request($request);
3297: if ($response->is_success()) {
3298: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3299: my $locmodtime = (stat($fname))[9];
3300: if ($locmodtime < $remmodtime) {
3301: my $stale;
3302: my $answer = &reply('pong',$homeserver);
3303: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3304: sleep(0.2);
3305: $locmodtime = (stat($fname))[9];
3306: if ($locmodtime < $remmodtime) {
3307: my $posstransfer = $fname.'.in.transfer';
3308: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3309: $removed = 1;
3310: } else {
3311: $stale = 1;
3312: }
3313: } else {
3314: $removed = 1;
3315: }
3316: } else {
3317: $stale = 1;
3318: }
3319: if ($stale) {
1.1172.2.124 raeburn 3320: if (unlink($fname)) {
3321: if ($uri!~/\.meta$/) {
3322: if (-e $fname.'.meta') {
3323: unlink($fname.'.meta');
3324: }
3325: }
3326: my $unsubresult = &unsubscribe($fname);
3327: unless ($unsubresult eq 'ok') {
3328: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3329: }
3330: $removed = 1;
1.1172.2.98 raeburn 3331: }
3332: }
3333: }
3334: }
3335: }
3336: }
3337: }
3338: }
3339: }
3340: return $removed;
3341: }
3342:
1.492 albertel 3343: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3344:
3345: sub allowuploaded {
3346: my ($srcurl,$url)=@_;
3347: $url=&clutter(&declutter($url));
3348: my $dir=$url;
3349: $dir=~s/\/[^\/]+$//;
3350: my %httpref=();
3351: my $httpurl=&hreflocation('',$url);
3352: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3353: &Apache::lonnet::appenv(\%httpref);
1.254 www 3354: }
1.477 raeburn 3355:
1.1172.2.13 raeburn 3356: #
3357: # Determine if the current user should be able to edit a particular resource,
3358: # when viewing in course context.
3359: # (a) When viewing resource used to determine if "Edit" item is included in
3360: # Functions.
3361: # (b) When displaying folder contents in course editor, used to determine if
3362: # "Edit" link will be displayed alongside resource.
3363: #
3364: # input: six args -- filename (decluttered), course number, course domain,
3365: # url, symb (if registered) and group (if this is a group
3366: # item -- e.g., bulletin board, group page etc.).
3367: # output: array of five scalars --
3368: # $cfile -- url for file editing if editable on current server
3369: # $home -- homeserver of resource (i.e., for author if published,
3370: # or course if uploaded.).
3371: # $switchserver -- 1 if server switch will be needed.
3372: # $forceedit -- 1 if icon/link should be to go to edit mode
3373: # $forceview -- 1 if icon/link should be to go to view mode
3374: #
3375:
3376: sub can_edit_resource {
3377: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3378: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3379: #
3380: # For aboutme pages user can only edit his/her own.
3381: #
3382: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3383: my ($sdom,$sname) = ($1,$2);
3384: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3385: $home = $env{'user.home'};
3386: $cfile = $resurl;
3387: if ($env{'form.forceedit'}) {
3388: $forceview = 1;
3389: } else {
3390: $forceedit = 1;
3391: }
3392: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3393: } else {
3394: return;
3395: }
3396: }
3397:
3398: if ($env{'request.course.id'}) {
3399: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3400: if ($group ne '') {
3401: # if this is a group homepage or group bulletin board, check group privs
3402: my $allowed = 0;
3403: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3404: if ((&allowed('mdg',$env{'request.course.id'}.
3405: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3406: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3407: $allowed = 1;
3408: }
3409: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3410: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3411: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3412: $allowed = 1;
3413: }
3414: }
3415: if ($allowed) {
3416: $home=&homeserver($cnum,$cdom);
3417: if ($env{'form.forceedit'}) {
3418: $forceview = 1;
3419: } else {
3420: $forceedit = 1;
3421: }
3422: $cfile = $resurl;
3423: } else {
3424: return;
3425: }
3426: } else {
1.1172.2.15 raeburn 3427: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3428: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3429: return;
3430: }
3431: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3432: #
3433: # No edit allowed where CC has switched to student role.
3434: #
3435: return;
3436: }
3437: }
3438: }
3439:
3440: if ($file ne '') {
3441: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3442: if (&is_course_upload($file,$cnum,$cdom)) {
3443: $uploaded = 1;
3444: $incourse = 1;
3445: if ($file =~/\.(htm|html|css|js|txt)$/) {
3446: $cfile = &hreflocation('',$file);
3447: if ($env{'form.forceedit'}) {
3448: $forceview = 1;
3449: } else {
3450: $forceedit = 1;
3451: }
3452: }
3453: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3454: $incourse = 1;
3455: if ($env{'form.forceedit'}) {
3456: $forceview = 1;
3457: } else {
3458: $forceedit = 1;
3459: }
3460: $cfile = $resurl;
3461: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3462: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3463: $incourse = 1;
3464: if ($env{'form.forceedit'}) {
3465: $forceview = 1;
3466: } else {
3467: $forceedit = 1;
3468: }
3469: $cfile = $resurl;
3470: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3471: $incourse = 1;
3472: $cfile = $resurl.'/smpedit';
3473: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3474: $incourse = 1;
3475: if ($env{'form.forceedit'}) {
3476: $forceview = 1;
3477: } else {
3478: $forceedit = 1;
3479: }
3480: $cfile = $resurl;
1.1172.2.122 raeburn 3481: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3482: my ($map,$id,$res) = &decode_symb($symb);
3483: if ($map =~ /\.page$/) {
3484: $incourse = 1;
3485: if ($env{'form.forceedit'}) {
3486: $forceview = 1;
3487: $cfile = $map;
3488: } else {
3489: $forceedit = 1;
3490: $cfile = '/adm/wrapper'.$resurl;
3491: }
3492: }
1.1172.2.15 raeburn 3493: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3494: $incourse = 1;
3495: if ($env{'form.forceedit'}) {
3496: $forceview = 1;
3497: } else {
3498: $forceedit = 1;
3499: }
3500: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3501: }
3502: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3503: my $template = '/res/lib/templates/simpleproblem.problem';
3504: if (&is_on_map($template)) {
3505: $incourse = 1;
3506: $forceview = 1;
3507: $cfile = $template;
3508: }
3509: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3510: $incourse = 1;
3511: if ($env{'form.forceedit'}) {
3512: $forceview = 1;
3513: } else {
3514: $forceedit = 1;
3515: }
3516: $cfile = $resurl;
1.1172.2.13 raeburn 3517: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3518: $incourse = 1;
3519: $forceview = 1;
3520: if ($symb) {
3521: my ($map,$id,$res)=&decode_symb($symb);
3522: $env{'request.symb'} = $symb;
3523: $cfile = &clutter($res);
3524: } else {
3525: $cfile = $env{'form.suppurl'};
3526: $cfile =~ s{^http://}{};
3527: $cfile = '/adm/wrapper/ext/'.$cfile;
3528: }
1.1172.2.31 raeburn 3529: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3530: if ($env{'form.forceedit'}) {
3531: $forceview = 1;
3532: } else {
3533: $forceedit = 1;
3534: }
3535: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3536: }
3537: }
3538: if ($uploaded || $incourse) {
3539: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3540: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3541: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3542: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3543: # Check that the user has permission to edit this resource
3544: my $setpriv = 1;
3545: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3546: if (defined($cfudom)) {
3547: $home=&homeserver($cfuname,$cfudom);
3548: $cfile=$file;
3549: }
3550: }
3551: if (($cfile ne '') && (!$incourse || $uploaded) &&
3552: (($home ne '') && ($home ne 'no_host'))) {
3553: my @ids=¤t_machine_ids();
3554: unless (grep(/^\Q$home\E$/,@ids)) {
3555: $switchserver=1;
3556: }
3557: }
3558: }
3559: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3560: }
3561:
3562: sub is_course_upload {
3563: my ($file,$cnum,$cdom) = @_;
3564: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3565: $uploadpath =~ s{^\/}{};
3566: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3567: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3568: return 1;
3569: }
3570: return;
3571: }
3572:
3573: sub in_course {
3574: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3575: if ($hideprivileged) {
3576: my $skipuser;
1.1172.2.23 raeburn 3577: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3578: my @possdoms = ($cdom);
3579: if ($coursehash{'checkforpriv'}) {
3580: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3581: }
3582: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3583: $skipuser = 1;
3584: if ($coursehash{'nothideprivileged'}) {
3585: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3586: my $user;
3587: if ($item =~ /:/) {
3588: $user = $item;
3589: } else {
3590: $user = join(':',split(/[\@]/,$item));
3591: }
3592: if ($user eq $uname.':'.$udom) {
3593: undef($skipuser);
3594: last;
3595: }
3596: }
3597: }
3598: if ($skipuser) {
3599: return 0;
3600: }
3601: }
3602: }
3603: $type ||= 'any';
3604: if (!defined($cdom) || !defined($cnum)) {
3605: my $cid = $env{'request.course.id'};
3606: $cdom = $env{'course.'.$cid.'.domain'};
3607: $cnum = $env{'course.'.$cid.'.num'};
3608: }
3609: my $typesref;
3610: if (($type eq 'any') || ($type eq 'all')) {
3611: $typesref = ['active','previous','future'];
3612: } elsif ($type eq 'previous' || $type eq 'future') {
3613: $typesref = [$type];
3614: }
3615: my %roles = &get_my_roles($uname,$udom,'userroles',
3616: $typesref,undef,[$cdom]);
3617: my ($tmp) = keys(%roles);
3618: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3619: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3620: if (@course_roles > 0) {
3621: return 1;
3622: }
3623: return 0;
3624: }
3625:
1.478 albertel 3626: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3627: # input: action, courseID, current domain, intended
1.637 raeburn 3628: # path to file, source of file, instruction to parse file for objects,
3629: # ref to hash for embedded objects,
3630: # ref to hash for codebase of java objects.
1.1095 raeburn 3631: # reference to scalar to accommodate mime type determined
3632: # from File::MMagic if $parser = parse.
1.637 raeburn 3633: #
1.485 raeburn 3634: # output: url to file (if action was uploaddoc),
3635: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3636: #
1.478 albertel 3637: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3638: # course.
1.477 raeburn 3639: #
1.478 albertel 3640: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3641: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3642: # course's home server.
1.477 raeburn 3643: #
1.478 albertel 3644: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3645: # be copied from $source (current location) to
3646: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3647: # and will then be copied to
3648: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3649: # course's home server.
1.485 raeburn 3650: #
1.481 raeburn 3651: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3652: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3653: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3654: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3655: # in course's home server.
1.637 raeburn 3656: #
1.477 raeburn 3657:
3658: sub process_coursefile {
1.1095 raeburn 3659: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3660: $mimetype)=@_;
1.477 raeburn 3661: my $fetchresult;
1.638 albertel 3662: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3663: if ($action eq 'propagate') {
1.638 albertel 3664: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3665: $home);
1.481 raeburn 3666: } else {
1.477 raeburn 3667: my $fpath = '';
3668: my $fname = $file;
1.478 albertel 3669: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3670: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3671: my $filepath = &build_filepath($fpath);
1.481 raeburn 3672: if ($action eq 'copy') {
3673: if ($source eq '') {
3674: $fetchresult = 'no source file';
3675: return $fetchresult;
3676: } else {
3677: my $destination = $filepath.'/'.$fname;
3678: rename($source,$destination);
3679: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3680: $home);
1.481 raeburn 3681: }
3682: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3683: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3684: print $fh $env{'form.'.$source};
1.481 raeburn 3685: close($fh);
1.637 raeburn 3686: if ($parser eq 'parse') {
1.1024 raeburn 3687: my $mm = new File::MMagic;
1.1095 raeburn 3688: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3689: if ($type eq 'text/html') {
1.1024 raeburn 3690: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3691: unless ($parse_result eq 'ok') {
3692: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3693: }
1.637 raeburn 3694: }
1.1095 raeburn 3695: if (ref($mimetype)) {
3696: $$mimetype = $type;
3697: }
1.637 raeburn 3698: }
1.477 raeburn 3699: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3700: $home);
1.481 raeburn 3701: if ($fetchresult eq 'ok') {
3702: return '/uploaded/'.$fpath.'/'.$fname;
3703: } else {
3704: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3705: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3706: return '/adm/notfound.html';
3707: }
1.477 raeburn 3708: }
3709: }
1.485 raeburn 3710: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3711: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3712: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3713: }
3714: return $fetchresult;
3715: }
3716:
1.637 raeburn 3717: sub build_filepath {
3718: my ($fpath) = @_;
3719: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3720: unless ($fpath eq '') {
3721: my @parts=split('/',$fpath);
3722: foreach my $part (@parts) {
3723: $filepath.= '/'.$part;
3724: if ((-e $filepath)!=1) {
3725: mkdir($filepath,0777);
3726: }
3727: }
3728: }
3729: return $filepath;
3730: }
3731:
3732: sub store_edited_file {
1.638 albertel 3733: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3734: my $file = $primary_url;
3735: $file =~ s#^/uploaded/$docudom/$docuname/##;
3736: my $fpath = '';
3737: my $fname = $file;
3738: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3739: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3740: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3741: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3742: print $fh $content;
3743: close($fh);
1.638 albertel 3744: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3745: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3746: $home);
1.637 raeburn 3747: if ($$fetchresult eq 'ok') {
3748: return '/uploaded/'.$fpath.'/'.$fname;
3749: } else {
1.638 albertel 3750: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3751: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3752: return '/adm/notfound.html';
3753: }
3754: }
3755:
1.531 albertel 3756: sub clean_filename {
1.831 albertel 3757: my ($fname,$args)=@_;
1.315 www 3758: # Replace Windows backslashes by forward slashes
1.257 www 3759: $fname=~s/\\/\//g;
1.831 albertel 3760: if (!$args->{'keep_path'}) {
3761: # Get rid of everything but the actual filename
3762: $fname=~s/^.*\/([^\/]+)$/$1/;
3763: }
1.315 www 3764: # Replace spaces by underscores
3765: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3766: # Transliterate non-ascii text to ascii
3767: my $lang = &Apache::lonlocal::current_language();
3768: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3769: # Replace all other weird characters by nothing
1.831 albertel 3770: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3771: # Replace all .\d. sequences with _\d. so they no longer look like version
3772: # numbers
3773: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3774: # Replace three or more adjacent underscores with one for consistency
3775: # with loncfile::filename_check() so complete url can be extracted by
3776: # lonnet::decode_symb()
3777: $fname=~s/_{3,}/_/g;
1.531 albertel 3778: return $fname;
3779: }
1.1172.2.110 raeburn 3780:
1.1051 raeburn 3781: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3782: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3783: # image with the same aspect ratio as the original, but with dimensions which do
3784: # not exceed $resizewidth and $resizeheight.
3785:
1.984 neumanie 3786: sub resizeImage {
1.1051 raeburn 3787: my ($img_path,$resizewidth,$resizeheight) = @_;
3788: my $ima = Image::Magick->new;
3789: my $resized;
3790: if (-e $img_path) {
3791: $ima->Read($img_path);
3792: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3793: my $width = $ima->Get('width');
3794: my $height = $ima->Get('height');
3795: if ($width > $resizewidth) {
3796: my $factor = $width/$resizewidth;
3797: my $newheight = $height/$factor;
3798: $ima->Scale(width=>$resizewidth,height=>$newheight);
3799: $resized = 1;
3800: }
3801: }
3802: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3803: my $width = $ima->Get('width');
3804: my $height = $ima->Get('height');
3805: if ($height > $resizeheight) {
3806: my $factor = $height/$resizeheight;
3807: my $newwidth = $width/$factor;
3808: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3809: $resized = 1;
3810: }
3811: }
3812: if ($resized) {
3813: $ima->Write($img_path);
3814: }
3815: }
3816: return;
1.977 amueller 3817: }
3818:
1.608 albertel 3819: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3820: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3821: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3822: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3823: # canceloverwrite, scantron or ''.
1.1090 raeburn 3824: # if 'coursedoc': upload to the current course
3825: # if 'existingfile': write file to tmp/overwrites directory
3826: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3827: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3828: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3829: # $parser - instruction to parse file for objects ($parser = parse) or
3830: # if context is 'scantron', $parser is hashref of csv column mapping
3831: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3832: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3833: # $allfiles - reference to hash for embedded objects
3834: # $codebase - reference to hash for codebase of java objects
3835: # $desuname - username for permanent storage of uploaded file
3836: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3837: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3838: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3839: # $resizewidth - width (pixels) to which to resize uploaded image
3840: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3841: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3842: # from File::MMagic.
1.858 raeburn 3843: #
1.686 albertel 3844: # output: url of file in userspace, or error: <message>
3845: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3846:
1.531 albertel 3847: sub userfileupload {
1.1090 raeburn 3848: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3849: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3850: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3851: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3852: $fname=&clean_filename($fname);
1.1090 raeburn 3853: # See if there is anything left
1.257 www 3854: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3855: # If filename now begins with a . prepend unix timestamp _ milliseconds
3856: if ($fname =~ /^\./) {
3857: my ($s,$usec) = &gettimeofday();
3858: while (length($usec) < 6) {
3859: $usec = '0'.$usec;
3860: }
3861: $fname = $s.'_'.substr($usec,0,3).$fname;
3862: }
1.1090 raeburn 3863: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3864: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3865: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3866: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3867: my $now = time;
1.1090 raeburn 3868: my $filepath;
1.1095 raeburn 3869: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3870: $filepath = 'tmp/helprequests/'.$now;
3871: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3872: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3873: '_'.$env{'user.domain'}.'/pending';
3874: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3875: my ($docuname,$docudom);
1.1172.2.96 raeburn 3876: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3877: $docudom = $destudom;
3878: } else {
3879: $docudom = $env{'user.domain'};
3880: }
1.1172.2.96 raeburn 3881: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3882: $docuname = $destuname;
3883: } else {
3884: $docuname = $env{'user.name'};
3885: }
3886: if (exists($env{'form.group'})) {
3887: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3888: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3889: }
3890: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3891: if ($context eq 'canceloverwrite') {
3892: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3893: if (-e $tempfile) {
3894: my @info = stat($tempfile);
3895: if ($info[9] eq $env{'form.timestamp'}) {
3896: unlink($tempfile);
3897: }
3898: }
3899: return;
1.523 raeburn 3900: }
3901: }
1.1090 raeburn 3902: # Create the directory if not present
1.741 raeburn 3903: my @parts=split(/\//,$filepath);
3904: my $fullpath = $perlvar{'lonDaemons'};
3905: for (my $i=0;$i<@parts;$i++) {
3906: $fullpath .= '/'.$parts[$i];
3907: if ((-e $fullpath)!=1) {
3908: mkdir($fullpath,0777);
3909: }
3910: }
1.1172.2.96 raeburn 3911: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3912: print $fh $env{'form.'.$formname};
3913: close($fh);
1.1090 raeburn 3914: if ($context eq 'existingfile') {
3915: my @info = stat($fullpath.'/'.$fname);
3916: return ($fullpath.'/'.$fname,$info[9]);
3917: } else {
3918: return $fullpath.'/'.$fname;
3919: }
1.523 raeburn 3920: }
1.995 raeburn 3921: if ($subdir eq 'scantron') {
3922: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3923: } else {
1.995 raeburn 3924: $fname="$subdir/$fname";
3925: }
1.1090 raeburn 3926: if ($context eq 'coursedoc') {
1.638 albertel 3927: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3928: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3929: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3930: return &finishuserfileupload($docuname,$docudom,
3931: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3932: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3933: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3934: } else {
1.1172.2.21 raeburn 3935: if ($env{'form.folder'}) {
3936: $fname=$env{'form.folder'}.'/'.$fname;
3937: }
1.638 albertel 3938: return &process_coursefile('uploaddoc',$docuname,$docudom,
3939: $fname,$formname,$parser,
1.1095 raeburn 3940: $allfiles,$codebase,$mimetype);
1.481 raeburn 3941: }
1.719 banghart 3942: } elsif (defined($destuname)) {
3943: my $docuname=$destuname;
3944: my $docudom=$destudom;
1.860 raeburn 3945: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3946: $parser,$allfiles,$codebase,
1.1051 raeburn 3947: $thumbwidth,$thumbheight,
1.1095 raeburn 3948: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3949: } else {
1.638 albertel 3950: my $docuname=$env{'user.name'};
3951: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3952: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3953: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3954: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3955: }
1.860 raeburn 3956: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3957: $parser,$allfiles,$codebase,
1.1051 raeburn 3958: $thumbwidth,$thumbheight,
1.1095 raeburn 3959: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3960: }
1.271 www 3961: }
3962:
3963: sub finishuserfileupload {
1.860 raeburn 3964: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3965: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3966: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3967: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3968:
1.860 raeburn 3969: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3970: $file=$fname;
3971: if ($fname=~m|/|) {
3972: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3973: $path.=$fnamepath.'/';
3974: }
1.259 www 3975: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3976: my $count;
3977: for ($count=4;$count<=$#parts;$count++) {
3978: $filepath.="/$parts[$count]";
3979: if ((-e $filepath)!=1) {
3980: mkdir($filepath,0777);
3981: }
3982: }
1.984 neumanie 3983:
1.258 www 3984: # Save the file
3985: {
1.1172.2.96 raeburn 3986: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3987: &logthis('Failed to create '.$filepath.'/'.$file);
3988: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3989: return '/adm/notfound.html';
3990: }
1.1090 raeburn 3991: if ($context eq 'overwrite') {
1.1117 foxr 3992: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3993: my $target = $filepath.'/'.$file;
3994: if (-e $source) {
3995: my @info = stat($source);
3996: if ($info[9] eq $env{'form.timestamp'}) {
3997: unless (&File::Copy::move($source,$target)) {
3998: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3999: return "Moving from $source failed";
4000: }
4001: } else {
4002: return "Temporary file: $source had unexpected date/time for last modification";
4003: }
4004: } else {
4005: return "Temporary file: $source missing";
4006: }
4007: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4008: &logthis('Failed to write to '.$filepath.'/'.$file);
4009: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4010: return '/adm/notfound.html';
4011: }
1.570 albertel 4012: close(FH);
1.1051 raeburn 4013: if ($resizewidth && $resizeheight) {
4014: my $mm = new File::MMagic;
4015: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4016: if ($mime_type =~ m{^image/}) {
4017: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4018: }
1.977 amueller 4019: }
1.258 www 4020: }
1.1152 raeburn 4021: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4022: if (ref($mimetype)) {
4023: if ($$mimetype eq '') {
4024: my $mm = new File::MMagic;
4025: my $type = $mm->checktype_filename($filepath.'/'.$file);
4026: $$mimetype = $type;
4027: }
4028: }
4029: }
1.1172.2.109 raeburn 4030: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4031: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4032: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4033: $allfiles,$codebase);
4034: unless ($parse_result eq 'ok') {
4035: &logthis('Failed to parse '.$filepath.$file.
4036: ' for embedded media: '.$parse_result);
4037: }
1.637 raeburn 4038: }
1.1172.2.109 raeburn 4039: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4040: my $format = $env{'form.scantron_format'};
4041: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4042: }
1.860 raeburn 4043: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4044: my $input = $filepath.'/'.$file;
4045: my $output = $filepath.'/'.'tn-'.$file;
4046: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4047: my @args = ('convert','-sample',$thumbsize,$input,$output);
4048: system({$args[0]} @args);
1.860 raeburn 4049: if (-e $filepath.'/'.'tn-'.$file) {
4050: $fetchthumb = 1;
4051: }
4052: }
1.858 raeburn 4053:
1.259 www 4054: # Notify homeserver to grep it
4055: #
1.984 neumanie 4056: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4057: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4058: if ($fetchresult eq 'ok') {
1.860 raeburn 4059: if ($fetchthumb) {
4060: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4061: if ($thumbresult ne 'ok') {
4062: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4063: $docuhome.': '.$thumbresult);
4064: }
4065: }
1.259 www 4066: #
1.258 www 4067: # Return the URL to it
1.494 albertel 4068: return '/uploaded/'.$path.$file;
1.263 www 4069: } else {
1.494 albertel 4070: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4071: ': '.$fetchresult);
1.263 www 4072: return '/adm/notfound.html';
1.858 raeburn 4073: }
1.493 albertel 4074: }
4075:
1.637 raeburn 4076: sub extract_embedded_items {
1.961 raeburn 4077: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4078: my @state = ();
1.1164 raeburn 4079: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4080: my %javafiles = (
4081: codebase => '',
4082: code => '',
4083: archive => ''
4084: );
4085: my %mediafiles = (
4086: src => '',
4087: movie => '',
4088: );
1.648 raeburn 4089: my $p;
4090: if ($content) {
4091: $p = HTML::LCParser->new($content);
4092: } else {
1.961 raeburn 4093: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4094: }
1.641 albertel 4095: while (my $t=$p->get_token()) {
1.640 albertel 4096: if ($t->[0] eq 'S') {
4097: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4098: push(@state, $tagname);
1.648 raeburn 4099: if (lc($tagname) eq 'allow') {
4100: &add_filetype($allfiles,$attr->{'src'},'src');
4101: }
1.640 albertel 4102: if (lc($tagname) eq 'img') {
4103: &add_filetype($allfiles,$attr->{'src'},'src');
4104: }
1.886 albertel 4105: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4106: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4107: &add_filetype($allfiles,$attr->{'href'},'href');
4108: }
1.886 albertel 4109: }
1.645 raeburn 4110: if (lc($tagname) eq 'script') {
1.1164 raeburn 4111: my $src;
1.645 raeburn 4112: if ($attr->{'archive'} =~ /\.jar$/i) {
4113: &add_filetype($allfiles,$attr->{'archive'},'archive');
4114: } else {
1.1164 raeburn 4115: if ($attr->{'src'} ne '') {
4116: $src = $attr->{'src'};
4117: &add_filetype($allfiles,$src,'src');
4118: }
4119: }
4120: my $text = $p->get_trimmed_text();
4121: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4122: my @swfargs = split(/,/,$1);
4123: foreach my $item (@swfargs) {
4124: $item =~ s/["']//g;
4125: $item =~ s/^\s+//;
4126: $item =~ s/\s+$//;
4127: }
4128: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4129: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4130: push(@{$related{$swfargs[0]}},$swfargs[2]);
4131: } else {
4132: $related{$swfargs[0]} = [$swfargs[2]];
4133: }
4134: }
1.645 raeburn 4135: }
4136: }
4137: if (lc($tagname) eq 'link') {
4138: if (lc($attr->{'rel'}) eq 'stylesheet') {
4139: &add_filetype($allfiles,$attr->{'href'},'href');
4140: }
4141: }
1.640 albertel 4142: if (lc($tagname) eq 'object' ||
4143: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4144: foreach my $item (keys(%javafiles)) {
4145: $javafiles{$item} = '';
4146: }
1.1164 raeburn 4147: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4148: $lastids{lc($tagname)} = $attr->{'id'};
4149: }
1.640 albertel 4150: }
4151: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4152: my $name = lc($attr->{'name'});
4153: foreach my $item (keys(%javafiles)) {
4154: if ($name eq $item) {
4155: $javafiles{$item} = $attr->{'value'};
4156: last;
4157: }
4158: }
1.1164 raeburn 4159: my $pathfrom;
1.640 albertel 4160: foreach my $item (keys(%mediafiles)) {
4161: if ($name eq $item) {
1.1164 raeburn 4162: $pathfrom = $attr->{'value'};
4163: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4164: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4165: last;
4166: }
4167: }
1.1164 raeburn 4168: if ($name eq 'flashvars') {
4169: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4170: }
4171: if ($pathfrom ne '') {
4172: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4173: $pathfrom);
4174: }
1.640 albertel 4175: }
4176: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4177: foreach my $item (keys(%javafiles)) {
4178: if ($attr->{$item}) {
4179: $javafiles{$item} = $attr->{$item};
4180: last;
4181: }
4182: }
4183: foreach my $item (keys(%mediafiles)) {
4184: if ($attr->{$item}) {
4185: &add_filetype($allfiles,$attr->{$item},$item);
4186: last;
4187: }
4188: }
1.1164 raeburn 4189: if (lc($tagname) eq 'embed') {
4190: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4191: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4192: $attr->{'src'});
4193: }
4194: }
1.640 albertel 4195: }
1.1172.2.35 raeburn 4196: if (lc($tagname) eq 'iframe') {
4197: my $src = $attr->{'src'} ;
4198: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4199: &add_filetype($allfiles,$src,'src');
4200: } elsif ($src =~ m{^/}) {
4201: if ($env{'request.course.id'}) {
4202: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4203: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4204: my $url = &hreflocation('',$fullpath);
4205: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4206: my $relpath = $1;
4207: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4208: &add_filetype($allfiles,$1,'src');
4209: }
4210: }
4211: }
4212: }
4213: }
1.1164 raeburn 4214: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4215: pop(@state);
1.1164 raeburn 4216: }
1.640 albertel 4217: } elsif ($t->[0] eq 'E') {
4218: my ($tagname) = ($t->[1]);
4219: if ($javafiles{'codebase'} ne '') {
4220: $javafiles{'codebase'} .= '/';
4221: }
4222: if (lc($tagname) eq 'applet' ||
4223: lc($tagname) eq 'object' ||
4224: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4225: ) {
4226: foreach my $item (keys(%javafiles)) {
4227: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4228: my $file=$javafiles{'codebase'}.$javafiles{$item};
4229: &add_filetype($allfiles,$file,$item);
4230: }
4231: }
4232: }
4233: pop @state;
4234: }
4235: }
1.1164 raeburn 4236: foreach my $id (sort(keys(%flashvars))) {
4237: if ($shockwave{$id} ne '') {
4238: my @pairs = split(/\&/,$flashvars{$id});
4239: foreach my $pair (@pairs) {
4240: my ($key,$value) = split(/\=/,$pair);
4241: if ($key eq 'thumb') {
4242: &add_filetype($allfiles,$value,$key);
4243: } elsif ($key eq 'content') {
4244: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4245: my ($ext) = ($value =~ /\.([^.]+)$/);
4246: if ($ext ne '') {
4247: &add_filetype($allfiles,$path.$value,$ext);
4248: }
4249: }
4250: }
4251: }
4252: }
1.637 raeburn 4253: return 'ok';
4254: }
4255:
1.639 albertel 4256: sub add_filetype {
4257: my ($allfiles,$file,$type)=@_;
4258: if (exists($allfiles->{$file})) {
4259: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4260: push(@{$allfiles->{$file}}, &escape($type));
4261: }
4262: } else {
4263: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4264: }
4265: }
4266:
1.1164 raeburn 4267: sub embedded_dependency {
4268: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4269: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4270: if (($identifier ne '') &&
4271: (ref($related->{$identifier}) eq 'ARRAY') &&
4272: ($pathfrom ne '')) {
4273: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4274: foreach my $dep (@{$related->{$identifier}}) {
4275: &add_filetype($allfiles,$path.$dep,'object');
4276: }
4277: }
4278: }
4279: return;
4280: }
4281:
1.1172.2.109 raeburn 4282: sub bubblesheet_converter {
4283: my ($cdom,$fullpath,$config,$format) = @_;
4284: if ((&domain($cdom) ne '') &&
4285: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4286: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4287: my (%csvcols,%csvoptions);
4288: if (ref($config->{'fields'}) eq 'HASH') {
4289: %csvcols = %{$config->{'fields'}};
4290: }
4291: if (ref($config->{'options'}) eq 'HASH') {
4292: %csvoptions = %{$config->{'options'}};
4293: }
4294: my %csvbynum = reverse(%csvcols);
4295: my %scantronconf = &get_scantron_config($format,$cdom);
4296: if (keys(%scantronconf)) {
4297: my %bynum = (
4298: $scantronconf{CODEstart} => 'CODEstart',
4299: $scantronconf{IDstart} => 'IDstart',
4300: $scantronconf{PaperID} => 'PaperID',
4301: $scantronconf{FirstName} => 'FirstName',
4302: $scantronconf{LastName} => 'LastName',
4303: $scantronconf{Qstart} => 'Qstart',
4304: );
4305: my @ordered;
4306: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4307: push(@ordered,$bynum{$item});
4308: }
4309: my %mapstart = (
4310: CODEstart => 'CODE',
4311: IDstart => 'ID',
4312: PaperID => 'PaperID',
4313: FirstName => 'FirstName',
4314: LastName => 'LastName',
4315: Qstart => 'FirstQuestion',
4316: );
4317: my %maplength = (
4318: CODEstart => 'CODElength',
4319: IDstart => 'IDlength',
4320: PaperID => 'PaperIDlength',
4321: FirstName => 'FirstNamelength',
4322: LastName => 'LastNamelength',
4323: );
4324: if (open(my $fh,'<',$fullpath)) {
4325: my $output;
4326: my %lettdig = &letter_to_digits();
4327: my %diglett = reverse(%lettdig);
4328: my $numletts = scalar(keys(%lettdig));
4329: my $num = 0;
4330: while (my $line=<$fh>) {
4331: $num ++;
4332: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4333: $line =~ s{[\r\n]+$}{};
4334: my %found;
1.1172.2.143 raeburn 4335: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4336: my ($qstart,$record);
4337: for (my $i=0; $i<@values; $i++) {
4338: if ((($qstart ne '') && ($i > $qstart)) ||
4339: ($csvbynum{$i} eq 'FirstQuestion')) {
4340: if ($values[$i] eq '') {
4341: $values[$i] = $scantronconf{'Qoff'};
4342: } elsif ($scantronconf{'Qon'} eq 'number') {
4343: if ($values[$i] =~ /^[A-Ja-j]$/) {
4344: $values[$i] = $lettdig{uc($values[$i])};
4345: }
4346: } elsif ($scantronconf{'Qon'} eq 'letter') {
4347: if ($values[$i] =~ /^[0-9]$/) {
4348: $values[$i] = $diglett{$values[$i]};
4349: }
4350: } else {
4351: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4352: my $digit;
4353: if ($values[$i] =~ /^[A-Ja-j]$/) {
4354: $digit = $lettdig{uc($values[$i])}-1;
4355: if ($values[$i] eq 'J') {
4356: $digit += $numletts;
4357: }
4358: } elsif ($values[$i] =~ /^[0-9]$/) {
4359: $digit = $values[$i]-1;
4360: if ($values[$i] eq '0') {
4361: $digit += $numletts;
4362: }
4363: }
4364: my $qval='';
4365: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4366: if ($j == $digit) {
4367: $qval .= $scantronconf{'Qon'};
4368: } else {
4369: $qval .= $scantronconf{'Qoff'};
4370: }
4371: }
4372: $values[$i] = $qval;
4373: }
4374: }
4375: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4376: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4377: }
4378: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4379: if ($numblank > 0) {
4380: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4381: }
4382: if ($csvbynum{$i} eq 'FirstQuestion') {
4383: $qstart = $i;
4384: $found{$csvbynum{$i}} = $values[$i];
4385: } else {
4386: $found{'FirstQuestion'} .= $values[$i];
4387: }
4388: } elsif (exists($csvbynum{$i})) {
4389: if ($csvoptions{'rem'}) {
4390: $values[$i] =~ s/^\s+//;
4391: }
4392: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4393: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4394: $values[$i] = '0'.$values[$i];
4395: }
4396: }
4397: $found{$csvbynum{$i}} = $values[$i];
4398: }
4399: }
4400: foreach my $item (@ordered) {
4401: my $currlength = 1+length($record);
4402: my $numspaces = $scantronconf{$item} - $currlength;
4403: if ($numspaces > 0) {
4404: $record .= (' ' x $numspaces);
4405: }
4406: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4407: unless ($item eq 'Qstart') {
4408: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4409: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4410: }
4411: }
4412: $record .= $found{$mapstart{$item}};
4413: }
4414: }
4415: $output .= "$record\n";
4416: }
4417: close($fh);
4418: if ($output) {
4419: if (open(my $fh,'>',$fullpath)) {
4420: print $fh $output;
4421: close($fh);
4422: }
4423: }
4424: }
4425: }
4426: return;
4427: }
4428: }
4429:
4430: sub letter_to_digits {
4431: my %lettdig = (
4432: A => 1,
4433: B => 2,
4434: C => 3,
4435: D => 4,
4436: E => 5,
4437: F => 6,
4438: G => 7,
4439: H => 8,
4440: I => 9,
4441: J => 0,
4442: );
4443: return %lettdig;
4444: }
4445:
4446: sub get_scantron_config {
4447: my ($which,$cdom) = @_;
4448: my @lines = &get_scantronformat_file($cdom);
4449: my %config;
4450: #FIXME probably should move to XML it has already gotten a bit much now
4451: foreach my $line (@lines) {
4452: my ($name,$descrip)=split(/:/,$line);
4453: if ($name ne $which ) { next; }
4454: chomp($line);
4455: my @config=split(/:/,$line);
4456: $config{'name'}=$config[0];
4457: $config{'description'}=$config[1];
4458: $config{'CODElocation'}=$config[2];
4459: $config{'CODEstart'}=$config[3];
4460: $config{'CODElength'}=$config[4];
4461: $config{'IDstart'}=$config[5];
4462: $config{'IDlength'}=$config[6];
4463: $config{'Qstart'}=$config[7];
4464: $config{'Qlength'}=$config[8];
4465: $config{'Qoff'}=$config[9];
4466: $config{'Qon'}=$config[10];
4467: $config{'PaperID'}=$config[11];
4468: $config{'PaperIDlength'}=$config[12];
4469: $config{'FirstName'}=$config[13];
4470: $config{'FirstNamelength'}=$config[14];
4471: $config{'LastName'}=$config[15];
4472: $config{'LastNamelength'}=$config[16];
4473: $config{'BubblesPerRow'}=$config[17];
4474: last;
4475: }
4476: return %config;
4477: }
4478:
4479: sub get_scantronformat_file {
4480: my ($cdom) = @_;
4481: if ($cdom eq '') {
4482: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4483: }
4484: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4485: my $gottab = 0;
4486: my @lines;
4487: if (ref($domconfig{'scantron'}) eq 'HASH') {
4488: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4489: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4490: if ($formatfile ne '-1') {
4491: @lines = split("\n",$formatfile,-1);
4492: $gottab = 1;
4493: }
4494: }
4495: }
4496: if (!$gottab) {
4497: my $confname = $cdom.'-domainconfig';
4498: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4499: my $formatfile = &getfile($default);
4500: if ($formatfile ne '-1') {
4501: @lines = split("\n",$formatfile,-1);
4502: $gottab = 1;
4503: }
4504: }
4505: if (!$gottab) {
4506: my @domains = ¤t_machine_domains();
4507: if (grep(/^\Q$cdom\E$/,@domains)) {
4508: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4509: @lines = <$fh>;
4510: close($fh);
4511: }
4512: } else {
4513: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4514: @lines = <$fh>;
4515: close($fh);
4516: }
4517: }
4518: }
4519: return @lines;
4520: }
4521:
1.493 albertel 4522: sub removeuploadedurl {
1.984 neumanie 4523: my ($url)=@_;
4524: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4525: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4526: }
4527:
4528: sub removeuserfile {
4529: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4530: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4531: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4532: if ($result eq 'ok') {
1.798 raeburn 4533: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4534: my $metafile = $fname.'.meta';
4535: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4536: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4537: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4538: my $sqlresult =
1.823 albertel 4539: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4540: 'portfolio_metadata',$group,
4541: 'delete');
1.798 raeburn 4542: }
4543: }
4544: return $result;
1.257 www 4545: }
1.15 www 4546:
1.530 albertel 4547: sub mkdiruserfile {
4548: my ($docuname,$docudom,$dir)=@_;
4549: my $home=&homeserver($docuname,$docudom);
4550: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4551: }
4552:
1.531 albertel 4553: sub renameuserfile {
4554: my ($docuname,$docudom,$old,$new)=@_;
4555: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4556: my $result = &reply("renameuserfile:$docudom:$docuname:".
4557: &escape("$old").':'.&escape("$new"),$home);
4558: if ($result eq 'ok') {
4559: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4560: my $oldmeta = $old.'.meta';
4561: my $newmeta = $new.'.meta';
4562: my $metaresult =
4563: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4564: my $url = "/uploaded/$docudom/$docuname/$old";
4565: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4566: my $sqlresult =
1.823 albertel 4567: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4568: 'portfolio_metadata',$group,
4569: 'delete');
1.798 raeburn 4570: }
4571: }
4572: return $result;
1.531 albertel 4573: }
4574:
1.14 www 4575: # ------------------------------------------------------------------------- Log
4576:
4577: sub log {
4578: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4579: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4580: }
4581:
4582: # ------------------------------------------------------------------ Course Log
1.352 www 4583: #
4584: # This routine flushes several buffers of non-mission-critical nature
4585: #
1.157 www 4586:
4587: sub flushcourselogs {
1.352 www 4588: &logthis('Flushing log buffers');
4589: #
4590: # course logs
4591: # This is a log of all transactions in a course, which can be used
4592: # for data mining purposes
4593: #
4594: # It also collects the courseid database, which lists last transaction
4595: # times and course titles for all courseids
4596: #
4597: my %courseidbuffer=();
1.921 raeburn 4598: foreach my $crsid (keys(%courselogs)) {
1.352 www 4599: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4600: &escape($courselogs{$crsid}),
4601: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4602: delete $courselogs{$crsid};
4603: } else {
4604: &logthis('Failed to flush log buffer for '.$crsid);
4605: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4606: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4607: " exceeded maximum size, deleting.</font>");
4608: delete $courselogs{$crsid};
4609: }
1.352 www 4610: }
1.920 raeburn 4611: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4612: 'description' => $coursedescrbuf{$crsid},
4613: 'inst_code' => $courseinstcodebuf{$crsid},
4614: 'type' => $coursetypebuf{$crsid},
4615: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4616: };
1.191 harris41 4617: }
1.352 www 4618: #
4619: # Write course id database (reverse lookup) to homeserver of courses
4620: # Is used in pickcourse
4621: #
1.840 albertel 4622: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4623: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4624: $courseidbuffer{$crs_home},
4625: $crs_home,'timeonly');
1.352 www 4626: }
4627: #
4628: # File accesses
4629: # Writes to the dynamic metadata of resources to get hit counts, etc.
4630: #
1.449 matthew 4631: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4632: if ($entry =~ /___count$/) {
4633: my ($dom,$name);
1.807 albertel 4634: ($dom,$name,undef)=
1.811 albertel 4635: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4636: if (! defined($dom) || $dom eq '' ||
4637: ! defined($name) || $name eq '') {
1.620 albertel 4638: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4639: #
4640: # FIXME 11/29/2021
4641: # Typo in rev. 1.458 (2003/12/09)??
4642: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4643: #
4644: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4645: # $dom and $name will always be null, so the &inc() call will default to storing this data
4646: # in a nohist_accesscount.db file for the user rather than the course.
4647: #
4648: # That said there is a lot of noise in the data being stored.
4649: # So counts for prtspool/ and adm/ etc. are recorded.
4650: #
4651: # A review of which items ending '___count' are written to %accesshash should likely be
4652: # made before deciding whether to set these to 'course.' instead of 'request.'
4653: #
4654: # Under the current scheme each user receives a nohist_accesscount.db file listing
4655: # accesses for things which are not published resources, regardless of course, and
4656: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4657: # anyone in the course for things which are not published resources.
4658: #
4659: # For an author, nohist_accesscount.db ends up having records for other items
4660: # mixed up with the legitimate access counts for the author's published resources.
4661: #
1.620 albertel 4662: $dom = $env{'request.'.$cid.'.domain'};
4663: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4664: }
1.450 matthew 4665: my $value = $accesshash{$entry};
4666: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4667: my %temphash=($url => $value);
1.449 matthew 4668: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4669: if ($result eq 'ok') {
4670: delete $accesshash{$entry};
4671: }
4672: } else {
1.811 albertel 4673: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4674: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4675: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4676: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4677: delete $accesshash{$entry};
4678: }
1.185 www 4679: }
1.191 harris41 4680: }
1.352 www 4681: #
4682: # Roles
4683: # Reverse lookup of user roles for course faculty/staff and co-authorship
4684: #
1.800 albertel 4685: foreach my $entry (keys(%userrolehash)) {
1.351 www 4686: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4687: split(/\:/,$entry);
4688: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4689: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4690: $rudom,$runame) eq 'ok') {
4691: delete $userrolehash{$entry};
4692: }
4693: }
1.662 raeburn 4694: #
1.1172.2.90 raeburn 4695: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4696: #
4697: my %domrolebuffer = ();
1.1000 raeburn 4698: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4699: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4700: if ($domrolebuffer{$rudom}) {
4701: $domrolebuffer{$rudom}.='&'.&escape($entry).
4702: '='.&escape($domainrolehash{$entry});
4703: } else {
4704: $domrolebuffer{$rudom}.=&escape($entry).
4705: '='.&escape($domainrolehash{$entry});
4706: }
4707: delete $domainrolehash{$entry};
4708: }
4709: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4710: my %servers;
4711: if (defined(&domain($dom,'primary'))) {
4712: my $primary=&domain($dom,'primary');
4713: my $hostname=&hostname($primary);
4714: $servers{$primary} = $hostname;
4715: } else {
4716: %servers = &get_servers($dom,'library');
4717: }
1.841 albertel 4718: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4719: if (&reply('domroleput:'.$dom.':'.
4720: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4721: last;
4722: } else {
1.841 albertel 4723: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4724: }
1.662 raeburn 4725: }
4726: }
1.186 www 4727: $dumpcount++;
1.157 www 4728: }
4729:
4730: sub courselog {
4731: my $what=shift;
1.158 www 4732: $what=time.':'.$what;
1.620 albertel 4733: unless ($env{'request.course.id'}) { return ''; }
4734: $coursedombuf{$env{'request.course.id'}}=
4735: $env{'course.'.$env{'request.course.id'}.'.domain'};
4736: $coursenumbuf{$env{'request.course.id'}}=
4737: $env{'course.'.$env{'request.course.id'}.'.num'};
4738: $coursehombuf{$env{'request.course.id'}}=
4739: $env{'course.'.$env{'request.course.id'}.'.home'};
4740: $coursedescrbuf{$env{'request.course.id'}}=
4741: $env{'course.'.$env{'request.course.id'}.'.description'};
4742: $courseinstcodebuf{$env{'request.course.id'}}=
4743: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4744: $courseownerbuf{$env{'request.course.id'}}=
4745: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4746: $coursetypebuf{$env{'request.course.id'}}=
4747: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4748: if (defined $courselogs{$env{'request.course.id'}}) {
4749: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4750: } else {
1.620 albertel 4751: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4752: }
1.620 albertel 4753: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4754: &flushcourselogs();
4755: }
1.158 www 4756: }
4757:
4758: sub courseacclog {
4759: my $fnsymb=shift;
1.620 albertel 4760: unless ($env{'request.course.id'}) { return ''; }
4761: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4762: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4763: $what.=':POST';
1.583 matthew 4764: # FIXME: Probably ought to escape things....
1.800 albertel 4765: foreach my $key (keys(%env)) {
4766: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4767: my $formitem = $1;
4768: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4769: $what.=':'.$formitem.'='.$env{$key};
4770: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4771: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4772: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4773: } else {
4774: $what.=':'.$formitem.'='.$env{$key};
4775: }
1.975 raeburn 4776: }
1.158 www 4777: }
1.191 harris41 4778: }
1.583 matthew 4779: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4780: # FIXME: We should not be depending on a form parameter that someone
4781: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4782: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4783: $what.= ':POST';
4784: # FIXME: Probably ought to escape things....
4785: foreach my $element ('courseexp','crsfulltext','crsrelated',
4786: 'crsdiscuss') {
1.620 albertel 4787: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4788: }
4789: }
1.158 www 4790: }
4791: &courselog($what);
1.149 www 4792: }
4793:
1.185 www 4794: sub countacc {
4795: my $url=&declutter(shift);
1.458 matthew 4796: return if (! defined($url) || $url eq '');
1.620 albertel 4797: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4798: #
4799: # Mark that this url was used in this course
4800: #
1.620 albertel 4801: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4802: #
4803: # Increase the access count for this resource in this child process
4804: #
1.281 www 4805: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4806: $accesshash{$key}++;
1.185 www 4807: }
1.349 www 4808:
1.361 www 4809: sub linklog {
4810: my ($from,$to)=@_;
4811: $from=&declutter($from);
4812: $to=&declutter($to);
4813: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4814: $accesshash{$to.'___'.$from.'___goto'}=1;
4815: }
1.1160 www 4816:
4817: sub statslog {
4818: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4819: if ($users<2) { return; }
4820: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4821: 'course' => $env{'request.course.id'},
4822: 'sections' => '"all"',
4823: 'num_students' => $users,
4824: 'part' => $part,
4825: 'symb' => $symb,
4826: 'mean_tries' => $av_attempts,
4827: 'deg_of_diff' => $degdiff});
4828: foreach my $key (keys(%dynstore)) {
4829: $accesshash{$key}=$dynstore{$key};
4830: }
4831: }
1.361 www 4832:
1.349 www 4833: sub userrolelog {
4834: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4835: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4836: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4837: $userrolehash
4838: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4839: =$tend.':'.$tstart;
1.662 raeburn 4840: }
1.1169 droeschl 4841: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4842: $userrolehash
4843: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4844: =$tend.':'.$tstart;
4845: }
1.1172.2.90 raeburn 4846: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4847: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4848: $domainrolehash
4849: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4850: = $tend.':'.$tstart;
4851: }
1.351 www 4852: }
4853:
1.957 raeburn 4854: sub courserolelog {
4855: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4856: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4857: my $cdom = $1;
4858: my $cnum = $2;
4859: my $sec = $3;
4860: my $namespace = 'rolelog';
4861: my %storehash = (
4862: role => $trole,
4863: start => $tstart,
4864: end => $tend,
4865: selfenroll => $selfenroll,
4866: context => $context,
4867: );
4868: if ($trole eq 'gr') {
4869: $namespace = 'groupslog';
4870: $storehash{'group'} = $sec;
4871: } else {
4872: $storehash{'section'} = $sec;
4873: }
4874: &write_log('course',$namespace,\%storehash,$delflag,$username,
4875: $domain,$cnum,$cdom);
4876: if (($trole ne 'st') || ($sec ne '')) {
4877: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4878: }
4879: }
4880: return;
4881: }
4882:
1.1172.2.9 raeburn 4883: sub domainrolelog {
4884: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4885: if ($area =~ m{^/($match_domain)/$}) {
4886: my $cdom = $1;
4887: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4888: my $namespace = 'rolelog';
4889: my %storehash = (
4890: role => $trole,
4891: start => $tstart,
4892: end => $tend,
4893: context => $context,
4894: );
4895: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4896: $domain,$domconfiguser,$cdom);
4897: }
4898: return;
4899:
4900: }
4901:
4902: sub coauthorrolelog {
4903: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4904: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4905: my $audom = $1;
4906: my $auname = $2;
4907: my $namespace = 'rolelog';
4908: my %storehash = (
4909: role => $trole,
4910: start => $tstart,
4911: end => $tend,
4912: context => $context,
4913: );
4914: &write_log('author',$namespace,\%storehash,$delflag,$username,
4915: $domain,$auname,$audom);
4916: }
4917: return;
4918: }
4919:
1.351 www 4920: sub get_course_adv_roles {
1.948 raeburn 4921: my ($cid,$codes) = @_;
1.620 albertel 4922: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4923: my %coursehash=&coursedescription($cid);
1.988 raeburn 4924: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4925: my %nothide=();
1.800 albertel 4926: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4927: if ($user !~ /:/) {
4928: $nothide{join(':',split(/[\@]/,$user))}=1;
4929: } else {
4930: $nothide{$user}=1;
4931: }
1.470 www 4932: }
1.1172.2.23 raeburn 4933: my @possdoms = ($coursehash{'domain'});
4934: if ($coursehash{'checkforpriv'}) {
4935: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4936: }
1.351 www 4937: my %returnhash=();
4938: my %dumphash=
4939: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4940: my $now=time;
1.997 raeburn 4941: my %privileged;
1.1000 raeburn 4942: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4943: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4944: if (($tstart) && ($tstart<0)) { next; }
4945: if (($tend) && ($tend<$now)) { next; }
4946: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4947: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4948: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4949: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4950: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4951: if ($role eq 'cr') { next; }
1.948 raeburn 4952: if ($codes) {
4953: if ($section) { $role .= ':'.$section; }
4954: if ($returnhash{$role}) {
4955: $returnhash{$role}.=','.$username.':'.$domain;
4956: } else {
4957: $returnhash{$role}=$username.':'.$domain;
4958: }
1.351 www 4959: } else {
1.988 raeburn 4960: my $key=&plaintext($role,$crstype);
1.973 bisitz 4961: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4962: if ($returnhash{$key}) {
4963: $returnhash{$key}.=','.$username.':'.$domain;
4964: } else {
4965: $returnhash{$key}=$username.':'.$domain;
4966: }
1.351 www 4967: }
1.948 raeburn 4968: }
1.400 www 4969: return %returnhash;
4970: }
4971:
4972: sub get_my_roles {
1.937 raeburn 4973: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4974: unless (defined($uname)) { $uname=$env{'user.name'}; }
4975: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4976: my (%dumphash,%nothide);
1.1086 raeburn 4977: if ($context eq 'userroles') {
1.1166 raeburn 4978: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4979: } else {
1.1172.2.23 raeburn 4980: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4981: if ($hidepriv) {
4982: my %coursehash=&coursedescription($udom.'_'.$uname);
4983: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4984: if ($user !~ /:/) {
4985: $nothide{join(':',split(/[\@]/,$user))} = 1;
4986: } else {
4987: $nothide{$user} = 1;
4988: }
4989: }
4990: }
1.858 raeburn 4991: }
1.400 www 4992: my %returnhash=();
4993: my $now=time;
1.999 raeburn 4994: my %privileged;
1.800 albertel 4995: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4996: my ($role,$tend,$tstart);
4997: if ($context eq 'userroles') {
1.1149 raeburn 4998: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4999: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5000: } else {
5001: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5002: }
1.400 www 5003: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5004: my $status = 'active';
1.939 raeburn 5005: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5006: $status = 'previous';
5007: }
5008: if (($tstart) && ($now<$tstart)) {
5009: $status = 'future';
5010: }
5011: if (ref($types) eq 'ARRAY') {
5012: if (!grep(/^\Q$status\E$/,@{$types})) {
5013: next;
5014: }
5015: } else {
5016: if ($status ne 'active') {
5017: next;
5018: }
5019: }
1.867 raeburn 5020: my ($rolecode,$username,$domain,$section,$area);
5021: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5022: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5023: (undef,$domain,$username,$section) = split(/\//,$area);
5024: } else {
5025: ($role,$username,$domain,$section) = split(/\:/,$entry);
5026: }
1.832 raeburn 5027: if (ref($roledoms) eq 'ARRAY') {
5028: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5029: next;
5030: }
5031: }
5032: if (ref($roles) eq 'ARRAY') {
5033: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5034: if ($role =~ /^cr\//) {
5035: if (!grep(/^cr$/,@{$roles})) {
5036: next;
5037: }
1.1104 raeburn 5038: } elsif ($role =~ /^gr\//) {
5039: if (!grep(/^gr$/,@{$roles})) {
5040: next;
5041: }
1.922 raeburn 5042: } else {
5043: next;
5044: }
1.832 raeburn 5045: }
1.867 raeburn 5046: }
1.937 raeburn 5047: if ($hidepriv) {
1.1172.2.23 raeburn 5048: my @privroles = ('dc','su');
1.999 raeburn 5049: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5050: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5051: } else {
1.1172.2.23 raeburn 5052: my $possdoms = [$domain];
5053: if (ref($roledoms) eq 'ARRAY') {
5054: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5055: }
1.1172.2.23 raeburn 5056: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5057: if (!$nothide{$username.':'.$domain}) {
5058: next;
5059: }
5060: }
1.937 raeburn 5061: }
5062: }
1.933 raeburn 5063: if ($withsec) {
5064: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5065: $tstart.':'.$tend;
5066: } else {
5067: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5068: }
1.832 raeburn 5069: }
1.373 www 5070: return %returnhash;
1.399 www 5071: }
5072:
1.1172.2.89 raeburn 5073: sub get_all_adhocroles {
5074: my ($dom) = @_;
5075: my @roles_by_num = ();
5076: my %domdefaults = &get_domain_defaults($dom);
5077: my (%description,%access_in_dom,%access_info);
5078: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5079: my $count = 0;
5080: my %domcurrent = %{$domdefaults{'adhocroles'}};
5081: my %ordered;
5082: foreach my $role (sort(keys(%domcurrent))) {
5083: my ($order,$desc,$access_in_dom);
5084: if (ref($domcurrent{$role}) eq 'HASH') {
5085: $order = $domcurrent{$role}{'order'};
5086: $desc = $domcurrent{$role}{'desc'};
5087: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5088: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5089: }
5090: if ($order eq '') {
5091: $order = $count;
5092: }
5093: $ordered{$order} = $role;
5094: if ($desc ne '') {
5095: $description{$role} = $desc;
5096: } else {
5097: $description{$role}= $role;
5098: }
5099: $count++;
5100: }
5101: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5102: push(@roles_by_num,$ordered{$item});
5103: }
5104: }
5105: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5106: }
5107:
5108: sub get_my_adhocroles {
5109: my ($cid,$checkreg) = @_;
5110: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5111: if ($env{'request.course.id'} eq $cid) {
5112: $cdom = $env{'course.'.$cid.'.domain'};
5113: $cnum = $env{'course.'.$cid.'.num'};
5114: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5115: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5116: $cdom = $1;
5117: $cnum = $2;
5118: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5119: $cdom,$cnum);
5120: }
5121: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5122: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5123: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5124: if ($rosterhash{$user} ne '') {
5125: my $type = (split(/:/,$rosterhash{$user}))[5];
5126: return ([],{}) if ($type eq 'auto');
5127: }
5128: }
5129: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5130: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5131: my $then=$env{'user.login.time'};
5132: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5133: if (!$update) {
5134: $update = $then;
5135: }
5136: my @liveroles;
5137: foreach my $role ('dh','da') {
5138: if ($env{"user.role.$role./$cdom/"}) {
5139: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5140: my $limit = $update;
5141: if ($env{'request.role'} eq "$role./$cdom/") {
5142: $limit = $then;
5143: }
5144: my $activerole = 1;
5145: if ($tstart && $tstart>$limit) { $activerole = 0; }
5146: if ($tend && $tend <$limit) { $activerole = 0; }
5147: if ($activerole) {
5148: push(@liveroles,$role);
5149: }
5150: }
5151: }
5152: if (@liveroles) {
1.1172.2.89 raeburn 5153: if (&homeserver($cnum,$cdom) ne 'no_host') {
5154: my ($accessref,$accessinfo,%access_in_dom);
5155: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5156: if (ref($roles_by_num) eq 'ARRAY') {
5157: if (@{$roles_by_num}) {
5158: my %settings;
5159: if ($env{'request.course.id'} eq $cid) {
5160: foreach my $envkey (keys(%env)) {
5161: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5162: $settings{$1} = $env{$envkey};
5163: }
5164: }
5165: } else {
5166: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5167: }
5168: my %setincrs;
5169: if ($settings{'internal.adhocaccess'}) {
5170: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5171: }
5172: my @statuses;
5173: if ($env{'environment.inststatus'}) {
5174: @statuses = split(/,/,$env{'environment.inststatus'});
5175: }
5176: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5177: if (ref($accessref) eq 'HASH') {
5178: %access_in_dom = %{$accessref};
5179: }
5180: foreach my $role (@{$roles_by_num}) {
5181: my ($curraccess,@okstatus,@personnel);
5182: if ($setincrs{$role}) {
5183: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5184: if ($curraccess eq 'status') {
5185: @okstatus = split(/\&/,$rest);
5186: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5187: @personnel = split(/\&/,$rest);
5188: }
5189: } else {
5190: $curraccess = $access_in_dom{$role};
5191: if (ref($accessinfo) eq 'HASH') {
5192: if ($curraccess eq 'status') {
5193: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5194: @okstatus = @{$accessinfo->{$role}};
5195: }
5196: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5197: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5198: @personnel = @{$accessinfo->{$role}};
5199: }
5200: }
5201: }
5202: }
5203: if ($curraccess eq 'none') {
5204: next;
5205: } elsif ($curraccess eq 'all') {
5206: push(@possroles,$role);
1.1172.2.90 raeburn 5207: } elsif ($curraccess eq 'dh') {
5208: if (grep(/^dh$/,@liveroles)) {
5209: push(@possroles,$role);
5210: } else {
5211: next;
5212: }
5213: } elsif ($curraccess eq 'da') {
5214: if (grep(/^da$/,@liveroles)) {
5215: push(@possroles,$role);
5216: } else {
5217: next;
5218: }
1.1172.2.89 raeburn 5219: } elsif ($curraccess eq 'status') {
5220: if (@okstatus) {
5221: if (!@statuses) {
5222: if (grep(/^default$/,@okstatus)) {
5223: push(@possroles,$role);
5224: }
5225: } else {
5226: foreach my $status (@okstatus) {
5227: if (grep(/^\Q$status\E$/,@statuses)) {
5228: push(@possroles,$role);
5229: last;
5230: }
5231: }
5232: }
5233: }
5234: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5235: if (grep(/^\Q$user\E$/,@personnel)) {
5236: if ($curraccess eq 'exc') {
5237: push(@possroles,$role);
5238: }
5239: } elsif ($curraccess eq 'inc') {
5240: push(@possroles,$role);
5241: }
5242: }
5243: }
5244: }
5245: }
5246: }
5247: }
5248: }
5249: }
5250: unless (ref($description) eq 'HASH') {
5251: if (ref($roles_by_num) eq 'ARRAY') {
5252: my %desc;
5253: map { $desc{$_} = $_; } (@{$roles_by_num});
5254: $description = \%desc;
5255: } else {
5256: $description = {};
5257: }
5258: }
5259: return (\@possroles,$description);
5260: }
5261:
1.399 www 5262: # ----------------------------------------------------- Frontpage Announcements
5263: #
5264: #
5265:
5266: sub postannounce {
5267: my ($server,$text)=@_;
1.844 albertel 5268: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5269: unless ($text=~/\w/) { $text=''; }
5270: return &reply('setannounce:'.&escape($text),$server);
5271: }
5272:
5273: sub getannounce {
1.448 albertel 5274:
1.1172.2.96 raeburn 5275: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5276: my $announcement='';
1.800 albertel 5277: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5278: close($fh);
1.399 www 5279: if ($announcement=~/\w/) {
5280: return
5281: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5282: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5283: } else {
5284: return '';
5285: }
5286: } else {
5287: return '';
5288: }
1.351 www 5289: }
1.353 www 5290:
5291: # ---------------------------------------------------------- Course ID routines
5292: # Deal with domain's nohist_courseid.db files
5293: #
5294:
5295: sub courseidput {
1.921 raeburn 5296: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5297: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5298: my $outcome;
5299: if ($caller eq 'timeonly') {
5300: my $cids = '';
5301: foreach my $item (keys(%$storehash)) {
5302: $cids.=&escape($item).'&';
5303: }
5304: $cids=~s/\&$//;
5305: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5306: $coursehome);
5307: } else {
5308: my $items = '';
5309: foreach my $item (keys(%$storehash)) {
5310: $items.= &escape($item).'='.
5311: &freeze_escape($$storehash{$item}).'&';
5312: }
5313: $items=~s/\&$//;
5314: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5315: $coursehome);
1.918 raeburn 5316: }
5317: if ($outcome eq 'unknown_cmd') {
5318: my $what;
5319: foreach my $cid (keys(%$storehash)) {
5320: $what .= &escape($cid).'=';
1.921 raeburn 5321: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5322: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5323: }
5324: $what =~ s/\:$/&/;
5325: }
5326: $what =~ s/\&$//;
5327: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5328: } else {
5329: return $outcome;
5330: }
1.353 www 5331: }
5332:
5333: sub courseiddump {
1.921 raeburn 5334: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5335: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5336: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5337: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5338: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5339: my $as_hash = 1;
5340: my %returnhash;
5341: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5342: my %libserv = &all_library();
5343: foreach my $tryserver (keys(%libserv)) {
5344: if ( ( $hostidflag == 1
5345: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5346: || (!defined($hostidflag)) ) {
5347:
1.918 raeburn 5348: if (($domfilter eq '') ||
5349: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5350: my $rep;
5351: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5352: $rep = &LONCAPA::Lond::dump_course_id_handler(
5353: join(":", (&host_domain($tryserver), $sincefilter,
5354: &escape($descfilter), &escape($instcodefilter),
5355: &escape($ownerfilter), &escape($coursefilter),
5356: &escape($typefilter), &escape($regexp_ok),
5357: $as_hash, &escape($selfenrollonly),
5358: &escape($catfilter), $showhidden, $caller,
5359: &escape($cloner), &escape($cc_clone), $cloneonly,
5360: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5361: &escape($creationcontext),$domcloner,$hasuniquecode,
5362: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5363: } else {
5364: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5365: $sincefilter.':'.&escape($descfilter).':'.
5366: &escape($instcodefilter).':'.&escape($ownerfilter).
5367: ':'.&escape($coursefilter).':'.&escape($typefilter).
5368: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5369: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5370: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5371: &escape($cc_clone).':'.$cloneonly.':'.
5372: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5373: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5374: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5375: }
5376:
1.918 raeburn 5377: my @pairs=split(/\&/,$rep);
5378: foreach my $item (@pairs) {
5379: my ($key,$value)=split(/\=/,$item,2);
5380: $key = &unescape($key);
5381: next if ($key =~ /^error: 2 /);
5382: my $result = &thaw_unescape($value);
5383: if (ref($result) eq 'HASH') {
5384: $returnhash{$key}=$result;
5385: } else {
1.921 raeburn 5386: my @responses = split(/:/,$value);
5387: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5388: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5389: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5390: }
1.1008 raeburn 5391: }
1.353 www 5392: }
5393: }
5394: }
5395: }
5396: return %returnhash;
5397: }
5398:
1.1055 raeburn 5399: sub courselastaccess {
5400: my ($cdom,$cnum,$hostidref) = @_;
5401: my %returnhash;
5402: if ($cdom && $cnum) {
5403: my $chome = &homeserver($cnum,$cdom);
5404: if ($chome ne 'no_host') {
5405: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5406: &extract_lastaccess(\%returnhash,$rep);
5407: }
5408: } else {
5409: if (!$cdom) { $cdom=''; }
5410: my %libserv = &all_library();
5411: foreach my $tryserver (keys(%libserv)) {
5412: if (ref($hostidref) eq 'ARRAY') {
5413: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5414: }
5415: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5416: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5417: &extract_lastaccess(\%returnhash,$rep);
5418: }
5419: }
5420: }
5421: return %returnhash;
5422: }
5423:
5424: sub extract_lastaccess {
5425: my ($returnhash,$rep) = @_;
5426: if (ref($returnhash) eq 'HASH') {
5427: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5428: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5429: $rep eq '') {
5430: my @pairs=split(/\&/,$rep);
5431: foreach my $item (@pairs) {
5432: my ($key,$value)=split(/\=/,$item,2);
5433: $key = &unescape($key);
5434: next if ($key =~ /^error: 2 /);
5435: $returnhash->{$key} = &thaw_unescape($value);
5436: }
5437: }
5438: }
5439: return;
5440: }
5441:
1.658 raeburn 5442: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5443:
5444: sub dcmailput {
1.685 raeburn 5445: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5446: my $status = &Apache::lonnet::critical(
1.740 www 5447: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5448: &escape($message),$server);
1.662 raeburn 5449: return $status;
5450: }
5451:
1.658 raeburn 5452: sub dcmaildump {
5453: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5454: my %returnhash=();
1.846 albertel 5455:
5456: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5457: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5458: &escape($enddate).':';
5459: my @esc_senders=map { &escape($_)} @$senders;
5460: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5461: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5462: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5463: if (($key) && ($value)) {
5464: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5465: }
5466: }
5467: }
5468: return %returnhash;
5469: }
1.662 raeburn 5470: # ---------------------------------------------------------- Domain roles
5471:
5472: sub get_domain_roles {
5473: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5474: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5475: $startdate = '.';
5476: }
1.1018 raeburn 5477: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5478: $enddate = '.';
5479: }
1.922 raeburn 5480: my $rolelist;
5481: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5482: $rolelist = join('&',@{$roles});
1.922 raeburn 5483: }
1.662 raeburn 5484: my %personnel = ();
1.841 albertel 5485:
5486: my %servers = &get_servers($dom,'library');
5487: foreach my $tryserver (keys(%servers)) {
5488: %{$personnel{$tryserver}}=();
5489: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5490: &escape($startdate).':'.
5491: &escape($enddate).':'.
5492: &escape($rolelist), $tryserver))) {
5493: my ($key,$value) = split(/\=/,$line,2);
5494: if (($key) && ($value)) {
5495: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5496: }
5497: }
1.662 raeburn 5498: }
5499: return %personnel;
5500: }
1.658 raeburn 5501:
1.1172.2.89 raeburn 5502: sub get_active_domroles {
5503: my ($dom,$roles) = @_;
5504: return () unless (ref($roles) eq 'ARRAY');
5505: my $now = time;
5506: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5507: my %domroles;
5508: foreach my $server (keys(%dompersonnel)) {
5509: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5510: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5511: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5512: }
5513: }
5514: return %domroles;
5515: }
5516:
1.1057 www 5517: # ----------------------------------------------------------- Interval timing
1.149 www 5518:
1.1153 www 5519: {
5520: # Caches needed for speedup of navmaps
5521: # We don't want to cache this for very long at all (5 seconds at most)
5522: #
5523: # The user for whom we cache
5524: my $cachedkey='';
5525: # The cached times for this user
5526: my %cachedtimes=();
5527: # When this was last done
1.1172.2.66 raeburn 5528: my $cachedtime='';
1.1153 www 5529:
5530: sub load_all_first_access {
1.1154 raeburn 5531: my ($uname,$udom)=@_;
1.1156 www 5532: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5533: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5534: return;
5535: }
5536: $cachedtime=time;
5537: $cachedkey=$uname.':'.$udom;
5538: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5539: }
5540:
1.504 albertel 5541: sub get_first_access {
1.1162 raeburn 5542: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5543: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5544: if ($argsymb) { $symb=$argsymb; }
5545: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5546: if ($argmap) { $map = $argmap; }
1.926 albertel 5547: if ($type eq 'course') {
5548: $res='course';
5549: } elsif ($type eq 'map') {
1.588 albertel 5550: $res=&symbread($map);
5551: } else {
5552: $res=$symb;
5553: }
1.1153 www 5554: &load_all_first_access($uname,$udom);
5555: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5556: }
5557:
5558: sub set_first_access {
1.1162 raeburn 5559: my ($type,$interval)=@_;
1.790 albertel 5560: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5561: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5562: if ($type eq 'course') {
5563: $res='course';
5564: } elsif ($type eq 'map') {
1.588 albertel 5565: $res=&symbread($map);
5566: } else {
5567: $res=$symb;
5568: }
1.1153 www 5569: $cachedkey='';
1.1162 raeburn 5570: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5571: if ($firstaccess) {
5572: &logthis("First access time already set ($firstaccess) when attempting ".
5573: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5574: "in $courseid");
5575: return 'already_set';
5576: } else {
1.1162 raeburn 5577: my $start = time;
5578: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5579: $udom,$uname);
5580: if ($putres eq 'ok') {
5581: &put('timerinterval',{"$courseid\0$res"=>$interval},
5582: $udom,$uname);
5583: &appenv(
5584: {
5585: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5586: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5587: }
5588: );
1.1172.2.97 raeburn 5589: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5590: $cachedtimes{"$courseid\0$res"} = $start;
5591: }
1.1172.2.102 raeburn 5592: } elsif ($putres ne 'refused') {
5593: &logthis("Result: $putres when attempting to set first access time ".
5594: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5595: }
5596: return $putres;
1.505 albertel 5597: }
5598: return 'already_set';
1.504 albertel 5599: }
1.1153 www 5600: }
1.1172.2.32 raeburn 5601:
5602: sub checkout {
5603: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5604: my $now=time;
5605: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5606: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5607: my $infostr=&escape(
5608: 'CHECKOUTTOKEN&'.
5609: $tuname.'&'.
5610: $tudom.'&'.
5611: $tcrsid.'&'.
5612: $symb.'&'.
1.1172.2.134 raeburn 5613: $now.'&'.$ip);
1.1172.2.32 raeburn 5614: my $token=&reply('tmpput:'.$infostr,$lonhost);
5615: if ($token=~/^error\:/) {
5616: &logthis("<font color=\"blue\">WARNING: ".
5617: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5618: "</font>");
5619: return '';
5620: }
5621:
5622: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5623: $token=~tr/a-z/A-Z/;
5624:
5625: my %infohash=('resource.0.outtoken' => $token,
5626: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5627: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5628:
5629: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5630: return '';
5631: } else {
5632: &logthis("<font color=\"blue\">WARNING: ".
5633: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5634: "</font>");
5635: }
5636:
5637: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5638: &escape('Checkout '.$infostr.' - '.
5639: $token)) ne 'ok') {
5640: return '';
5641: } else {
5642: &logthis("<font color=\"blue\">WARNING: ".
5643: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5644: "</font>");
5645: }
5646: return $token;
5647: }
5648:
5649: # ------------------------------------------------------------ Check in an item
5650:
5651: sub checkin {
5652: my $token=shift;
5653: my $now=time;
5654: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5655: $lonhost=~tr/A-Z/a-z/;
5656: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5657: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5658: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5659: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5660: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5661:
5662: unless (($tuname) && ($tudom)) {
5663: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5664: return '';
5665: }
5666:
5667: unless (&allowed('mgr',$tcrsid)) {
5668: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5669: $env{'user.name'}.' - '.$env{'user.domain'});
5670: return '';
5671: }
5672:
5673: my %infohash=('resource.0.intoken' => $token,
5674: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5675: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5676:
5677: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5678: return '';
5679: }
5680:
5681: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5682: &escape('Checkin - '.$token)) ne 'ok') {
5683: return '';
5684: }
5685:
5686: return ($symb,$tuname,$tudom,$tcrsid);
5687: }
5688:
1.110 www 5689: # --------------------------------------------- Set Expire Date for Spreadsheet
5690:
5691: sub expirespread {
5692: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5693: my $cid=$env{'request.course.id'};
1.110 www 5694: if ($cid) {
5695: my $now=time;
5696: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5697: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5698: $env{'course.'.$cid.'.num'}.
1.110 www 5699: ':nohist_expirationdates:'.
5700: &escape($key).'='.$now,
1.620 albertel 5701: $env{'course.'.$cid.'.home'})
1.110 www 5702: }
5703: return 'ok';
1.14 www 5704: }
5705:
1.109 www 5706: # ----------------------------------------------------- Devalidate Spreadsheets
5707:
5708: sub devalidate {
1.325 www 5709: my ($symb,$uname,$udom)=@_;
1.620 albertel 5710: my $cid=$env{'request.course.id'};
1.109 www 5711: if ($cid) {
1.391 matthew 5712: # delete the stored spreadsheets for
5713: # - the student level sheet of this user in course's homespace
5714: # - the assessment level sheet for this resource
5715: # for this user in user's homespace
1.553 albertel 5716: # - current conditional state info
1.325 www 5717: my $key=$uname.':'.$udom.':';
1.109 www 5718: my $status=
1.299 matthew 5719: &del('nohist_calculatedsheets',
1.391 matthew 5720: [$key.'studentcalc:'],
1.620 albertel 5721: $env{'course.'.$cid.'.domain'},
5722: $env{'course.'.$cid.'.num'})
1.133 albertel 5723: .' '.
5724: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5725: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5726: unless ($status eq 'ok ok') {
5727: &logthis('Could not devalidate spreadsheet '.
1.325 www 5728: $uname.' at '.$udom.' for '.
1.109 www 5729: $symb.': '.$status);
1.133 albertel 5730: }
1.553 albertel 5731: &delenv('user.state.'.$cid);
1.109 www 5732: }
5733: }
5734:
1.265 albertel 5735: sub get_scalar {
5736: my ($string,$end) = @_;
5737: my $value;
5738: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5739: $value = $1;
5740: } elsif ($$string =~ s/^([^&]*?)&//) {
5741: $value = $1;
5742: }
5743: return &unescape($value);
5744: }
5745:
5746: sub array2str {
5747: my (@array) = @_;
5748: my $result=&arrayref2str(\@array);
5749: $result=~s/^__ARRAY_REF__//;
5750: $result=~s/__END_ARRAY_REF__$//;
5751: return $result;
5752: }
5753:
1.204 albertel 5754: sub arrayref2str {
5755: my ($arrayref) = @_;
1.265 albertel 5756: my $result='__ARRAY_REF__';
1.204 albertel 5757: foreach my $elem (@$arrayref) {
1.265 albertel 5758: if(ref($elem) eq 'ARRAY') {
5759: $result.=&arrayref2str($elem).'&';
5760: } elsif(ref($elem) eq 'HASH') {
5761: $result.=&hashref2str($elem).'&';
5762: } elsif(ref($elem)) {
5763: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5764: } else {
5765: $result.=&escape($elem).'&';
5766: }
5767: }
5768: $result=~s/\&$//;
1.265 albertel 5769: $result .= '__END_ARRAY_REF__';
1.204 albertel 5770: return $result;
5771: }
5772:
1.168 albertel 5773: sub hash2str {
1.204 albertel 5774: my (%hash) = @_;
5775: my $result=&hashref2str(\%hash);
1.265 albertel 5776: $result=~s/^__HASH_REF__//;
5777: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5778: return $result;
5779: }
5780:
5781: sub hashref2str {
5782: my ($hashref)=@_;
1.265 albertel 5783: my $result='__HASH_REF__';
1.800 albertel 5784: foreach my $key (sort(keys(%$hashref))) {
5785: if (ref($key) eq 'ARRAY') {
5786: $result.=&arrayref2str($key).'=';
5787: } elsif (ref($key) eq 'HASH') {
5788: $result.=&hashref2str($key).'=';
5789: } elsif (ref($key)) {
1.265 albertel 5790: $result.='=';
1.800 albertel 5791: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5792: } else {
1.1132 raeburn 5793: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5794: }
5795:
1.800 albertel 5796: if(ref($hashref->{$key}) eq 'ARRAY') {
5797: $result.=&arrayref2str($hashref->{$key}).'&';
5798: } elsif(ref($hashref->{$key}) eq 'HASH') {
5799: $result.=&hashref2str($hashref->{$key}).'&';
5800: } elsif(ref($hashref->{$key})) {
1.265 albertel 5801: $result.='&';
1.800 albertel 5802: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5803: } else {
1.800 albertel 5804: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5805: }
5806: }
1.168 albertel 5807: $result=~s/\&$//;
1.265 albertel 5808: $result .= '__END_HASH_REF__';
1.168 albertel 5809: return $result;
5810: }
5811:
5812: sub str2hash {
1.265 albertel 5813: my ($string)=@_;
5814: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5815: return %$hash;
5816: }
5817:
5818: sub str2hashref {
1.168 albertel 5819: my ($string) = @_;
1.265 albertel 5820:
5821: my %hash;
5822:
5823: if($string !~ /^__HASH_REF__/) {
5824: if (! ($string eq '' || !defined($string))) {
5825: $hash{'error'}='Not hash reference';
5826: }
5827: return (\%hash, $string);
5828: }
5829:
5830: $string =~ s/^__HASH_REF__//;
5831:
5832: while($string !~ /^__END_HASH_REF__/) {
5833: #key
5834: my $key='';
5835: if($string =~ /^__HASH_REF__/) {
5836: ($key, $string)=&str2hashref($string);
5837: if(defined($key->{'error'})) {
5838: $hash{'error'}='Bad data';
5839: return (\%hash, $string);
5840: }
5841: } elsif($string =~ /^__ARRAY_REF__/) {
5842: ($key, $string)=&str2arrayref($string);
5843: if($key->[0] eq 'Array reference error') {
5844: $hash{'error'}='Bad data';
5845: return (\%hash, $string);
5846: }
5847: } else {
5848: $string =~ s/^(.*?)=//;
1.267 albertel 5849: $key=&unescape($1);
1.265 albertel 5850: }
5851: $string =~ s/^=//;
5852:
5853: #value
5854: my $value='';
5855: if($string =~ /^__HASH_REF__/) {
5856: ($value, $string)=&str2hashref($string);
5857: if(defined($value->{'error'})) {
5858: $hash{'error'}='Bad data';
5859: return (\%hash, $string);
5860: }
5861: } elsif($string =~ /^__ARRAY_REF__/) {
5862: ($value, $string)=&str2arrayref($string);
5863: if($value->[0] eq 'Array reference error') {
5864: $hash{'error'}='Bad data';
5865: return (\%hash, $string);
5866: }
5867: } else {
5868: $value=&get_scalar(\$string,'__END_HASH_REF__');
5869: }
5870: $string =~ s/^&//;
5871:
5872: $hash{$key}=$value;
1.204 albertel 5873: }
1.265 albertel 5874:
5875: $string =~ s/^__END_HASH_REF__//;
5876:
5877: return (\%hash, $string);
1.204 albertel 5878: }
5879:
5880: sub str2array {
1.265 albertel 5881: my ($string)=@_;
5882: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5883: return @$array;
5884: }
5885:
5886: sub str2arrayref {
1.204 albertel 5887: my ($string) = @_;
1.265 albertel 5888: my @array;
5889:
5890: if($string !~ /^__ARRAY_REF__/) {
5891: if (! ($string eq '' || !defined($string))) {
5892: $array[0]='Array reference error';
5893: }
5894: return (\@array, $string);
5895: }
5896:
5897: $string =~ s/^__ARRAY_REF__//;
5898:
5899: while($string !~ /^__END_ARRAY_REF__/) {
5900: my $value='';
5901: if($string =~ /^__HASH_REF__/) {
5902: ($value, $string)=&str2hashref($string);
5903: if(defined($value->{'error'})) {
5904: $array[0] ='Array reference error';
5905: return (\@array, $string);
5906: }
5907: } elsif($string =~ /^__ARRAY_REF__/) {
5908: ($value, $string)=&str2arrayref($string);
5909: if($value->[0] eq 'Array reference error') {
5910: $array[0] ='Array reference error';
5911: return (\@array, $string);
5912: }
5913: } else {
5914: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5915: }
5916: $string =~ s/^&//;
5917:
5918: push(@array, $value);
1.191 harris41 5919: }
1.265 albertel 5920:
5921: $string =~ s/^__END_ARRAY_REF__//;
5922:
5923: return (\@array, $string);
1.168 albertel 5924: }
5925:
1.167 albertel 5926: # -------------------------------------------------------------------Temp Store
5927:
1.168 albertel 5928: sub tmpreset {
5929: my ($symb,$namespace,$domain,$stuname) = @_;
5930: if (!$symb) {
5931: $symb=&symbread();
1.620 albertel 5932: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5933: }
5934: $symb=escape($symb);
5935:
1.620 albertel 5936: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5937: $namespace=~s/\//\_/g;
5938: $namespace=~s/\W//g;
5939:
1.620 albertel 5940: if (!$domain) { $domain=$env{'user.domain'}; }
5941: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5942: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5943: $stuname=&get_requestor_ip();
1.591 albertel 5944: }
1.1117 foxr 5945: my $path=LONCAPA::tempdir();
1.168 albertel 5946: my %hash;
5947: if (tie(%hash,'GDBM_File',
5948: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5949: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5950: foreach my $key (keys(%hash)) {
1.180 albertel 5951: if ($key=~ /:$symb/) {
1.168 albertel 5952: delete($hash{$key});
5953: }
5954: }
5955: }
5956: }
5957:
1.167 albertel 5958: sub tmpstore {
1.168 albertel 5959: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5960:
5961: if (!$symb) {
5962: $symb=&symbread();
1.620 albertel 5963: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5964: }
5965: $symb=escape($symb);
5966:
5967: if (!$namespace) {
5968: # I don't think we would ever want to store this for a course.
5969: # it seems this will only be used if we don't have a course.
1.620 albertel 5970: #$namespace=$env{'request.course.id'};
1.168 albertel 5971: #if (!$namespace) {
1.620 albertel 5972: $namespace=$env{'request.state'};
1.168 albertel 5973: #}
5974: }
5975: $namespace=~s/\//\_/g;
5976: $namespace=~s/\W//g;
1.620 albertel 5977: if (!$domain) { $domain=$env{'user.domain'}; }
5978: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5979: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5980: $stuname=&get_requestor_ip();
1.591 albertel 5981: }
1.168 albertel 5982: my $now=time;
5983: my %hash;
1.1117 foxr 5984: my $path=LONCAPA::tempdir();
1.168 albertel 5985: if (tie(%hash,'GDBM_File',
5986: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5987: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5988: $hash{"version:$symb"}++;
5989: my $version=$hash{"version:$symb"};
5990: my $allkeys='';
5991: foreach my $key (keys(%$storehash)) {
5992: $allkeys.=$key.':';
1.591 albertel 5993: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5994: }
5995: $hash{"$version:$symb:timestamp"}=$now;
5996: $allkeys.='timestamp';
5997: $hash{"$version:keys:$symb"}=$allkeys;
5998: if (untie(%hash)) {
5999: return 'ok';
6000: } else {
6001: return "error:$!";
6002: }
6003: } else {
6004: return "error:$!";
6005: }
6006: }
1.167 albertel 6007:
1.168 albertel 6008: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6009:
1.168 albertel 6010: sub tmprestore {
6011: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6012:
1.168 albertel 6013: if (!$symb) {
6014: $symb=&symbread();
1.620 albertel 6015: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6016: }
6017: $symb=escape($symb);
6018:
1.620 albertel 6019: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6020:
1.620 albertel 6021: if (!$domain) { $domain=$env{'user.domain'}; }
6022: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6023: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6024: $stuname=&get_requestor_ip();
1.591 albertel 6025: }
1.168 albertel 6026: my %returnhash;
6027: $namespace=~s/\//\_/g;
6028: $namespace=~s/\W//g;
6029: my %hash;
1.1117 foxr 6030: my $path=LONCAPA::tempdir();
1.168 albertel 6031: if (tie(%hash,'GDBM_File',
6032: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6033: &GDBM_READER(),0640)) {
1.168 albertel 6034: my $version=$hash{"version:$symb"};
6035: $returnhash{'version'}=$version;
6036: my $scope;
6037: for ($scope=1;$scope<=$version;$scope++) {
6038: my $vkeys=$hash{"$scope:keys:$symb"};
6039: my @keys=split(/:/,$vkeys);
6040: my $key;
6041: $returnhash{"$scope:keys"}=$vkeys;
6042: foreach $key (@keys) {
1.591 albertel 6043: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6044: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6045: }
6046: }
1.168 albertel 6047: if (!(untie(%hash))) {
6048: return "error:$!";
6049: }
6050: } else {
6051: return "error:$!";
6052: }
6053: return %returnhash;
1.167 albertel 6054: }
6055:
1.9 www 6056: # ----------------------------------------------------------------------- Store
6057:
6058: sub store {
1.1172.2.64 raeburn 6059: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6060: my $home='';
6061:
1.168 albertel 6062: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6063:
1.213 www 6064: $symb=&symbclean($symb);
1.122 albertel 6065: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6066:
1.620 albertel 6067: if (!$domain) { $domain=$env{'user.domain'}; }
6068: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6069:
6070: &devalidate($symb,$stuname,$domain);
1.109 www 6071:
6072: $symb=escape($symb);
1.187 www 6073: if (!$namespace) {
1.620 albertel 6074: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6075: return '';
6076: }
6077: }
1.620 albertel 6078: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6079:
1.1172.2.138 raeburn 6080: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6081: $$storehash{'host'}=$perlvar{'lonHostID'};
6082:
1.12 www 6083: my $namevalue='';
1.800 albertel 6084: foreach my $key (keys(%$storehash)) {
6085: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6086: }
1.12 www 6087: $namevalue=~s/\&$//;
1.187 www 6088: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6089: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6090: }
6091:
1.47 www 6092: # -------------------------------------------------------------- Critical Store
6093:
6094: sub cstore {
1.1172.2.64 raeburn 6095: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6096: my $home='';
6097:
1.168 albertel 6098: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6099:
1.213 www 6100: $symb=&symbclean($symb);
1.122 albertel 6101: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6102:
1.620 albertel 6103: if (!$domain) { $domain=$env{'user.domain'}; }
6104: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6105:
6106: &devalidate($symb,$stuname,$domain);
1.109 www 6107:
6108: $symb=escape($symb);
1.187 www 6109: if (!$namespace) {
1.620 albertel 6110: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6111: return '';
6112: }
6113: }
1.620 albertel 6114: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6115:
1.1172.2.138 raeburn 6116: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6117: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6118:
1.47 www 6119: my $namevalue='';
1.800 albertel 6120: foreach my $key (keys(%$storehash)) {
6121: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6122: }
1.47 www 6123: $namevalue=~s/\&$//;
1.187 www 6124: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6125: return critical
1.1172.2.64 raeburn 6126: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6127: }
6128:
1.9 www 6129: # --------------------------------------------------------------------- Restore
6130:
6131: sub restore {
1.124 www 6132: my ($symb,$namespace,$domain,$stuname) = @_;
6133: my $home='';
6134:
1.168 albertel 6135: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6136:
1.122 albertel 6137: if (!$symb) {
1.1172.2.26 raeburn 6138: return if ($namespace eq 'courserequests');
6139: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6140: } else {
1.1172.2.26 raeburn 6141: unless ($namespace eq 'courserequests') {
6142: $symb=&escape(&symbclean($symb));
6143: }
1.122 albertel 6144: }
1.188 www 6145: if (!$namespace) {
1.620 albertel 6146: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6147: return '';
6148: }
6149: }
1.620 albertel 6150: if (!$domain) { $domain=$env{'user.domain'}; }
6151: if (!$stuname) { $stuname=$env{'user.name'}; }
6152: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6153: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6154:
1.12 www 6155: my %returnhash=();
1.800 albertel 6156: foreach my $line (split(/\&/,$answer)) {
6157: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6158: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6159: }
1.75 www 6160: my $version;
6161: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6162: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6163: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6164: }
1.75 www 6165: }
1.13 www 6166: return %returnhash;
1.34 www 6167: }
6168:
6169: # ---------------------------------------------------------- Course Description
1.1118 foxr 6170: #
6171: #
1.34 www 6172:
6173: sub coursedescription {
1.731 albertel 6174: my ($courseid,$args)=@_;
1.34 www 6175: $courseid=~s/^\///;
1.49 www 6176: $courseid=~s/\_/\//g;
1.34 www 6177: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6178: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6179: my $normalid=$cdomain.'_'.$cnum;
6180: # need to always cache even if we get errors otherwise we keep
6181: # trying and trying and trying to get the course description.
6182: my %envhash=();
6183: my %returnhash=();
1.731 albertel 6184:
6185: my $expiretime=600;
6186: if ($env{'request.course.id'} eq $normalid) {
6187: $expiretime=120;
6188: }
6189:
6190: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6191: if (!$args->{'freshen_cache'}
6192: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6193: foreach my $key (keys(%env)) {
6194: next if ($key !~ /^\Q$prefix\E(.*)/);
6195: my ($setting) = $1;
6196: $returnhash{$setting} = $env{$key};
6197: }
6198: return %returnhash;
6199: }
6200:
1.1118 foxr 6201: # get the data again
6202:
1.731 albertel 6203: if (!$args->{'one_time'}) {
6204: $envhash{'course.'.$normalid.'.last_cache'}=time;
6205: }
1.811 albertel 6206:
1.34 www 6207: if ($chome ne 'no_host') {
1.302 albertel 6208: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6209: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6210: my $username = $env{'user.name'}; # Defult username
6211: if(defined $args->{'user'}) {
6212: $username = $args->{'user'};
6213: }
1.129 albertel 6214: $returnhash{'home'}= $chome;
6215: $returnhash{'domain'} = $cdomain;
6216: $returnhash{'num'} = $cnum;
1.741 raeburn 6217: if (!defined($returnhash{'type'})) {
6218: $returnhash{'type'} = 'Course';
6219: }
1.130 albertel 6220: while (my ($name,$value) = each %returnhash) {
1.53 www 6221: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6222: }
1.270 www 6223: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6224: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6225: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6226: $envhash{'course.'.$normalid.'.home'}=$chome;
6227: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6228: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6229: }
6230: }
1.731 albertel 6231: if (!$args->{'one_time'}) {
1.949 raeburn 6232: &appenv(\%envhash);
1.731 albertel 6233: }
1.302 albertel 6234: return %returnhash;
1.461 www 6235: }
6236:
1.1080 raeburn 6237: sub update_released_required {
6238: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6239: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6240: $cid = $env{'request.course.id'};
6241: $cdom = $env{'course.'.$cid.'.domain'};
6242: $cnum = $env{'course.'.$cid.'.num'};
6243: $chome = $env{'course.'.$cid.'.home'};
6244: }
6245: if ($needsrelease) {
6246: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6247: my $needsupdate;
6248: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6249: $needsupdate = 1;
6250: } else {
6251: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6252: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6253: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6254: $needsupdate = 1;
6255: }
6256: }
6257: if ($needsupdate) {
6258: my %needshash = (
6259: 'internal.releaserequired' => $needsrelease,
6260: );
6261: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6262: if ($putresult eq 'ok') {
6263: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6264: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6265: if (ref($crsinfo{$cid}) eq 'HASH') {
6266: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6267: &courseidput($cdom,\%crsinfo,$chome,'notime');
6268: }
6269: }
6270: }
6271: }
6272: return;
6273: }
6274:
1.461 www 6275: # -------------------------------------------------See if a user is privileged
6276:
6277: sub privileged {
1.1172.2.23 raeburn 6278: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6279: my $now = time;
1.1172.2.23 raeburn 6280: my $roles;
6281: if (ref($possroles) eq 'ARRAY') {
6282: $roles = $possroles;
6283: } else {
6284: $roles = ['dc','su'];
6285: }
6286: if (ref($possdomains) eq 'ARRAY') {
6287: my %privileged = &privileged_by_domain($possdomains,$roles);
6288: foreach my $dom (@{$possdomains}) {
6289: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6290: (ref($privileged{$dom}) eq 'HASH')) {
6291: foreach my $role (@{$roles}) {
6292: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6293: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6294: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6295: return 1 unless (($end && $end < $now) ||
6296: ($start && $start > $now));
6297: }
6298: }
6299: }
6300: }
6301: }
6302: } else {
6303: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6304: my $now = time;
1.1170 droeschl 6305:
1.1172.2.58 raeburn 6306: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6307: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6308: if (grep(/^\Q$trole\E$/,@{$roles})) {
6309: return 1 unless ($tend && $tend < $now)
6310: or ($tstart && $tstart > $now);
1.1170 droeschl 6311: }
1.1172.2.23 raeburn 6312: }
6313: }
1.461 www 6314: return 0;
1.9 www 6315: }
1.1 albertel 6316:
1.1172.2.23 raeburn 6317: sub privileged_by_domain {
6318: my ($domains,$roles) = @_;
6319: my %privileged = ();
6320: my $cachetime = 60*60*24;
6321: my $now = time;
6322: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6323: return %privileged;
6324: }
6325: foreach my $dom (@{$domains}) {
6326: next if (ref($privileged{$dom}) eq 'HASH');
6327: my $needroles;
6328: foreach my $role (@{$roles}) {
6329: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6330: if (defined($cached)) {
6331: if (ref($result) eq 'HASH') {
6332: $privileged{$dom}{$role} = $result;
6333: }
6334: } else {
6335: $needroles = 1;
6336: }
6337: }
6338: if ($needroles) {
6339: my %dompersonnel = &get_domain_roles($dom,$roles);
6340: $privileged{$dom} = {};
6341: foreach my $server (keys(%dompersonnel)) {
6342: if (ref($dompersonnel{$server}) eq 'HASH') {
6343: foreach my $item (keys(%{$dompersonnel{$server}})) {
6344: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6345: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6346: next if ($end && $end < $now);
6347: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6348: $dompersonnel{$server}{$item};
6349: }
6350: }
6351: }
6352: if (ref($privileged{$dom}) eq 'HASH') {
6353: foreach my $role (@{$roles}) {
6354: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6355: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6356: } else {
6357: my %hash = ();
6358: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6359: }
6360: }
6361: }
6362: }
6363: }
6364: return %privileged;
6365: }
6366:
1.103 harris41 6367: # -------------------------------------------------------- Get user privileges
1.11 www 6368:
6369: sub rolesinit {
1.1169 droeschl 6370: my ($domain, $username) = @_;
6371: my %userroles = ('user.login.time' => time);
6372: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6373:
6374: # firstaccess and timerinterval are related to timed maps/resources.
6375: # also, blocking can be triggered by an activating timer
6376: # it's saved in the user's %env.
6377: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6378: my %timerinterval = &dump('timerinterval', $domain, $username);
6379: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6380: %timerintchk, %timerintenv);
6381:
1.1162 raeburn 6382: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6383: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6384: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6385: }
1.1169 droeschl 6386:
1.1162 raeburn 6387: foreach my $key (keys(%timerinterval)) {
6388: my ($cid,$rest) = split(/\0/,$key);
6389: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6390: }
1.1169 droeschl 6391:
1.11 www 6392: my %allroles=();
1.1162 raeburn 6393: my %allgroups=();
1.11 www 6394:
1.1172.2.58 raeburn 6395: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6396: my $role = $rolesdump{$area};
6397: $area =~ s/\_\w\w$//;
6398:
6399: my ($trole, $tend, $tstart, $group_privs);
6400:
6401: if ($role =~ /^cr/) {
6402: # Custom role, defined by a user
6403: # e.g., user.role.cr/msu/smith/mynewrole
6404: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6405: $trole = $1;
6406: ($tend, $tstart) = split('_', $2);
6407: } else {
6408: $trole = $role;
6409: }
6410: } elsif ($role =~ m|^gr/|) {
6411: # Role of member in a group, defined within a course/community
6412: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6413: ($trole, $tend, $tstart) = split(/_/, $role);
6414: next if $tstart eq '-1';
6415: ($trole, $group_privs) = split(/\//, $trole);
6416: $group_privs = &unescape($group_privs);
6417: } else {
6418: # Just a normal role, defined in roles.tab
6419: ($trole, $tend, $tstart) = split(/_/,$role);
6420: }
6421:
6422: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6423: $username);
6424: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6425:
6426: # role expired or not available yet?
6427: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6428: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6429:
6430: next if $area eq '' or $trole eq '';
6431:
6432: my $spec = "$trole.$area";
6433: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6434:
6435: if ($trole =~ /^cr\//) {
6436: # Custom role, defined by a user
6437: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6438: } elsif ($trole eq 'gr') {
6439: # Role of a member in a group, defined within a course/community
6440: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6441: next;
6442: } else {
6443: # Normal role, defined in roles.tab
6444: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6445: }
6446:
6447: my $cid = $tdomain.'_'.$trest;
6448: unless ($firstaccchk{$cid}) {
6449: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6450: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6451: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6452: $coursetimerstarts{$cid}{$item};
6453: }
6454: }
6455: $firstaccchk{$cid} = 1;
6456: }
6457: unless ($timerintchk{$cid}) {
6458: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6459: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6460: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6461: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6462: }
1.12 www 6463: }
1.1169 droeschl 6464: $timerintchk{$cid} = 1;
1.191 harris41 6465: }
1.11 www 6466: }
1.1169 droeschl 6467:
1.1172.2.91 raeburn 6468: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6469: \%allroles, \%allgroups);
1.1169 droeschl 6470: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6471: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6472:
1.1162 raeburn 6473: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6474: }
6475:
1.567 raeburn 6476: sub set_arearole {
1.1172.2.19 raeburn 6477: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6478: unless ($nolog) {
1.567 raeburn 6479: # log the associated role with the area
1.1172.2.19 raeburn 6480: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6481: }
1.743 albertel 6482: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6483: }
6484:
6485: sub custom_roleprivs {
6486: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6487: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6488: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6489: if (&hostname($homsvr) ne '') {
1.567 raeburn 6490: my ($rdummy,$roledef)=
6491: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6492: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6493: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6494: if (defined($syspriv)) {
1.1043 raeburn 6495: if ($trest =~ /^$match_community$/) {
6496: $syspriv =~ s/bre\&S//;
6497: }
1.567 raeburn 6498: $$allroles{'cm./'}.=':'.$syspriv;
6499: $$allroles{$spec.'./'}.=':'.$syspriv;
6500: }
6501: if ($tdomain ne '') {
6502: if (defined($dompriv)) {
6503: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6504: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6505: }
6506: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6507: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6508: my $rolename = $1;
6509: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6510: }
1.567 raeburn 6511: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6512: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6513: }
6514: }
6515: }
6516: }
6517: }
6518:
1.1172.2.89 raeburn 6519: sub course_adhocrole_privs {
6520: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6521: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6522: if ($overrides{"internal.adhocpriv.$rolename"}) {
6523: my (%currprivs,%storeprivs);
6524: foreach my $item (split(/:/,$coursepriv)) {
6525: my ($priv,$restrict) = split(/\&/,$item);
6526: $currprivs{$priv} = $restrict;
6527: }
6528: my (%possadd,%possremove,%full);
6529: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6530: my ($priv,$restrict)=split(/\&/,$item);
6531: $full{$priv} = $restrict;
6532: }
6533: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6534: next if ($item eq '');
6535: my ($rule,$rest) = split(/=/,$item);
6536: next unless (($rule eq 'off') || ($rule eq 'on'));
6537: foreach my $priv (split(/:/,$rest)) {
6538: if ($priv ne '') {
6539: if ($rule eq 'off') {
6540: $possremove{$priv} = 1;
6541: } else {
6542: $possadd{$priv} = 1;
6543: }
6544: }
6545: }
6546: }
6547: foreach my $priv (sort(keys(%full))) {
6548: if (exists($currprivs{$priv})) {
6549: unless (exists($possremove{$priv})) {
6550: $storeprivs{$priv} = $currprivs{$priv};
6551: }
6552: } elsif (exists($possadd{$priv})) {
6553: $storeprivs{$priv} = $full{$priv};
6554: }
6555: }
6556: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6557: }
6558: return $coursepriv;
6559: }
6560:
1.678 raeburn 6561: sub group_roleprivs {
6562: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6563: my $access = 1;
6564: my $now = time;
6565: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6566: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6567: if ($access) {
1.811 albertel 6568: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6569: $$allgroups{$course}{$group} .=':'.$group_privs;
6570: }
6571: }
1.567 raeburn 6572:
6573: sub standard_roleprivs {
6574: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6575: if (defined($pr{$trole.':s'})) {
6576: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6577: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6578: }
6579: if ($tdomain ne '') {
6580: if (defined($pr{$trole.':d'})) {
6581: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6582: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6583: }
6584: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6585: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6586: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6587: }
6588: }
6589: }
6590:
6591: sub set_userprivs {
1.1064 raeburn 6592: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6593: my $author=0;
6594: my $adv=0;
1.1172.2.91 raeburn 6595: my $rar=0;
1.678 raeburn 6596: my %grouproles = ();
6597: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6598: my @groupkeys;
1.1000 raeburn 6599: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6600: push(@groupkeys,$role);
6601: }
6602: if (ref($groups_roles) eq 'HASH') {
6603: foreach my $key (keys(%{$groups_roles})) {
6604: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6605: push(@groupkeys,$key);
6606: }
6607: }
6608: }
6609: if (@groupkeys > 0) {
6610: foreach my $role (@groupkeys) {
6611: my ($trole,$area,$sec,$extendedarea);
6612: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6613: $trole = $1;
6614: $area = $2;
6615: $sec = $3;
6616: $extendedarea = $area.$sec;
6617: if (exists($$allgroups{$area})) {
6618: foreach my $group (keys(%{$$allgroups{$area}})) {
6619: my $spec = $trole.'.'.$extendedarea;
6620: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6621: $$allgroups{$area}{$group};
1.1064 raeburn 6622: }
1.678 raeburn 6623: }
6624: }
6625: }
6626: }
6627: }
1.800 albertel 6628: foreach my $group (keys(%grouproles)) {
6629: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6630: }
1.800 albertel 6631: foreach my $role (keys(%{$allroles})) {
6632: my %thesepriv;
1.941 raeburn 6633: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6634: foreach my $item (split(/:/,$$allroles{$role})) {
6635: if ($item ne '') {
6636: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6637: if ($restrictions eq '') {
6638: $thesepriv{$privilege}='F';
6639: } elsif ($thesepriv{$privilege} ne 'F') {
6640: $thesepriv{$privilege}.=$restrictions;
6641: }
6642: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6643: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6644: }
6645: }
6646: my $thesestr='';
1.1104 raeburn 6647: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6648: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6649: }
6650: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6651: }
1.1172.2.91 raeburn 6652: return ($author,$adv,$rar);
1.567 raeburn 6653: }
6654:
1.994 raeburn 6655: sub role_status {
1.1104 raeburn 6656: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6657: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6658: my ($one,$two) = split(m{\./},$rolekey,2);
6659: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6660: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6661: $$where = '/'.$two;
1.994 raeburn 6662: $$trolecode=$$role.'.'.$$where;
6663: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6664: $$tstatus='is';
1.1104 raeburn 6665: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6666: $$tstatus='future';
1.1034 raeburn 6667: if ($$tstart<$now) {
6668: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6669: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6670: my (%allroles,%allgroups,$group_privs,
6671: %groups_roles,@rolecodes);
1.1002 raeburn 6672: my %userroles = (
6673: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6674: );
1.1064 raeburn 6675: @rolecodes = ('cm');
1.1002 raeburn 6676: my $spec=$$role.'.'.$$where;
6677: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6678: if ($$role =~ /^cr\//) {
6679: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6680: push(@rolecodes,'cr');
1.1002 raeburn 6681: } elsif ($$role eq 'gr') {
1.1064 raeburn 6682: push(@rolecodes,$$role);
1.1002 raeburn 6683: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6684: $env{'user.name'});
1.1064 raeburn 6685: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6686: (undef,my $group_privs) = split(/\//,$trole);
6687: $group_privs = &unescape($group_privs);
6688: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6689: 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 6690: &get_groups_roles($tdomain,$trest,
6691: \%course_roles,\@rolecodes,
6692: \%groups_roles);
1.1002 raeburn 6693: } else {
1.1064 raeburn 6694: push(@rolecodes,$$role);
1.1002 raeburn 6695: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6696: }
1.1172.2.91 raeburn 6697: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6698: \%groups_roles);
1.1064 raeburn 6699: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6700: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6701: }
6702: }
1.1034 raeburn 6703: $$tstatus = 'is';
1.1002 raeburn 6704: }
1.994 raeburn 6705: }
6706: if ($$tend) {
1.1104 raeburn 6707: if ($$tend<$update) {
1.994 raeburn 6708: $$tstatus='expired';
6709: } elsif ($$tend<$now) {
6710: $$tstatus='will_not';
6711: }
6712: }
6713: }
6714: }
6715: }
6716:
1.1104 raeburn 6717: sub get_groups_roles {
6718: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6719: return unless((ref($cdom_courseroles) eq 'HASH') &&
6720: (ref($rolecodes) eq 'ARRAY') &&
6721: (ref($groups_roles) eq 'HASH'));
6722: if (keys(%{$cdom_courseroles}) > 0) {
6723: my ($cnum) = ($rest =~ /^($match_courseid)/);
6724: if ($cdom ne '' && $cnum ne '') {
6725: foreach my $key (keys(%{$cdom_courseroles})) {
6726: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6727: my $crsrole = $1;
6728: my $crssec = $2;
6729: if ($crsrole =~ /^cr/) {
6730: unless (grep(/^cr$/,@{$rolecodes})) {
6731: push(@{$rolecodes},'cr');
6732: }
6733: } else {
6734: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6735: push(@{$rolecodes},$crsrole);
6736: }
6737: }
6738: my $rolekey = "$crsrole./$cdom/$cnum";
6739: if ($crssec ne '') {
6740: $rolekey .= "/$crssec";
6741: }
6742: $rolekey .= './';
6743: $groups_roles->{$rolekey} = $rolecodes;
6744: }
6745: }
6746: }
6747: }
6748: return;
6749: }
6750:
6751: sub delete_env_groupprivs {
6752: my ($where,$courseroles,$possroles) = @_;
6753: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6754: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6755: unless (ref($courseroles->{$udom}) eq 'HASH') {
6756: %{$courseroles->{$udom}} =
6757: &get_my_roles('','','userroles',['active'],
6758: $possroles,[$udom],1);
6759: }
6760: if (ref($courseroles->{$udom}) eq 'HASH') {
6761: foreach my $item (keys(%{$courseroles->{$udom}})) {
6762: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6763: my $area = '/'.$cdom.'/'.$cnum;
6764: my $privkey = "user.priv.$crsrole.$area";
6765: if ($crssec ne '') {
6766: $privkey .= '/'.$crssec;
6767: }
6768: $privkey .= ".$area/$group";
6769: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6770: }
6771: }
6772: return;
6773: }
6774:
1.994 raeburn 6775: sub check_adhoc_privs {
1.1172.2.86 raeburn 6776: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6777: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6778: if ($sec) {
6779: $cckey .= '/'.$sec;
6780: }
1.1172.2.9 raeburn 6781: my $setprivs;
1.994 raeburn 6782: if ($env{$cckey}) {
6783: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6784: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6785: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6786: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6787: $setprivs = 1;
1.994 raeburn 6788: }
6789: } else {
1.1172.2.87 raeburn 6790: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6791: $setprivs = 1;
1.994 raeburn 6792: }
1.1172.2.9 raeburn 6793: return $setprivs;
1.994 raeburn 6794: }
6795:
6796: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6797: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6798: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6799: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6800: if ($sec ne '') {
6801: $area .= '/'.$sec;
6802: }
1.994 raeburn 6803: my $spec = $role.'.'.$area;
6804: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6805: $env{'user.name'},1);
1.1172.2.84 raeburn 6806: my %rolehash = ();
1.1172.2.89 raeburn 6807: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6808: my $rolename = $1;
1.1172.2.84 raeburn 6809: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6810: my %domdef = &get_domain_defaults($dcdom);
6811: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6812: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6813: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6814: }
6815: }
1.1172.2.84 raeburn 6816: } else {
6817: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6818: }
1.1172.2.91 raeburn 6819: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6820: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6821: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6822: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6823: &appenv( {'request.role' => $spec,
6824: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6825: 'request.course.sec' => $sec,
1.1088 raeburn 6826: }
6827: );
6828: my $tadv=0;
6829: if (&allowed('adv') eq 'F') { $tadv=1; }
6830: &appenv({'request.role.adv' => $tadv});
6831: }
1.994 raeburn 6832: }
6833:
1.12 www 6834: # --------------------------------------------------------------- get interface
6835:
6836: sub get {
1.131 albertel 6837: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6838: my $items='';
1.800 albertel 6839: foreach my $item (@$storearr) {
6840: $items.=&escape($item).'&';
1.191 harris41 6841: }
1.12 www 6842: $items=~s/\&$//;
1.620 albertel 6843: if (!$udomain) { $udomain=$env{'user.domain'}; }
6844: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6845: my $uhome=&homeserver($uname,$udomain);
6846:
1.133 albertel 6847: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6848: my @pairs=split(/\&/,$rep);
1.273 albertel 6849: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6850: return @pairs;
6851: }
1.15 www 6852: my %returnhash=();
1.42 www 6853: my $i=0;
1.800 albertel 6854: foreach my $item (@$storearr) {
6855: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6856: $i++;
1.191 harris41 6857: }
1.15 www 6858: return %returnhash;
1.27 www 6859: }
6860:
6861: # --------------------------------------------------------------- del interface
6862:
6863: sub del {
1.133 albertel 6864: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6865: my $items='';
1.800 albertel 6866: foreach my $item (@$storearr) {
6867: $items.=&escape($item).'&';
1.191 harris41 6868: }
1.984 neumanie 6869:
1.27 www 6870: $items=~s/\&$//;
1.620 albertel 6871: if (!$udomain) { $udomain=$env{'user.domain'}; }
6872: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6873: my $uhome=&homeserver($uname,$udomain);
6874: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6875: }
6876:
6877: # -------------------------------------------------------------- dump interface
6878:
1.1172.2.22 raeburn 6879: sub unserialize {
6880: my ($rep, $escapedkeys) = @_;
6881:
6882: return {} if $rep =~ /^error/;
6883:
6884: my %returnhash=();
6885: foreach my $item (split(/\&/,$rep)) {
6886: my ($key, $value) = split(/=/, $item, 2);
6887: $key = unescape($key) unless $escapedkeys;
6888: next if $key =~ /^error: 2 /;
6889: $returnhash{$key} = &thaw_unescape($value);
6890: }
6891: return \%returnhash;
6892: }
6893:
6894: # see Lond::dump_with_regexp
6895: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6896: sub dump {
1.1172.2.22 raeburn 6897: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6898: if (!$udomain) { $udomain=$env{'user.domain'}; }
6899: if (!$uname) { $uname=$env{'user.name'}; }
6900: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6901:
1.1172.2.55 raeburn 6902: if ($regexp) {
6903: $regexp=&escape($regexp);
6904: } else {
6905: $regexp='.';
6906: }
1.1172.2.22 raeburn 6907: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6908: # user is hosted on this machine
1.1172.2.55 raeburn 6909: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6910: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6911: return %{&unserialize($reply, $escapedkeys)};
6912: }
1.1166 raeburn 6913: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6914: my @pairs=split(/\&/,$rep);
6915: my %returnhash=();
1.1098 foxr 6916: if (!($rep =~ /^error/ )) {
6917: foreach my $item (@pairs) {
6918: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6919: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6920: next if ($key =~ /^error: 2 /);
6921: $returnhash{$key}=&thaw_unescape($value);
6922: }
1.755 albertel 6923: }
6924: return %returnhash;
1.407 www 6925: }
6926:
1.1098 foxr 6927:
1.717 albertel 6928: # --------------------------------------------------------- dumpstore interface
6929:
6930: sub dumpstore {
6931: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6932: # same as dump but keys must be escaped. They may contain colon separated
6933: # lists of values that may themself contain colons (e.g. symbs).
6934: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6935: }
6936:
1.407 www 6937: # -------------------------------------------------------------- keys interface
6938:
6939: sub getkeys {
6940: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6941: if (!$udomain) { $udomain=$env{'user.domain'}; }
6942: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6943: my $uhome=&homeserver($uname,$udomain);
6944: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6945: my @keyarray=();
1.800 albertel 6946: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6947: next if ($key =~ /^error: 2 /);
1.800 albertel 6948: push(@keyarray,&unescape($key));
1.407 www 6949: }
6950: return @keyarray;
1.318 matthew 6951: }
6952:
1.319 matthew 6953: # --------------------------------------------------------------- currentdump
6954: sub currentdump {
1.328 matthew 6955: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6956: $courseid = $env{'request.course.id'} if (! defined($courseid));
6957: $sdom = $env{'user.domain'} if (! defined($sdom));
6958: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6959: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6960: my $rep;
6961:
6962: if (grep { $_ eq $uhome } current_machine_ids()) {
6963: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6964: $courseid)));
6965: } else {
6966: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6967: }
6968:
1.318 matthew 6969: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6970: #
1.318 matthew 6971: my %returnhash=();
1.319 matthew 6972: #
6973: if ($rep eq "unknown_cmd") {
6974: # an old lond will not know currentdump
6975: # Do a dump and make it look like a currentdump
1.822 albertel 6976: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6977: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6978: my %hash = @tmp;
6979: @tmp=();
1.424 matthew 6980: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6981: } else {
6982: my @pairs=split(/\&/,$rep);
1.800 albertel 6983: foreach my $pair (@pairs) {
6984: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6985: my ($symb,$param) = split(/:/,$key);
6986: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6987: &thaw_unescape($value);
1.319 matthew 6988: }
1.191 harris41 6989: }
1.12 www 6990: return %returnhash;
1.424 matthew 6991: }
6992:
6993: sub convert_dump_to_currentdump{
6994: my %hash = %{shift()};
6995: my %returnhash;
6996: # Code ripped from lond, essentially. The only difference
6997: # here is the unescaping done by lonnet::dump(). Conceivably
6998: # we might run in to problems with parameter names =~ /^v\./
6999: while (my ($key,$value) = each(%hash)) {
7000: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7001: $symb = &unescape($symb);
7002: $param = &unescape($param);
1.424 matthew 7003: next if ($v eq 'version' || $symb eq 'keys');
7004: next if (exists($returnhash{$symb}) &&
7005: exists($returnhash{$symb}->{$param}) &&
7006: $returnhash{$symb}->{'v.'.$param} > $v);
7007: $returnhash{$symb}->{$param}=$value;
7008: $returnhash{$symb}->{'v.'.$param}=$v;
7009: }
7010: #
7011: # Remove all of the keys in the hashes which keep track of
7012: # the version of the parameter.
7013: while (my ($symb,$param_hash) = each(%returnhash)) {
7014: # use a foreach because we are going to delete from the hash.
7015: foreach my $key (keys(%$param_hash)) {
7016: delete($param_hash->{$key}) if ($key =~ /^v\./);
7017: }
7018: }
7019: return \%returnhash;
1.12 www 7020: }
7021:
1.627 albertel 7022: # ------------------------------------------------------ critical inc interface
7023:
7024: sub cinc {
7025: return &inc(@_,'critical');
7026: }
7027:
1.449 matthew 7028: # --------------------------------------------------------------- inc interface
7029:
7030: sub inc {
1.627 albertel 7031: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7032: if (!$udomain) { $udomain=$env{'user.domain'}; }
7033: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7034: my $uhome=&homeserver($uname,$udomain);
7035: my $items='';
7036: if (! ref($store)) {
7037: # got a single value, so use that instead
7038: $items = &escape($store).'=&';
7039: } elsif (ref($store) eq 'SCALAR') {
7040: $items = &escape($$store).'=&';
7041: } elsif (ref($store) eq 'ARRAY') {
7042: $items = join('=&',map {&escape($_);} @{$store});
7043: } elsif (ref($store) eq 'HASH') {
7044: while (my($key,$value) = each(%{$store})) {
7045: $items.= &escape($key).'='.&escape($value).'&';
7046: }
7047: }
7048: $items=~s/\&$//;
1.627 albertel 7049: if ($critical) {
7050: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7051: } else {
7052: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7053: }
1.449 matthew 7054: }
7055:
1.12 www 7056: # --------------------------------------------------------------- put interface
7057:
7058: sub put {
1.134 albertel 7059: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7060: if (!$udomain) { $udomain=$env{'user.domain'}; }
7061: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7062: my $uhome=&homeserver($uname,$udomain);
1.12 www 7063: my $items='';
1.800 albertel 7064: foreach my $item (keys(%$storehash)) {
7065: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7066: }
1.12 www 7067: $items=~s/\&$//;
1.134 albertel 7068: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7069: }
7070:
1.631 albertel 7071: # ------------------------------------------------------------ newput interface
7072:
7073: sub newput {
7074: my ($namespace,$storehash,$udomain,$uname)=@_;
7075: if (!$udomain) { $udomain=$env{'user.domain'}; }
7076: if (!$uname) { $uname=$env{'user.name'}; }
7077: my $uhome=&homeserver($uname,$udomain);
7078: my $items='';
7079: foreach my $key (keys(%$storehash)) {
7080: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7081: }
7082: $items=~s/\&$//;
7083: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7084: }
7085:
7086: # --------------------------------------------------------- putstore interface
7087:
1.524 raeburn 7088: sub putstore {
1.1172.2.59 raeburn 7089: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7090: if (!$udomain) { $udomain=$env{'user.domain'}; }
7091: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7092: my $uhome=&homeserver($uname,$udomain);
7093: my $items='';
1.715 albertel 7094: foreach my $key (keys(%$storehash)) {
7095: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7096: }
1.715 albertel 7097: $items=~s/\&$//;
1.716 albertel 7098: my $esc_symb=&escape($symb);
7099: my $esc_v=&escape($version);
1.715 albertel 7100: my $reply =
1.716 albertel 7101: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7102: $uhome);
1.1172.2.59 raeburn 7103: if (($tolog) && ($reply eq 'ok')) {
7104: my $namevalue='';
7105: foreach my $key (keys(%{$storehash})) {
7106: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7107: }
1.1172.2.134 raeburn 7108: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7109: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7110: '&host='.&escape($perlvar{'lonHostID'}).
7111: '&version='.$esc_v.
7112: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7113: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7114: }
1.715 albertel 7115: if ($reply eq 'unknown_cmd') {
1.716 albertel 7116: # gfall back to way things use to be done
1.715 albertel 7117: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7118: $uname);
1.524 raeburn 7119: }
1.715 albertel 7120: return $reply;
7121: }
7122:
7123: sub old_putstore {
1.716 albertel 7124: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7125: if (!$udomain) { $udomain=$env{'user.domain'}; }
7126: if (!$uname) { $uname=$env{'user.name'}; }
7127: my $uhome=&homeserver($uname,$udomain);
7128: my %newstorehash;
1.800 albertel 7129: foreach my $item (keys(%$storehash)) {
7130: my $key = $version.':'.&escape($symb).':'.$item;
7131: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7132: }
7133: my $items='';
7134: my %allitems = ();
1.800 albertel 7135: foreach my $item (keys(%newstorehash)) {
7136: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7137: my $key = $1.':keys:'.$2;
7138: $allitems{$key} .= $3.':';
7139: }
1.800 albertel 7140: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7141: }
1.800 albertel 7142: foreach my $item (keys(%allitems)) {
7143: $allitems{$item} =~ s/\:$//;
7144: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7145: }
7146: $items=~s/\&$//;
7147: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7148: }
7149:
1.47 www 7150: # ------------------------------------------------------ critical put interface
7151:
7152: sub cput {
1.134 albertel 7153: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7154: if (!$udomain) { $udomain=$env{'user.domain'}; }
7155: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7156: my $uhome=&homeserver($uname,$udomain);
1.47 www 7157: my $items='';
1.800 albertel 7158: foreach my $item (keys(%$storehash)) {
7159: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7160: }
1.47 www 7161: $items=~s/\&$//;
1.134 albertel 7162: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7163: }
7164:
7165: # -------------------------------------------------------------- eget interface
7166:
7167: sub eget {
1.133 albertel 7168: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7169: my $items='';
1.800 albertel 7170: foreach my $item (@$storearr) {
7171: $items.=&escape($item).'&';
1.191 harris41 7172: }
1.12 www 7173: $items=~s/\&$//;
1.620 albertel 7174: if (!$udomain) { $udomain=$env{'user.domain'}; }
7175: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7176: my $uhome=&homeserver($uname,$udomain);
7177: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7178: my @pairs=split(/\&/,$rep);
7179: my %returnhash=();
1.42 www 7180: my $i=0;
1.800 albertel 7181: foreach my $item (@$storearr) {
7182: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7183: $i++;
1.191 harris41 7184: }
1.12 www 7185: return %returnhash;
7186: }
7187:
1.667 albertel 7188: # ------------------------------------------------------------ tmpput interface
7189: sub tmpput {
1.802 raeburn 7190: my ($storehash,$server,$context)=@_;
1.667 albertel 7191: my $items='';
1.800 albertel 7192: foreach my $item (keys(%$storehash)) {
7193: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7194: }
7195: $items=~s/\&$//;
1.802 raeburn 7196: if (defined($context)) {
7197: $items .= ':'.&escape($context);
7198: }
1.667 albertel 7199: return &reply("tmpput:$items",$server);
7200: }
7201:
7202: # ------------------------------------------------------------ tmpget interface
7203: sub tmpget {
1.688 albertel 7204: my ($token,$server)=@_;
7205: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7206: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7207: my %returnhash;
1.1172.2.85 raeburn 7208: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7209: return %returnhash;
7210: }
1.667 albertel 7211: foreach my $item (split(/\&/,$rep)) {
7212: my ($key,$value)=split(/=/,$item);
7213: $returnhash{&unescape($key)}=&thaw_unescape($value);
7214: }
7215: return %returnhash;
7216: }
7217:
1.1113 raeburn 7218: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7219: sub tmpdel {
7220: my ($token,$server)=@_;
7221: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7222: return &reply("tmpdel:$token",$server);
7223: }
7224:
1.1172.2.13 raeburn 7225: # ------------------------------------------------------------ get_timebased_id
7226:
7227: sub get_timebased_id {
7228: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7229: $maxtries) = @_;
7230: my ($newid,$error,$dellock);
7231: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7232: return ('','ok','invalid call to get suffix');
7233: }
7234:
7235: # set defaults for any optional args for which values were not supplied
7236: if ($who eq '') {
7237: $who = $env{'user.name'}.':'.$env{'user.domain'};
7238: }
7239: if (!$locktries) {
7240: $locktries = 3;
7241: }
7242: if (!$maxtries) {
7243: $maxtries = 10;
7244: }
7245:
7246: if (($cdom eq '') || ($cnum eq '')) {
7247: if ($env{'request.course.id'}) {
7248: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7249: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7250: }
7251: if (($cdom eq '') || ($cnum eq '')) {
7252: return ('','ok','call to get suffix not in course context');
7253: }
7254: }
7255:
7256: # construct locking item
7257: my $lockhash = {
7258: $prefix."\0".'locked_'.$keyid => $who,
7259: };
7260: my $tries = 0;
7261:
7262: # attempt to get lock on nohist_$namespace file
7263: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7264: while (($gotlock ne 'ok') && $tries <$locktries) {
7265: $tries ++;
7266: sleep 1;
7267: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7268: }
7269:
7270: # attempt to get unique identifier, based on current timestamp
7271: if ($gotlock eq 'ok') {
7272: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7273: my $id = time;
7274: $newid = $id;
1.1172.2.56 raeburn 7275: if ($idtype eq 'addcode') {
7276: $newid .= &sixnum_code();
7277: }
1.1172.2.13 raeburn 7278: my $idtries = 0;
7279: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7280: if ($idtype eq 'concat') {
7281: $newid = $id.$idtries;
1.1172.2.56 raeburn 7282: } elsif ($idtype eq 'addcode') {
7283: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7284: } else {
7285: $newid ++;
7286: }
7287: $idtries ++;
7288: }
7289: if (!exists($inuse{$prefix."\0".$newid})) {
7290: my %new_item = (
7291: $prefix."\0".$newid => $who,
7292: );
7293: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7294: $cdom,$cnum);
7295: if ($putresult ne 'ok') {
7296: undef($newid);
7297: $error = 'error saving new item: '.$putresult;
7298: }
7299: } else {
1.1172.2.56 raeburn 7300: undef($newid);
1.1172.2.13 raeburn 7301: $error = ('error: no unique suffix available for the new item ');
7302: }
7303: # remove lock
7304: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7305: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7306: } else {
7307: $error = "error: could not obtain lockfile\n";
7308: $dellock = 'ok';
1.1172.2.58 raeburn 7309: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7310: $dellock = 'nolock';
7311: }
1.1172.2.13 raeburn 7312: }
7313: return ($newid,$dellock,$error);
7314: }
7315:
1.1172.2.56 raeburn 7316: sub sixnum_code {
7317: my $code;
7318: for (0..6) {
7319: $code .= int( rand(9) );
7320: }
7321: return $code;
7322: }
7323:
1.765 albertel 7324: # -------------------------------------------------- portfolio access checking
7325:
7326: sub portfolio_access {
1.1172.2.77 raeburn 7327: my ($requrl,$clientip) = @_;
1.765 albertel 7328: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7329: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7330: if ($result) {
7331: my %setters;
7332: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7333: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7334: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7335: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7336: return 'B';
7337: }
7338: } else {
1.1172.2.142 raeburn 7339: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7340: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7341: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7342: return 'B';
7343: }
7344: }
7345: }
1.765 albertel 7346: if ($result eq 'ok') {
1.766 albertel 7347: return 'F';
1.765 albertel 7348: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7349: return 'A';
1.765 albertel 7350: }
1.766 albertel 7351: return '';
1.765 albertel 7352: }
7353:
7354: sub get_portfolio_access {
1.1172.2.77 raeburn 7355: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7356:
7357: if (!ref($access_hash)) {
7358: my $current_perms = &get_portfile_permissions($udom,$unum);
7359: my %access_controls = &get_access_controls($current_perms,$group,
7360: $file_name);
7361: $access_hash = $access_controls{$file_name};
7362: }
7363:
1.1172.2.77 raeburn 7364: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7365: my $now = time;
7366: if (ref($access_hash) eq 'HASH') {
7367: foreach my $key (keys(%{$access_hash})) {
7368: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7369: if ($start > $now) {
7370: next;
7371: }
7372: if ($end && $end<$now) {
7373: next;
7374: }
7375: if ($scope eq 'public') {
7376: $public = $key;
7377: last;
7378: } elsif ($scope eq 'guest') {
7379: $guest = $key;
7380: } elsif ($scope eq 'domains') {
7381: push(@domains,$key);
7382: } elsif ($scope eq 'users') {
7383: push(@users,$key);
7384: } elsif ($scope eq 'course') {
7385: push(@courses,$key);
7386: } elsif ($scope eq 'group') {
7387: push(@groups,$key);
1.1172.2.77 raeburn 7388: } elsif ($scope eq 'ip') {
7389: push(@ips,$key);
1.765 albertel 7390: }
7391: }
7392: if ($public) {
7393: return 'ok';
1.1172.2.77 raeburn 7394: } elsif (@ips > 0) {
7395: my $allowed;
7396: foreach my $ipkey (@ips) {
7397: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7398: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7399: $allowed = 1;
7400: last;
7401: }
7402: }
7403: }
7404: if ($allowed) {
7405: return 'ok';
7406: }
1.765 albertel 7407: }
7408: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7409: if ($guest) {
7410: return $guest;
7411: }
7412: } else {
7413: if (@domains > 0) {
7414: foreach my $domkey (@domains) {
7415: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7416: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7417: return 'ok';
7418: }
7419: }
7420: }
7421: }
7422: if (@users > 0) {
7423: foreach my $userkey (@users) {
1.865 raeburn 7424: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7425: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7426: if (ref($item) eq 'HASH') {
7427: if (($item->{'uname'} eq $env{'user.name'}) &&
7428: ($item->{'udom'} eq $env{'user.domain'})) {
7429: return 'ok';
7430: }
7431: }
7432: }
7433: }
1.765 albertel 7434: }
7435: }
7436: my %roleshash;
7437: my @courses_and_groups = @courses;
7438: push(@courses_and_groups,@groups);
7439: if (@courses_and_groups > 0) {
7440: my (%allgroups,%allroles);
7441: my ($start,$end,$role,$sec,$group);
7442: foreach my $envkey (%env) {
1.1060 raeburn 7443: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7444: my $cid = $2.'_'.$3;
7445: if ($1 eq 'gr') {
7446: $group = $4;
7447: $allgroups{$cid}{$group} = $env{$envkey};
7448: } else {
7449: if ($4 eq '') {
7450: $sec = 'none';
7451: } else {
7452: $sec = $4;
7453: }
7454: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7455: }
1.811 albertel 7456: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7457: my $cid = $2.'_'.$3;
7458: if ($4 eq '') {
7459: $sec = 'none';
7460: } else {
7461: $sec = $4;
7462: }
7463: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7464: }
7465: }
7466: if (keys(%allroles) == 0) {
7467: return;
7468: }
7469: foreach my $key (@courses_and_groups) {
7470: my %content = %{$$access_hash{$key}};
7471: my $cnum = $content{'number'};
7472: my $cdom = $content{'domain'};
7473: my $cid = $cdom.'_'.$cnum;
7474: if (!exists($allroles{$cid})) {
7475: next;
7476: }
7477: foreach my $role_id (keys(%{$content{'roles'}})) {
7478: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7479: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7480: my @status = @{$content{'roles'}{$role_id}{'access'}};
7481: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7482: foreach my $role (keys(%{$allroles{$cid}})) {
7483: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7484: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7485: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7486: if (grep/^all$/,@sections) {
7487: return 'ok';
7488: } else {
7489: if (grep/^$sec$/,@sections) {
7490: return 'ok';
7491: }
7492: }
7493: }
7494: }
7495: if (keys(%{$allgroups{$cid}}) == 0) {
7496: if (grep/^none$/,@groups) {
7497: return 'ok';
7498: }
7499: } else {
7500: if (grep/^all$/,@groups) {
7501: return 'ok';
7502: }
7503: foreach my $group (keys(%{$allgroups{$cid}})) {
7504: if (grep/^$group$/,@groups) {
7505: return 'ok';
7506: }
7507: }
7508: }
7509: }
7510: }
7511: }
7512: }
7513: }
7514: if ($guest) {
7515: return $guest;
7516: }
7517: }
7518: }
7519: return;
7520: }
7521:
7522: sub course_group_datechecker {
7523: my ($dates,$now,$status) = @_;
7524: my ($start,$end) = split(/\./,$dates);
7525: if (!$start && !$end) {
7526: return 'ok';
7527: }
7528: if (grep/^active$/,@{$status}) {
7529: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7530: return 'ok';
7531: }
7532: }
7533: if (grep/^previous$/,@{$status}) {
7534: if ($end > $now ) {
7535: return 'ok';
7536: }
7537: }
7538: if (grep/^future$/,@{$status}) {
7539: if ($start > $now) {
7540: return 'ok';
7541: }
7542: }
7543: return;
7544: }
7545:
7546: sub parse_portfolio_url {
7547: my ($url) = @_;
7548:
7549: my ($type,$udom,$unum,$group,$file_name);
7550:
1.823 albertel 7551: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7552: $type = 1;
7553: $udom = $1;
7554: $unum = $2;
7555: $file_name = $3;
1.823 albertel 7556: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7557: $type = 2;
7558: $udom = $1;
7559: $unum = $2;
7560: $group = $3;
7561: $file_name = $3.'/'.$4;
7562: }
7563: if (wantarray) {
7564: return ($type,$udom,$unum,$file_name,$group);
7565: }
7566: return $type;
7567: }
7568:
7569: sub is_portfolio_url {
7570: my ($url) = @_;
7571: return scalar(&parse_portfolio_url($url));
7572: }
7573:
1.798 raeburn 7574: sub is_portfolio_file {
7575: my ($file) = @_;
1.820 raeburn 7576: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7577: return 1;
7578: }
7579: return;
7580: }
7581:
1.976 raeburn 7582: sub usertools_access {
1.1084 raeburn 7583: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7584: my ($access,%tools);
7585: if ($context eq '') {
7586: $context = 'tools';
7587: }
7588: if ($context eq 'requestcourses') {
7589: %tools = (
7590: official => 1,
7591: unofficial => 1,
1.1006 raeburn 7592: community => 1,
1.1172.2.37 raeburn 7593: textbook => 1,
1.985 raeburn 7594: );
1.1172.2.9 raeburn 7595: } elsif ($context eq 'requestauthor') {
7596: %tools = (
7597: requestauthor => 1,
7598: );
1.985 raeburn 7599: } else {
7600: %tools = (
7601: aboutme => 1,
7602: blog => 1,
1.1172.2.6 raeburn 7603: webdav => 1,
1.985 raeburn 7604: portfolio => 1,
7605: );
7606: }
1.976 raeburn 7607: return if (!defined($tools{$tool}));
7608:
1.1172.2.35 raeburn 7609: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7610: $udom = $env{'user.domain'};
7611: $uname = $env{'user.name'};
7612: }
7613:
1.978 raeburn 7614: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7615: if ($action ne 'reload') {
1.985 raeburn 7616: if ($context eq 'requestcourses') {
7617: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7618: } elsif ($context eq 'requestauthor') {
7619: return $env{'environment.canrequest.author'};
1.985 raeburn 7620: } else {
7621: return $env{'environment.availabletools.'.$tool};
7622: }
7623: }
1.976 raeburn 7624: }
7625:
1.1172.2.9 raeburn 7626: my ($toolstatus,$inststatus,$envkey);
7627: if ($context eq 'requestauthor') {
7628: $envkey = $context;
7629: } else {
7630: $envkey = $context.'.'.$tool;
7631: }
1.976 raeburn 7632:
1.985 raeburn 7633: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7634: ($action ne 'reload')) {
1.1172.2.9 raeburn 7635: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7636: $inststatus = $env{'environment.inststatus'};
7637: } else {
1.1084 raeburn 7638: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7639: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7640: $inststatus = $userenvref->{'inststatus'};
7641: } else {
1.1172.2.9 raeburn 7642: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7643: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7644: $inststatus = $userenv{'inststatus'};
7645: }
1.976 raeburn 7646: }
7647:
7648: if ($toolstatus ne '') {
7649: if ($toolstatus) {
7650: $access = 1;
7651: } else {
7652: $access = 0;
7653: }
7654: return $access;
7655: }
7656:
1.1084 raeburn 7657: my ($is_adv,%domdef);
7658: if (ref($is_advref) eq 'HASH') {
7659: $is_adv = $is_advref->{'is_adv'};
7660: } else {
7661: $is_adv = &is_advanced_user($udom,$uname);
7662: }
7663: if (ref($domdefref) eq 'HASH') {
7664: %domdef = %{$domdefref};
7665: } else {
7666: %domdef = &get_domain_defaults($udom);
7667: }
1.976 raeburn 7668: if (ref($domdef{$tool}) eq 'HASH') {
7669: if ($is_adv) {
7670: if ($domdef{$tool}{'_LC_adv'} ne '') {
7671: if ($domdef{$tool}{'_LC_adv'}) {
7672: $access = 1;
7673: } else {
7674: $access = 0;
7675: }
7676: return $access;
7677: }
7678: }
7679: if ($inststatus ne '') {
7680: my ($hasaccess,$hasnoaccess);
7681: foreach my $affiliation (split(/:/,$inststatus)) {
7682: if ($domdef{$tool}{$affiliation} ne '') {
7683: if ($domdef{$tool}{$affiliation}) {
7684: $hasaccess = 1;
7685: } else {
7686: $hasnoaccess = 1;
7687: }
7688: }
7689: }
7690: if ($hasaccess || $hasnoaccess) {
7691: if ($hasaccess) {
7692: $access = 1;
7693: } elsif ($hasnoaccess) {
7694: $access = 0;
7695: }
7696: return $access;
7697: }
7698: } else {
7699: if ($domdef{$tool}{'default'} ne '') {
7700: if ($domdef{$tool}{'default'}) {
7701: $access = 1;
7702: } elsif ($domdef{$tool}{'default'} == 0) {
7703: $access = 0;
7704: }
7705: return $access;
7706: }
7707: }
7708: } else {
1.1172.2.6 raeburn 7709: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7710: $access = 1;
7711: } else {
7712: $access = 0;
7713: }
1.976 raeburn 7714: return $access;
7715: }
7716: }
7717:
1.1050 raeburn 7718: sub is_course_owner {
7719: my ($cdom,$cnum,$udom,$uname) = @_;
7720: if (($udom eq '') || ($uname eq '')) {
7721: $udom = $env{'user.domain'};
7722: $uname = $env{'user.name'};
7723: }
7724: unless (($udom eq '') || ($uname eq '')) {
7725: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7726: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7727: return 1;
7728: } else {
7729: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7730: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7731: return 1;
7732: }
7733: }
7734: }
7735: }
7736: return;
7737: }
7738:
1.976 raeburn 7739: sub is_advanced_user {
7740: my ($udom,$uname) = @_;
1.1085 raeburn 7741: if ($udom ne '' && $uname ne '') {
7742: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7743: if (wantarray) {
7744: return ($env{'user.adv'},$env{'user.author'});
7745: } else {
7746: return $env{'user.adv'};
7747: }
1.1085 raeburn 7748: }
7749: }
1.976 raeburn 7750: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7751: my %allroles;
1.1128 raeburn 7752: my ($is_adv,$is_author);
1.976 raeburn 7753: foreach my $role (keys(%roleshash)) {
7754: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7755: my $area = '/'.$tdomain.'/'.$trest;
7756: if ($sec ne '') {
7757: $area .= '/'.$sec;
7758: }
7759: if (($area ne '') && ($trole ne '')) {
7760: my $spec=$trole.'.'.$area;
7761: if ($trole =~ /^cr\//) {
7762: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7763: } elsif ($trole ne 'gr') {
7764: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7765: }
1.1128 raeburn 7766: if ($trole eq 'au') {
7767: $is_author = 1;
7768: }
1.976 raeburn 7769: }
7770: }
7771: foreach my $role (keys(%allroles)) {
7772: last if ($is_adv);
7773: foreach my $item (split(/:/,$allroles{$role})) {
7774: if ($item ne '') {
7775: my ($privilege,$restrictions)=split(/&/,$item);
7776: if ($privilege eq 'adv') {
7777: $is_adv = 1;
7778: last;
7779: }
7780: }
7781: }
7782: }
1.1128 raeburn 7783: if (wantarray) {
7784: return ($is_adv,$is_author);
7785: }
1.976 raeburn 7786: return $is_adv;
7787: }
1.798 raeburn 7788:
1.1035 raeburn 7789: sub check_can_request {
1.1036 raeburn 7790: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7791: my $canreq = 0;
7792: my ($types,$typename) = &Apache::loncommon::course_types();
7793: my @options = ('approval','validate','autolimit');
7794: my $optregex = join('|',@options);
7795: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7796: foreach my $type (@{$types}) {
7797: if (&usertools_access($env{'user.name'},
7798: $env{'user.domain'},
7799: $type,undef,'requestcourses')) {
7800: $canreq ++;
1.1036 raeburn 7801: if (ref($request_domains) eq 'HASH') {
7802: push(@{$request_domains->{$type}},$env{'user.domain'});
7803: }
1.1035 raeburn 7804: if ($dom eq $env{'user.domain'}) {
7805: $can_request->{$type} = 1;
7806: }
7807: }
7808: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7809: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7810: if (@curr > 0) {
1.1036 raeburn 7811: foreach my $item (@curr) {
7812: if (ref($request_domains) eq 'HASH') {
7813: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7814: if ($otherdom ne '') {
7815: if (ref($request_domains->{$type}) eq 'ARRAY') {
7816: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7817: push(@{$request_domains->{$type}},$otherdom);
7818: }
7819: } else {
7820: push(@{$request_domains->{$type}},$otherdom);
7821: }
7822: }
7823: }
7824: }
7825: unless($dom eq $env{'user.domain'}) {
7826: $canreq ++;
1.1035 raeburn 7827: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7828: $can_request->{$type} = 1;
7829: }
7830: }
7831: }
7832: }
7833: }
7834: }
7835: return $canreq;
7836: }
7837:
1.341 www 7838: # ---------------------------------------------- Custom access rule evaluation
7839:
7840: sub customaccess {
7841: my ($priv,$uri)=@_;
1.807 albertel 7842: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7843: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7844: $udom = &LONCAPA::clean_domain($udom);
7845: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7846: my $access=0;
1.800 albertel 7847: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7848: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7849: if ($type eq 'user') {
7850: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7851: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7852: if ($tdom) {
7853: if ($tdom ne $env{'user.domain'}) { next; }
7854: }
1.896 albertel 7855: if ($tuname) {
7856: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7857: }
7858: $access=($effect eq 'allow');
7859: last;
7860: }
7861: } else {
7862: if ($role) {
7863: if ($role ne $urole) { next; }
7864: }
7865: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7866: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7867: if ($tdom) {
7868: if ($tdom ne $udom) { next; }
7869: }
7870: if ($tcrs) {
7871: if ($tcrs ne $ucrs) { next; }
7872: }
7873: if ($tsec) {
7874: if ($tsec ne $usec) { next; }
7875: }
7876: $access=($effect eq 'allow');
7877: last;
7878: }
7879: if ($realm eq '' && $role eq '') {
7880: $access=($effect eq 'allow');
7881: }
1.402 bowersj2 7882: }
1.341 www 7883: }
7884: return $access;
7885: }
7886:
1.103 harris41 7887: # ------------------------------------------------- Check for a user privilege
1.12 www 7888:
7889: sub allowed {
1.1172.2.126 raeburn 7890: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7891: my $ver_orguri=$uri;
1.439 www 7892: $uri=&deversion($uri);
1.152 www 7893: my $orguri=$uri;
1.52 www 7894: $uri=&declutter($uri);
1.809 raeburn 7895:
1.810 raeburn 7896: if ($priv eq 'evb') {
7897: # Evade communication block restrictions for specified role in a course
7898: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7899: return $1;
7900: } else {
7901: return;
7902: }
7903: }
7904:
1.620 albertel 7905: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7906: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7907: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7908: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7909: && ($priv eq 'bre')) {
1.14 www 7910: return 'F';
1.159 www 7911: }
7912:
1.545 banghart 7913: # Free bre access to user's own portfolio contents
1.714 raeburn 7914: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7915: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7916: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7917: my %setters;
1.1172.2.142 raeburn 7918: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7919: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7920: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7921: return 'B';
7922: } else {
7923: return 'F';
7924: }
1.545 banghart 7925: }
7926:
1.762 raeburn 7927: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7928: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7929: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7930: if (exists($env{'request.course.id'})) {
7931: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7932: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7933: if (($domain eq $cdom) && ($name eq $cnum)) {
7934: my $courseprivid=$env{'request.course.id'};
7935: $courseprivid=~s/\_/\//;
7936: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7937: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7938: return $1;
1.762 raeburn 7939: } else {
7940: if ($env{'request.course.sec'}) {
7941: $courseprivid.='/'.$env{'request.course.sec'};
7942: }
7943: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7944: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7945: return $2;
7946: }
1.714 raeburn 7947: }
7948: }
7949: }
7950: }
7951:
1.159 www 7952: # Free bre to public access
7953:
7954: if ($priv eq 'bre') {
1.238 www 7955: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7956: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7957: return 'F';
7958: }
1.238 www 7959: if ($copyright eq 'priv') {
7960: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7961: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7962: return '';
7963: }
7964: }
7965: if ($copyright eq 'domain') {
7966: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7967: unless (($env{'user.domain'} eq $1) ||
7968: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7969: return '';
7970: }
1.262 matthew 7971: }
1.620 albertel 7972: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7973: # Library role, so allow browsing of resources in this domain.
7974: return 'F';
1.238 www 7975: }
1.341 www 7976: if ($copyright eq 'custom') {
7977: unless (&customaccess($priv,$uri)) { return ''; }
7978: }
1.14 www 7979: }
1.264 matthew 7980: # Domain coordinator is trying to create a course
1.620 albertel 7981: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7982: # uri is the requested domain in this case.
7983: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7984: # a role of dc for the domain in question.
1.620 albertel 7985: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7986: }
1.29 www 7987:
1.52 www 7988: my $thisallowed='';
7989: my $statecond=0;
7990: my $courseprivid='';
7991:
1.1039 raeburn 7992: my $ownaccess;
1.1043 raeburn 7993: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7994: if (($priv eq 'bro') && ($env{'user.author'})) {
7995: if ($uri eq '') {
7996: $ownaccess = 1;
7997: } else {
7998: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7999: my $udom = $env{'user.domain'};
8000: my $uname = $env{'user.name'};
8001: if ($uri =~ m{^\Q$udom\E/?$}) {
8002: $ownaccess = 1;
1.1040 raeburn 8003: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8004: unless ($uri =~ m{\.\./}) {
8005: $ownaccess = 1;
8006: }
8007: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8008: my $now = time;
8009: if ($uri =~ m{^([^/]+)/?$}) {
8010: my $adom = $1;
8011: foreach my $key (keys(%env)) {
1.1042 raeburn 8012: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8013: my ($start,$end) = split(/\./,$env{$key});
8014: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8015: $ownaccess = 1;
8016: last;
8017: }
8018: }
8019: }
8020: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8021: my $adom = $1;
8022: my $aname = $2;
1.1042 raeburn 8023: foreach my $role ('ca','aa') {
8024: if ($env{"user.role.$role./$adom/$aname"}) {
8025: my ($start,$end) =
1.1172.2.142 raeburn 8026: split(/\./,$env{"user.role.$role./$adom/$aname"});
8027: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8028: $ownaccess = 1;
8029: last;
8030: }
1.1039 raeburn 8031: }
8032: }
8033: }
8034: }
8035: }
8036: }
8037: }
8038:
1.52 www 8039: # Course
8040:
1.620 albertel 8041: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8042: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8043: $thisallowed.=$1;
8044: }
1.52 www 8045: }
1.29 www 8046:
1.52 www 8047: # Domain
8048:
1.620 albertel 8049: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8050: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8051: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8052: $thisallowed.=$1;
8053: }
1.12 www 8054: }
1.52 www 8055:
1.1141 raeburn 8056: # User who is not author or co-author might still be able to edit
8057: # resource of an author in the domain (e.g., if Domain Coordinator).
8058: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8059: (&allowed('mdc',$env{'request.course.id'}))) {
8060: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8061: $thisallowed.=$1;
8062: }
8063: }
8064:
1.52 www 8065: # Course: uri itself is a course
1.66 www 8066: my $courseuri=$uri;
8067: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8068: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8069:
1.620 albertel 8070: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8071: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8072: if ($priv eq 'mip') {
8073: my $rem = $1;
8074: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8075: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8076: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8077: if ($cdom ne '') {
8078: my %passwdconf = &get_passwdconf($cdom);
8079: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8080: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8081: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8082: my @inststatuses = split(':',$env{'environment.inststatus'});
8083: unless (@inststatuses) {
8084: @inststatuses = ('default');
8085: }
8086: foreach my $status (@inststatuses) {
8087: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8088: $thisallowed.=$rem;
8089: }
8090: }
8091: }
8092: }
8093: }
8094: }
8095: }
8096: } else {
8097: unless (($priv eq 'bro') && (!$ownaccess)) {
8098: $thisallowed.=$1;
8099: }
1.1039 raeburn 8100: }
1.12 www 8101: }
1.29 www 8102:
1.665 albertel 8103: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8104: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8105: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8106: $thisallowed='';
1.671 raeburn 8107: my ($match)=&is_on_map($uri);
8108: if ($match) {
8109: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8110: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8111: my $value = $1;
8112: if ($noblockcheck) {
8113: $thisallowed.=$value;
1.1162 raeburn 8114: } else {
1.1172.2.126 raeburn 8115: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8116: if (@blockers > 0) {
8117: $thisallowed = 'B';
8118: } else {
8119: $thisallowed.=$value;
8120: }
1.1162 raeburn 8121: }
1.671 raeburn 8122: }
8123: } else {
1.705 albertel 8124: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8125: if ($refuri) {
8126: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8127: $thisallowed='F';
1.671 raeburn 8128: } else {
8129: $refuri=&declutter($refuri);
8130: my ($match) = &is_on_map($refuri);
8131: if ($match) {
1.1172.2.65 raeburn 8132: if ($noblockcheck) {
1.1162 raeburn 8133: $thisallowed='F';
1.1172.2.65 raeburn 8134: } else {
1.1172.2.127 raeburn 8135: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8136: if (@blockers > 0) {
8137: $thisallowed = 'B';
8138: } else {
8139: $thisallowed='F';
8140: }
1.1162 raeburn 8141: }
1.671 raeburn 8142: }
1.669 raeburn 8143: }
1.671 raeburn 8144: }
8145: }
1.314 www 8146: }
1.492 albertel 8147:
1.766 albertel 8148: if ($priv eq 'bre'
8149: && $thisallowed ne 'F'
8150: && $thisallowed ne '2'
8151: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8152: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8153: }
8154:
1.52 www 8155: # Full access at system, domain or course-wide level? Exit.
1.29 www 8156: if ($thisallowed=~/F/) {
8157: return 'F';
8158: }
8159:
1.52 www 8160: # If this is generating or modifying users, exit with special codes
1.29 www 8161:
1.643 www 8162: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8163: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8164: my ($audom,$auname)=split('/',$uri);
1.643 www 8165: # no author name given, so this just checks on the general right to make a co-author in this domain
8166: unless ($auname) { return $thisallowed; }
8167: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8168: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8169: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8170: ($audom ne $env{'request.role.domain'}))) { return ''; }
8171: }
1.52 www 8172: return $thisallowed;
8173: }
8174: #
1.103 harris41 8175: # Gathered so far: system, domain and course wide privileges
1.52 www 8176: #
8177: # Course: See if uri or referer is an individual resource that is part of
8178: # the course
8179:
1.620 albertel 8180: if ($env{'request.course.id'}) {
1.232 www 8181:
1.1172.2.115 raeburn 8182: # If this is modifying password (internal auth) domains must match for user and user's role.
8183:
8184: if ($priv eq 'mip') {
8185: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8186: return $thisallowed;
8187: } else {
8188: return '';
8189: }
8190: }
8191:
1.620 albertel 8192: $courseprivid=$env{'request.course.id'};
8193: if ($env{'request.course.sec'}) {
8194: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8195: }
8196: $courseprivid=~s/\_/\//;
8197: my $checkreferer=1;
1.232 www 8198: my ($match,$cond)=&is_on_map($uri);
8199: if ($match) {
8200: $statecond=$cond;
1.620 albertel 8201: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8202: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8203: my $value = $1;
8204: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8205: if ($noblockcheck) {
1.1162 raeburn 8206: $thisallowed.=$value;
1.1172.2.65 raeburn 8207: } else {
1.1172.2.126 raeburn 8208: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8209: if (@blockers > 0) {
8210: $thisallowed = 'B';
8211: } else {
8212: $thisallowed.=$value;
8213: }
1.1162 raeburn 8214: }
8215: } else {
8216: $thisallowed.=$value;
8217: }
1.52 www 8218: $checkreferer=0;
8219: }
1.29 www 8220: }
1.1172.2.126 raeburn 8221:
1.148 www 8222: if ($checkreferer) {
1.620 albertel 8223: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8224: unless ($refuri) {
1.800 albertel 8225: foreach my $key (keys(%env)) {
8226: if ($key=~/^httpref\..*\*/) {
8227: my $pattern=$key;
1.156 www 8228: $pattern=~s/^httpref\.\/res\///;
1.148 www 8229: $pattern=~s/\*/\[\^\/\]\+/g;
8230: $pattern=~s/\//\\\//g;
1.152 www 8231: if ($orguri=~/$pattern/) {
1.800 albertel 8232: $refuri=$env{$key};
1.148 www 8233: }
8234: }
1.191 harris41 8235: }
1.148 www 8236: }
1.232 www 8237:
1.148 www 8238: if ($refuri) {
1.152 www 8239: $refuri=&declutter($refuri);
1.232 www 8240: my ($match,$cond)=&is_on_map($refuri);
8241: if ($match) {
8242: my $refstatecond=$cond;
1.620 albertel 8243: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8244: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8245: my $value = $1;
8246: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8247: if ($noblockcheck) {
1.1162 raeburn 8248: $thisallowed.=$value;
1.1172.2.65 raeburn 8249: } else {
1.1172.2.127 raeburn 8250: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8251: if (@blockers > 0) {
8252: $thisallowed = 'B';
8253: } else {
8254: $thisallowed.=$value;
8255: }
1.1162 raeburn 8256: }
8257: } else {
8258: $thisallowed.=$value;
8259: }
1.53 www 8260: $uri=$refuri;
8261: $statecond=$refstatecond;
1.52 www 8262: }
8263: }
1.148 www 8264: }
1.29 www 8265: }
1.52 www 8266: }
1.29 www 8267:
1.52 www 8268: #
1.103 harris41 8269: # Gathered now: all privileges that could apply, and condition number
1.52 www 8270: #
8271: #
8272: # Full or no access?
8273: #
1.29 www 8274:
1.52 www 8275: if ($thisallowed=~/F/) {
8276: return 'F';
8277: }
1.29 www 8278:
1.52 www 8279: unless ($thisallowed) {
8280: return '';
8281: }
1.29 www 8282:
1.52 www 8283: # Restrictions exist, deal with them
8284: #
8285: # C:according to course preferences
8286: # R:according to resource settings
8287: # L:unless locked
8288: # X:according to user session state
8289: #
8290:
8291: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8292: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8293: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8294: # courses, and 2 minutes for current course, in which user has st or ta role
8295: # which is neither expired nor a future role (unless current course).
1.52 www 8296:
1.1172.2.142 raeburn 8297: my ($needlockcheck,$now,$crsonly);
1.52 www 8298: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8299: $now = time;
8300: if ($priv eq 'bre') {
8301: if ($uri ne '') {
8302: if ($orguri =~ m{^/+res/}) {
8303: if ($uri =~ m{^lib/templates/}) {
8304: if ($env{'request.course.id'}) {
8305: $crsonly = 1;
8306: $needlockcheck = 1;
8307: }
8308: } else {
8309: $needlockcheck = 1;
8310: }
8311: } elsif ($env{'request.course.id'}) {
8312: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8313: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8314: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8315: $crsonly = 1;
8316: }
8317: $needlockcheck = 1;
8318: }
8319: }
8320: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8321: $needlockcheck = 1;
8322: }
8323: }
8324: if ($needlockcheck) {
8325: foreach my $envkey (keys(%env)) {
1.54 www 8326: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8327: my $courseid=$2;
8328: my $roleid=$1.'.'.$2;
1.92 www 8329: $courseid=~s/^\///;
1.1172.2.142 raeburn 8330: unless ($env{'request.role'} eq $roleid) {
8331: my ($start,$end) = split(/\./,$env{$envkey});
8332: next unless (($now >= $start) && (!$end || $end > $now));
8333: }
1.54 www 8334: my $expiretime=600;
1.620 albertel 8335: if ($env{'request.role'} eq $roleid) {
1.54 www 8336: $expiretime=120;
8337: }
8338: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8339: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8340: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8341: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8342: }
1.620 albertel 8343: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8344: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8345: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8346: &log($env{'user.domain'},$env{'user.name'},
8347: $env{'user.home'},
1.57 www 8348: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8349: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8350: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8351: return '';
8352: }
8353: }
1.620 albertel 8354: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8355: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8356: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8357: &log($env{'user.domain'},$env{'user.name'},
8358: $env{'user.home'},
1.57 www 8359: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8360: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8361: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8362: return '';
8363: }
8364: }
8365: }
1.29 www 8366: }
1.52 www 8367: }
1.1172.2.126 raeburn 8368:
1.52 www 8369: #
8370: # Rest of the restrictions depend on selected course
8371: #
8372:
1.620 albertel 8373: unless ($env{'request.course.id'}) {
1.766 albertel 8374: if ($thisallowed eq 'A') {
8375: return 'A';
1.814 raeburn 8376: } elsif ($thisallowed eq 'B') {
8377: return 'B';
1.766 albertel 8378: } else {
8379: return '1';
8380: }
1.52 www 8381: }
1.29 www 8382:
1.52 www 8383: #
8384: # Now user is definitely in a course
8385: #
1.53 www 8386:
8387:
8388: # Course preferences
8389:
8390: if ($thisallowed=~/C/) {
1.620 albertel 8391: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8392: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8393: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8394: =~/\Q$rolecode\E/) {
1.1103 raeburn 8395: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8396: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8397: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8398: $env{'request.course.id'});
8399: }
1.237 www 8400: return '';
8401: }
8402:
1.620 albertel 8403: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8404: =~/\Q$unamedom\E/) {
1.1103 raeburn 8405: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8406: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8407: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8408: $env{'request.course.id'});
8409: }
1.54 www 8410: return '';
8411: }
1.53 www 8412: }
8413:
8414: # Resource preferences
8415:
8416: if ($thisallowed=~/R/) {
1.620 albertel 8417: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8418: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8419: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8420: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8421: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8422: }
8423: return '';
1.54 www 8424: }
1.53 www 8425: }
1.30 www 8426:
1.246 www 8427: # Restricted by state or randomout?
1.30 www 8428:
1.52 www 8429: if ($thisallowed=~/X/) {
1.620 albertel 8430: if ($env{'acc.randomout'}) {
1.579 albertel 8431: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8432: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8433: return '';
8434: }
1.247 www 8435: }
8436: if (&condval($statecond)) {
1.52 www 8437: return '2';
8438: } else {
8439: return '';
8440: }
8441: }
1.30 www 8442:
1.766 albertel 8443: if ($thisallowed eq 'A') {
8444: return 'A';
1.814 raeburn 8445: } elsif ($thisallowed eq 'B') {
8446: return 'B';
1.766 albertel 8447: }
1.52 www 8448: return 'F';
1.232 www 8449: }
1.1162 raeburn 8450:
1.1172.2.13 raeburn 8451: # ------------------------------------------- Check construction space access
8452:
8453: sub constructaccess {
8454: my ($url,$setpriv)=@_;
8455:
8456: # We do not allow editing of previous versions of files
8457: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8458:
8459: # Get username and domain from URL
8460: my ($ownername,$ownerdomain,$ownerhome);
8461:
8462: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8463: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8464:
8465: # The URL does not really point to any authorspace, forget it
8466: unless (($ownername) && ($ownerdomain)) { return ''; }
8467:
8468: # Now we need to see if the user has access to the authorspace of
8469: # $ownername at $ownerdomain
8470:
8471: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8472: # Real author for this?
8473: $ownerhome = $env{'user.home'};
8474: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8475: return ($ownername,$ownerdomain,$ownerhome);
8476: }
8477: } else {
8478: # Co-author for this?
8479: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8480: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8481: $ownerhome = &homeserver($ownername,$ownerdomain);
8482: return ($ownername,$ownerdomain,$ownerhome);
8483: }
8484: }
8485:
8486: # We don't have any access right now. If we are not possibly going to do anything about this,
8487: # we might as well leave
8488: unless ($setpriv) { return ''; }
8489:
8490: # Backdoor access?
8491: my $allowed=&allowed('eco',$ownerdomain);
8492: # Nope
8493: unless ($allowed) { return ''; }
8494: # Looks like we may have access, but could be locked by the owner of the construction space
8495: if ($allowed eq 'U') {
8496: my %blocked=&get('environment',['domcoord.author'],
8497: $ownerdomain,$ownername);
8498: # Is blocked by owner
8499: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8500: }
8501: if (($allowed eq 'F') || ($allowed eq 'U')) {
8502: # Grant temporary access
8503: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8504: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8505: if (!$update) { $update = $then; }
8506: my $refresh=$env{'user.refresh.time'};
8507: if (!$refresh) { $refresh = $update; }
8508: my $now = time;
8509: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8510: $now,'ca','constructaccess');
8511: $ownerhome = &homeserver($ownername,$ownerdomain);
8512: return($ownername,$ownerdomain,$ownerhome);
8513: }
8514: # No business here
8515: return '';
8516: }
8517:
1.1172.2.66 raeburn 8518: # ----------------------------------------------------------- Content Blocking
8519:
8520: {
8521: # Caches for faster Course Contents display where content blocking
8522: # is in operation (i.e., interval param set) for timed quiz.
8523: #
8524: # User for whom data are being temporarily cached.
8525: my $cacheduser='';
1.1172.2.126 raeburn 8526: # Course for which data are being temporarily cached.
8527: my $cachedcid='';
1.1172.2.66 raeburn 8528: # Cached blockers for this user (a hash of blocking items).
8529: my %cachedblockers=();
8530: # When the data were last cached.
8531: my $cachedlast='';
8532:
8533: sub load_all_blockers {
1.1172.2.128 raeburn 8534: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8535: if (($uname ne '') && ($udom ne '')) {
8536: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8537: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8538: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8539: return;
8540: }
8541: }
8542: $cachedlast=time;
8543: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8544: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8545: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8546: return;
1.1172.2.66 raeburn 8547: }
8548:
1.1162 raeburn 8549: sub get_comm_blocks {
8550: my ($cdom,$cnum) = @_;
8551: if ($cdom eq '' || $cnum eq '') {
8552: return unless ($env{'request.course.id'});
8553: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8554: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8555: }
8556: my %commblocks;
8557: my $hashid=$cdom.'_'.$cnum;
8558: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8559: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8560: %commblocks = %{$blocksref};
8561: } else {
8562: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8563: my $cachetime = 600;
8564: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8565: }
8566: return %commblocks;
8567: }
8568:
1.1172.2.66 raeburn 8569: sub get_commblock_resources {
8570: my ($blocks) = @_;
8571: my %blockers = ();
8572: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8573: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8574: if ($env{'request.course.sec'}) {
8575: $courseurl .= '/'.$env{'request.course.sec'};
8576: }
8577: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8578: my %commblocks;
8579: if (ref($blocks) eq 'HASH') {
8580: %commblocks = %{$blocks};
8581: } else {
8582: %commblocks = &get_comm_blocks();
8583: }
1.1172.2.66 raeburn 8584: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8585: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8586: return %blockers unless (ref($navmap));
8587: my $now = time;
1.1162 raeburn 8588: foreach my $block (keys(%commblocks)) {
8589: if ($block =~ /^(\d+)____(\d+)$/) {
8590: my ($start,$end) = ($1,$2);
8591: if ($start <= $now && $end >= $now) {
8592: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8593: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8594: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8595: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8596: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8597: }
8598: }
8599: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8600: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8601: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8602: }
8603: }
8604: }
8605: }
8606: }
8607: } elsif ($block =~ /^firstaccess____(.+)$/) {
8608: my $item = $1;
8609: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8610: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8611: my (@interval,$mapname);
1.1172.2.66 raeburn 8612: my $type = 'map';
8613: if ($item eq 'course') {
8614: $type = 'course';
8615: @interval=&EXT("resource.0.interval");
8616: } else {
8617: if ($item =~ /___\d+___/) {
8618: $type = 'resource';
8619: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8620: } else {
1.1172.2.142 raeburn 8621: $mapname = &deversion($item);
8622: if (ref($navmap)) {
8623: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8624: @interval = ($timelimit,'map');
1.1162 raeburn 8625: }
8626: }
1.1172.2.66 raeburn 8627: }
8628: if ($interval[0] =~ /^\d+$/) {
8629: my $first_access;
8630: if ($type eq 'resource') {
8631: $first_access=&get_first_access($interval[1],$item);
8632: } elsif ($type eq 'map') {
8633: $first_access=&get_first_access($interval[1],undef,$item);
8634: } else {
8635: $first_access=&get_first_access($interval[1]);
8636: }
8637: if ($first_access) {
8638: my $timesup = $first_access+$interval[0];
8639: if ($timesup > $now) {
8640: my $activeblock;
1.1172.2.142 raeburn 8641: if ($type eq 'resource') {
8642: if (ref($navmap)) {
8643: my $res = $navmap->getBySymb($item);
8644: if ($res->answerable()) {
8645: $activeblock = 1;
8646: }
8647: }
8648: } elsif ($type eq 'map') {
8649: my $mapsymb = &symbread($mapname,1);
8650: if (($mapsymb) && (ref($navmap))) {
8651: my $mapres = $navmap->getBySymb($mapsymb);
8652: if (ref($mapres)) {
8653: my $first = $mapres->map_start();
8654: my $finish = $mapres->map_finish();
8655: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8656: if (ref($it)) {
8657: my $res;
8658: while ($res = $it->next(undef,1)) {
8659: next unless (ref($res));
8660: my $symb = $res->symb();
8661: next if (($symb eq $mapsymb) || ($symb eq ''));
8662: @interval=&EXT("resource.0.interval",$symb);
8663: if ($interval[1] eq 'map') {
8664: if ($res->answerable()) {
8665: $activeblock = 1;
8666: last;
8667: }
8668: }
8669: }
8670: }
8671: }
1.1172.2.66 raeburn 8672: }
8673: }
8674: if ($activeblock) {
8675: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8676: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8677: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8678: }
8679: }
8680: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8681: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8682: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8683: }
1.1162 raeburn 8684: }
8685: }
8686: }
8687: }
8688: }
8689: }
8690: }
8691: }
8692: }
1.1172.2.66 raeburn 8693: return %blockers;
1.1162 raeburn 8694: }
8695:
1.1172.2.66 raeburn 8696: sub has_comm_blocking {
1.1172.2.128 raeburn 8697: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8698: my @blockers;
8699: return unless ($env{'request.course.id'});
8700: return unless ($priv eq 'bre');
8701: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8702: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8703: if ($env{'request.course.sec'}) {
8704: $courseurl .= '/'.$env{'request.course.sec'};
8705: }
8706: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8707: my %blockinfo;
8708: if (ref($blocks) eq 'HASH') {
8709: %blockinfo = &get_commblock_resources($blocks);
8710: } else {
8711: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8712: %blockinfo = %cachedblockers;
8713: }
8714: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8715: my (%possibles,@symbs);
8716: if (!$symb) {
1.1172.2.128 raeburn 8717: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8718: }
1.1172.2.66 raeburn 8719: if ($symb) {
8720: @symbs = ($symb);
8721: } elsif (keys(%possibles)) {
8722: @symbs = keys(%possibles);
8723: }
8724: my $noblock;
8725: foreach my $symb (@symbs) {
8726: last if ($noblock);
8727: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8728: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8729: if ($block =~ /^firstaccess____(.+)$/) {
8730: my $item = $1;
1.1172.2.126 raeburn 8731: unless ($blocked) {
8732: if (($item eq $map) || ($item eq $symb)) {
8733: $noblock = 1;
8734: last;
8735: }
1.1172.2.66 raeburn 8736: }
1.1162 raeburn 8737: }
1.1172.2.128 raeburn 8738: if (ref($blockinfo{$block}) eq 'HASH') {
8739: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8740: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8741: unless (grep(/^\Q$block\E$/,@blockers)) {
8742: push(@blockers,$block);
8743: }
8744: }
8745: }
1.1172.2.128 raeburn 8746: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8747: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8748: unless (grep(/^\Q$block\E$/,@blockers)) {
8749: push(@blockers,$block);
8750: }
1.1172.2.66 raeburn 8751: }
8752: }
1.1162 raeburn 8753: }
8754: }
8755: }
1.1172.2.126 raeburn 8756: unless ($noblock) {
8757: return @blockers;
8758: }
8759: return;
1.1172.2.66 raeburn 8760: }
1.1162 raeburn 8761: }
8762:
1.1172.2.66 raeburn 8763: # -------------------------------- Deversion and split uri into path an filename
8764:
1.1133 foxr 8765: #
1.1172.2.66 raeburn 8766: # Removes the version from a URI and
1.1133 foxr 8767: # splits it in to its filename and path to the filename.
8768: # Seems like File::Basename could have done this more clearly.
8769: # Parameters:
8770: # $uri - input URI
8771: # Returns:
8772: # Two element list consisting of
8773: # $pathname - the URI up to and excluding the trailing /
8774: # $filename - The part of the URI following the last /
8775: # NOTE:
8776: # Another realization of this is simply:
8777: # use File::Basename;
8778: # ...
8779: # $uri = shift;
8780: # $filename = basename($uri);
8781: # $path = dirname($uri);
8782: # return ($filename, $path);
8783: #
8784: # The implementation below is probably faster however.
8785: #
1.710 albertel 8786: sub split_uri_for_cond {
8787: my $uri=&deversion(&declutter(shift));
8788: my @uriparts=split(/\//,$uri);
8789: my $filename=pop(@uriparts);
8790: my $pathname=join('/',@uriparts);
8791: return ($pathname,$filename);
8792: }
1.232 www 8793: # --------------------------------------------------- Is a resource on the map?
8794:
8795: sub is_on_map {
1.710 albertel 8796: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8797: #Trying to find the conditional for the file
1.620 albertel 8798: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8799: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8800: if ($match) {
1.289 bowersj2 8801: return (1,$1);
8802: } else {
1.434 www 8803: return (0,0);
1.289 bowersj2 8804: }
1.12 www 8805: }
8806:
1.427 www 8807: # --------------------------------------------------------- Get symb from alias
8808:
8809: sub get_symb_from_alias {
8810: my $symb=shift;
8811: my ($map,$resid,$url)=&decode_symb($symb);
8812: # Already is a symb
8813: if ($url) { return $symb; }
8814: # Must be an alias
8815: my $aliassymb='';
8816: my %bighash;
1.620 albertel 8817: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8818: &GDBM_READER(),0640)) {
8819: my $rid=$bighash{'mapalias_'.$symb};
8820: if ($rid) {
8821: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8822: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8823: $resid,$bighash{'src_'.$rid});
1.427 www 8824: }
8825: untie %bighash;
8826: }
8827: return $aliassymb;
8828: }
8829:
1.12 www 8830: # ----------------------------------------------------------------- Define Role
8831:
8832: sub definerole {
8833: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8834: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8835: foreach my $role (split(':',$sysrole)) {
8836: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8837: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8838: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8839: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8840: return "refused:s:$crole&$cqual";
8841: }
8842: }
1.191 harris41 8843: }
1.800 albertel 8844: foreach my $role (split(':',$domrole)) {
8845: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8846: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8847: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8848: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8849: return "refused:d:$crole&$cqual";
8850: }
8851: }
1.191 harris41 8852: }
1.800 albertel 8853: foreach my $role (split(':',$courole)) {
8854: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8855: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8856: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8857: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8858: return "refused:c:$crole&$cqual";
8859: }
8860: }
1.191 harris41 8861: }
1.1172.2.84 raeburn 8862: my $uhome;
8863: if (($uname ne '') && ($udom ne '')) {
8864: $uhome = &homeserver($uname,$udom);
8865: return $uhome if ($uhome eq 'no_host');
8866: } else {
8867: $uname = $env{'user.name'};
8868: $udom = $env{'user.domain'};
8869: $uhome = $env{'user.home'};
8870: }
1.620 albertel 8871: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8872: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8873: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8874: return reply($command,$uhome);
1.12 www 8875: } else {
8876: return 'refused';
8877: }
1.105 harris41 8878: }
8879:
8880: # ---------------- Make a metadata query against the network of library servers
8881:
8882: sub metadata_query {
1.1172.2.33 raeburn 8883: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8884: my %rhash;
1.845 albertel 8885: my %libserv = &all_library();
1.244 matthew 8886: my @server_list = (defined($server_array) ? @$server_array
8887: : keys(%libserv) );
8888: for my $server (@server_list) {
1.1172.2.33 raeburn 8889: my $domains = '';
8890: if (ref($domains_hash) eq 'HASH') {
8891: $domains = $domains_hash->{$server};
8892: }
1.118 harris41 8893: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8894: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8895: $rhash{$server}=$reply;
8896: }
8897: else {
8898: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8899: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8900: $server);
8901: $rhash{$server}=$reply;
8902: }
1.112 harris41 8903: }
1.118 harris41 8904: return \%rhash;
1.240 www 8905: }
8906:
8907: # ----------------------------------------- Send log queries and wait for reply
8908:
8909: sub log_query {
8910: my ($uname,$udom,$query,%filters)=@_;
8911: my $uhome=&homeserver($uname,$udom);
8912: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8913: my $uhost=&hostname($uhome);
1.800 albertel 8914: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8915: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8916: $uhome);
1.479 albertel 8917: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8918: return get_query_reply($queryid);
8919: }
8920:
1.818 raeburn 8921: # -------------------------- Update MySQL table for portfolio file
8922:
8923: sub update_portfolio_table {
1.821 raeburn 8924: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8925: if ($group ne '') {
8926: $file_name =~s /^\Q$group\E//;
8927: }
1.818 raeburn 8928: my $homeserver = &homeserver($uname,$udom);
8929: my $queryid=
1.821 raeburn 8930: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8931: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8932: my $reply = &get_query_reply($queryid);
8933: return $reply;
8934: }
8935:
1.899 raeburn 8936: # -------------------------- Update MySQL allusers table
8937:
8938: sub update_allusers_table {
8939: my ($uname,$udom,$names) = @_;
8940: my $homeserver = &homeserver($uname,$udom);
8941: my $queryid=
8942: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8943: 'lastname='.&escape($names->{'lastname'}).'%%'.
8944: 'firstname='.&escape($names->{'firstname'}).'%%'.
8945: 'middlename='.&escape($names->{'middlename'}).'%%'.
8946: 'generation='.&escape($names->{'generation'}).'%%'.
8947: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8948: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8949: return;
1.899 raeburn 8950: }
8951:
1.508 raeburn 8952: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8953:
8954: sub fetch_enrollment_query {
1.511 raeburn 8955: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8956: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8957: my $maxtries = 1;
1.508 raeburn 8958: if ($context eq 'automated') {
8959: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8960: $sleep = 2;
8961: $loopmax = 100;
1.547 raeburn 8962: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8963: } else {
8964: $homeserver = &homeserver($cnum,$dom);
8965: }
1.838 albertel 8966: my $host=&hostname($homeserver);
1.506 raeburn 8967: my $cmd = '';
1.1000 raeburn 8968: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8969: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8970: }
8971: $cmd =~ s/%%$//;
8972: $cmd = &escape($cmd);
8973: my $query = 'fetchenrollment';
1.620 albertel 8974: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8975: unless ($queryid=~/^\Q$host\E\_/) {
8976: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8977: return 'error: '.$queryid;
8978: }
1.1172.2.93 raeburn 8979: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8980: my $tries = 1;
8981: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8982: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8983: $tries ++;
8984: }
1.526 raeburn 8985: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8986: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8987: } else {
1.901 albertel 8988: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8989: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8990: foreach my $line (@responses) {
8991: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8992: $$replyref{$key} = $value;
8993: }
8994: } else {
1.1117 foxr 8995: my $pathname = LONCAPA::tempdir();
1.800 albertel 8996: foreach my $line (@responses) {
8997: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8998: $$replyref{$key} = $value;
8999: if ($value > 0) {
1.800 albertel 9000: foreach my $item (@{$$affiliatesref{$key}}) {
9001: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9002: my $destname = $pathname.'/'.$filename;
9003: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9004: if ($xml_classlist =~ /^error/) {
9005: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9006: } else {
1.1172.2.96 raeburn 9007: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9008: print FILE &unescape($xml_classlist);
9009: close(FILE);
1.526 raeburn 9010: } else {
9011: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9012: }
9013: }
9014: }
9015: }
9016: }
9017: }
9018: return 'ok';
9019: }
9020: return 'error';
9021: }
9022:
1.242 www 9023: sub get_query_reply {
1.1172.2.79 raeburn 9024: my ($queryid,$sleep,$loopmax) = @_;
9025: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9026: $sleep = 0.2;
9027: }
9028: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9029: $loopmax = 100;
9030: }
1.1117 foxr 9031: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9032: my $reply='';
1.1172.2.79 raeburn 9033: for (1..$loopmax) {
9034: sleep($sleep);
1.240 www 9035: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9036: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9037: $reply = join('',<$fh>);
9038: close($fh);
1.240 www 9039: } else { return 'error: reply_file_error'; }
1.242 www 9040: return &unescape($reply);
9041: }
1.240 www 9042: }
1.242 www 9043: return 'timeout:'.$queryid;
1.240 www 9044: }
9045:
9046: sub courselog_query {
1.241 www 9047: #
9048: # possible filters:
9049: # url: url or symb
9050: # username
9051: # domain
9052: # action: view, submit, grade
9053: # start: timestamp
9054: # end: timestamp
9055: #
1.240 www 9056: my (%filters)=@_;
1.620 albertel 9057: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9058: if ($filters{'url'}) {
9059: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9060: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9061: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9062: }
1.620 albertel 9063: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9064: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9065: return &log_query($cname,$cdom,'courselog',%filters);
9066: }
9067:
9068: sub userlog_query {
1.858 raeburn 9069: #
9070: # possible filters:
9071: # action: log check role
9072: # start: timestamp
9073: # end: timestamp
9074: #
1.240 www 9075: my ($uname,$udom,%filters)=@_;
9076: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9077: }
9078:
1.506 raeburn 9079: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9080:
9081: sub auto_run {
1.508 raeburn 9082: my ($cnum,$cdom) = @_;
1.876 raeburn 9083: my $response = 0;
9084: my $settings;
9085: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9086: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9087: $settings = $domconfig{'autoenroll'};
9088: if ($settings->{'run'} eq '1') {
9089: $response = 1;
9090: }
9091: } else {
1.934 raeburn 9092: my $homeserver;
9093: if (&is_course($cdom,$cnum)) {
9094: $homeserver = &homeserver($cnum,$cdom);
9095: } else {
9096: $homeserver = &domain($cdom,'primary');
9097: }
9098: if ($homeserver ne 'no_host') {
9099: $response = &reply('autorun:'.$cdom,$homeserver);
9100: }
1.876 raeburn 9101: }
1.506 raeburn 9102: return $response;
9103: }
1.776 albertel 9104:
1.506 raeburn 9105: sub auto_get_sections {
1.508 raeburn 9106: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9107: my $homeserver;
9108: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9109: $homeserver = &homeserver($cnum,$cdom);
9110: }
9111: if (!defined($homeserver)) {
9112: if ($cdom =~ /^$match_domain$/) {
9113: $homeserver = &domain($cdom,'primary');
9114: }
9115: }
9116: my @secs;
9117: if (defined($homeserver)) {
9118: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9119: unless ($response eq 'refused') {
9120: @secs = split(/:/,$response);
9121: }
1.506 raeburn 9122: }
9123: return @secs;
9124: }
1.776 albertel 9125:
1.506 raeburn 9126: sub auto_new_course {
1.1099 raeburn 9127: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9128: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9129: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9130: return $response;
9131: }
1.776 albertel 9132:
1.506 raeburn 9133: sub auto_validate_courseID {
1.508 raeburn 9134: my ($cnum,$cdom,$inst_course_id) = @_;
9135: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9136: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9137: return $response;
9138: }
1.776 albertel 9139:
1.1007 raeburn 9140: sub auto_validate_instcode {
1.1020 raeburn 9141: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9142: my ($homeserver,$response);
9143: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9144: $homeserver = &homeserver($cnum,$cdom);
9145: }
9146: if (!defined($homeserver)) {
9147: if ($cdom =~ /^$match_domain$/) {
9148: $homeserver = &domain($cdom,'primary');
9149: }
9150: }
1.1065 raeburn 9151: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9152: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9153: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9154: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9155: }
9156:
1.1172.2.141 raeburn 9157: sub auto_validate_inst_crosslist {
9158: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9159: my ($homeserver,$response);
9160: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9161: $homeserver = &homeserver($cnum,$cdom);
9162: }
9163: if (!defined($homeserver)) {
9164: if ($cdom =~ /^$match_domain$/) {
9165: $homeserver = &domain($cdom,'primary');
9166: }
9167: }
9168: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9169: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9170: &escape($instcode).':'.&escape($inst_xlist).':'.
9171: &escape($coowner),$homeserver);
9172: }
9173: return $response;
9174: }
9175:
1.506 raeburn 9176: sub auto_create_password {
1.873 raeburn 9177: my ($cnum,$cdom,$authparam,$udom) = @_;
9178: my ($homeserver,$response);
1.506 raeburn 9179: my $create_passwd = 0;
9180: my $authchk = '';
1.873 raeburn 9181: if ($udom =~ /^$match_domain$/) {
9182: $homeserver = &domain($udom,'primary');
9183: }
9184: if ($homeserver eq '') {
9185: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9186: $homeserver = &homeserver($cnum,$cdom);
9187: }
9188: }
9189: if ($homeserver eq '') {
9190: $authchk = 'nodomain';
1.506 raeburn 9191: } else {
1.873 raeburn 9192: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9193: if ($response eq 'refused') {
9194: $authchk = 'refused';
9195: } else {
1.901 albertel 9196: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9197: }
1.506 raeburn 9198: }
9199: return ($authparam,$create_passwd,$authchk);
9200: }
9201:
1.706 raeburn 9202: sub auto_photo_permission {
9203: my ($cnum,$cdom,$students) = @_;
9204: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9205: my ($outcome,$perm_reqd,$conditions) =
9206: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9207: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9208: return (undef,undef);
9209: }
1.706 raeburn 9210: return ($outcome,$perm_reqd,$conditions);
9211: }
9212:
9213: sub auto_checkphotos {
9214: my ($uname,$udom,$pid) = @_;
9215: my $homeserver = &homeserver($uname,$udom);
9216: my ($result,$resulttype);
9217: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9218: &escape($uname).':'.&escape($pid),
9219: $homeserver));
1.709 albertel 9220: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9221: return (undef,undef);
9222: }
1.706 raeburn 9223: if ($outcome) {
9224: ($result,$resulttype) = split(/:/,$outcome);
9225: }
9226: return ($result,$resulttype);
9227: }
9228:
9229: sub auto_photochoice {
9230: my ($cnum,$cdom) = @_;
9231: my $homeserver = &homeserver($cnum,$cdom);
9232: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9233: &escape($cdom),
9234: $homeserver)));
1.709 albertel 9235: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9236: return (undef,undef);
9237: }
1.706 raeburn 9238: return ($update,$comment);
9239: }
9240:
9241: sub auto_photoupdate {
9242: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9243: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9244: my $host=&hostname($homeserver);
1.706 raeburn 9245: my $cmd = '';
9246: my $maxtries = 1;
1.800 albertel 9247: foreach my $affiliate (keys(%{$affiliatesref})) {
9248: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9249: }
9250: $cmd =~ s/%%$//;
9251: $cmd = &escape($cmd);
9252: my $query = 'institutionalphotos';
9253: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9254: unless ($queryid=~/^\Q$host\E\_/) {
9255: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9256: return 'error: '.$queryid;
9257: }
9258: my $reply = &get_query_reply($queryid);
9259: my $tries = 1;
9260: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9261: $reply = &get_query_reply($queryid);
9262: $tries ++;
9263: }
9264: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9265: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9266: } else {
9267: my @responses = split(/:/,$reply);
9268: my $outcome = shift(@responses);
9269: foreach my $item (@responses) {
9270: my ($key,$value) = split(/=/,$item);
9271: $$photo{$key} = $value;
9272: }
9273: return $outcome;
9274: }
9275: return 'error';
9276: }
9277:
1.521 raeburn 9278: sub auto_instcode_format {
1.793 albertel 9279: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9280: $cat_order) = @_;
1.521 raeburn 9281: my $courses = '';
1.772 raeburn 9282: my @homeservers;
1.521 raeburn 9283: if ($caller eq 'global') {
1.841 albertel 9284: my %servers = &get_servers($codedom,'library');
9285: foreach my $tryserver (keys(%servers)) {
9286: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9287: push(@homeservers,$tryserver);
9288: }
1.584 raeburn 9289: }
1.1022 raeburn 9290: } elsif ($caller eq 'requests') {
9291: if ($codedom =~ /^$match_domain$/) {
9292: my $chome = &domain($codedom,'primary');
9293: unless ($chome eq 'no_host') {
9294: push(@homeservers,$chome);
9295: }
9296: }
1.521 raeburn 9297: } else {
1.772 raeburn 9298: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9299: }
1.793 albertel 9300: foreach my $code (keys(%{$instcodes})) {
9301: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9302: }
9303: chop($courses);
1.772 raeburn 9304: my $ok_response = 0;
9305: my $response;
9306: while (@homeservers > 0 && $ok_response == 0) {
9307: my $server = shift(@homeservers);
9308: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9309: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9310: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9311: split(/:/,$response);
1.772 raeburn 9312: %{$codes} = (%{$codes},&str2hash($codes_str));
9313: push(@{$codetitles},&str2array($codetitles_str));
9314: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9315: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9316: $ok_response = 1;
9317: }
9318: }
9319: if ($ok_response) {
1.521 raeburn 9320: return 'ok';
1.772 raeburn 9321: } else {
9322: return $response;
1.521 raeburn 9323: }
9324: }
9325:
1.792 raeburn 9326: sub auto_instcode_defaults {
9327: my ($domain,$returnhash,$code_order) = @_;
9328: my @homeservers;
1.841 albertel 9329:
9330: my %servers = &get_servers($domain,'library');
9331: foreach my $tryserver (keys(%servers)) {
9332: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9333: push(@homeservers,$tryserver);
9334: }
1.792 raeburn 9335: }
1.841 albertel 9336:
1.792 raeburn 9337: my $response;
1.841 albertel 9338: foreach my $server (@homeservers) {
1.792 raeburn 9339: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9340: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9341:
9342: foreach my $pair (split(/\&/,$response)) {
9343: my ($name,$value)=split(/\=/,$pair);
9344: if ($name eq 'code_order') {
9345: @{$code_order} = split(/\&/,&unescape($value));
9346: } else {
9347: $returnhash->{&unescape($name)}=&unescape($value);
9348: }
9349: }
9350: return 'ok';
1.792 raeburn 9351: }
1.841 albertel 9352:
9353: return $response;
1.1003 raeburn 9354: }
9355:
9356: sub auto_possible_instcodes {
1.1007 raeburn 9357: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9358: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9359: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9360: return;
9361: }
1.1003 raeburn 9362: my (@homeservers,$uhome);
9363: if (defined(&domain($domain,'primary'))) {
9364: $uhome=&domain($domain,'primary');
9365: push(@homeservers,&domain($domain,'primary'));
9366: } else {
9367: my %servers = &get_servers($domain,'library');
9368: foreach my $tryserver (keys(%servers)) {
9369: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9370: push(@homeservers,$tryserver);
9371: }
9372: }
9373: }
9374: my $response;
9375: foreach my $server (@homeservers) {
9376: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9377: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9378: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9379: split(':',$response);
9380: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9381: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9382: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9383: my ($name,$value)=split('=',$item);
9384: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9385: }
9386: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9387: my ($name,$value)=split('=',$item);
9388: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9389: }
9390: return 'ok';
9391: }
9392: return $response;
9393: }
1.792 raeburn 9394:
1.1010 raeburn 9395: sub auto_courserequest_checks {
9396: my ($dom) = @_;
1.1020 raeburn 9397: my ($homeserver,%validations);
9398: if ($dom =~ /^$match_domain$/) {
9399: $homeserver = &domain($dom,'primary');
9400: }
9401: unless ($homeserver eq 'no_host') {
9402: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9403: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9404: my @items = split(/&/,$response);
9405: foreach my $item (@items) {
9406: my ($key,$value) = split('=',$item);
9407: $validations{&unescape($key)} = &thaw_unescape($value);
9408: }
9409: }
9410: }
1.1010 raeburn 9411: return %validations;
9412: }
9413:
1.1020 raeburn 9414: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9415: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9416: my ($homeserver,$response);
9417: if ($dom =~ /^$match_domain$/) {
9418: $homeserver = &domain($dom,'primary');
9419: }
1.1172.2.43 raeburn 9420: unless ($homeserver eq 'no_host') {
9421: my $customdata;
9422: if (ref($custominfo) eq 'HASH') {
9423: $customdata = &freeze_escape($custominfo);
9424: }
1.1020 raeburn 9425: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9426: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9427: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9428: $customdata,$homeserver));
1.1020 raeburn 9429: }
9430: return $response;
9431: }
9432:
1.777 albertel 9433: sub auto_validate_class_sec {
1.918 raeburn 9434: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9435: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9436: my $ownerlist;
9437: if (ref($owners) eq 'ARRAY') {
9438: $ownerlist = join(',',@{$owners});
9439: } else {
9440: $ownerlist = $owners;
9441: }
1.773 raeburn 9442: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9443: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9444: return $response;
9445: }
9446:
1.1172.2.141 raeburn 9447: sub auto_instsec_reformat {
9448: my ($cdom,$action,$instsecref) = @_;
9449: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9450: my @homeservers;
9451: if (defined(&domain($cdom,'primary'))) {
9452: push(@homeservers,&domain($cdom,'primary'));
9453: } else {
9454: my %servers = &get_servers($cdom,'library');
9455: foreach my $tryserver (keys(%servers)) {
9456: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9457: push(@homeservers,$tryserver);
9458: }
9459: }
9460: }
9461: my $response;
9462: my %reformatted = %{$instsecref};
9463: foreach my $server (@homeservers) {
9464: if (ref($instsecref) eq 'HASH') {
9465: my $info = &freeze_escape($instsecref);
9466: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9467: $action.':'.$info,$server);
9468: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9469: my @items = split(/&/,$response);
9470: foreach my $item (@items) {
9471: my ($key,$value) = split(/=/,$item);
9472: $reformatted{&unescape($key)} = &thaw_unescape($value);
9473: }
9474: }
9475: }
9476: return %reformatted;
9477: }
9478:
1.1172.2.94 raeburn 9479: sub auto_validate_instclasses {
9480: my ($cdom,$cnum,$owners,$classesref) = @_;
9481: my ($homeserver,%validations);
9482: $homeserver = &homeserver($cnum,$cdom);
9483: unless ($homeserver eq 'no_host') {
9484: my $ownerlist;
9485: if (ref($owners) eq 'ARRAY') {
9486: $ownerlist = join(',',@{$owners});
9487: } else {
9488: $ownerlist = $owners;
9489: }
9490: if (ref($classesref) eq 'HASH') {
9491: my $classes = &freeze_escape($classesref);
9492: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9493: ':'.$cdom.':'.$classes,$homeserver);
9494: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9495: my @items = split(/&/,$response);
9496: foreach my $item (@items) {
9497: my ($key,$value) = split('=',$item);
9498: $validations{&unescape($key)} = &thaw_unescape($value);
9499: }
9500: }
9501: }
9502: }
9503: return %validations;
9504: }
9505:
1.1172.2.38 raeburn 9506: sub auto_crsreq_update {
9507: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9508: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9509: my ($homeserver,%crsreqresponse);
9510: if ($cdom =~ /^$match_domain$/) {
9511: $homeserver = &domain($cdom,'primary');
9512: }
9513: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9514: my $info;
9515: if (ref($inbound) eq 'HASH') {
9516: $info = &freeze_escape($inbound);
9517: }
9518: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9519: ':'.&escape($action).':'.&escape($ownername).':'.
9520: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9521: &escape($title).':'.&escape($code).':'.
9522: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9523: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9524: my @items = split(/&/,$response);
9525: foreach my $item (@items) {
9526: my ($key,$value) = split('=',$item);
9527: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9528: }
9529: }
9530: }
9531: return \%crsreqresponse;
9532: }
9533:
1.1172.2.78 raeburn 9534: sub auto_export_grades {
9535: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9536: my ($homeserver,%exportresponse);
9537: if ($cdom =~ /^$match_domain$/) {
9538: $homeserver = &domain($cdom,'primary');
9539: }
9540: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9541: my $info;
9542: if (ref($inforef) eq 'HASH') {
9543: $info = &freeze_escape($inforef);
9544: }
9545: if (ref($gradesref) eq 'HASH') {
9546: my $grades = &freeze_escape($gradesref);
9547: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9548: $info.':'.$grades,$homeserver);
9549: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9550: my @items = split(/&/,$response);
9551: foreach my $item (@items) {
9552: my ($key,$value) = split('=',$item);
9553: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9554: }
9555: }
9556: }
9557: }
9558: return \%exportresponse;
9559: }
9560:
1.1172.2.68 raeburn 9561: sub check_instcode_cloning {
9562: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9563: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9564: return;
9565: }
9566: my $canclone;
9567: if (@{$code_order} > 0) {
9568: my $instcoderegexp ='^';
9569: my @clonecodes = split(/\&/,$cloner);
9570: foreach my $item (@{$code_order}) {
9571: if (grep(/^\Q$item\E=/,@clonecodes)) {
9572: foreach my $pair (@clonecodes) {
9573: my ($key,$val) = split(/\=/,$pair,2);
9574: $val = &unescape($val);
9575: if ($key eq $item) {
9576: $instcoderegexp .= '('.$val.')';
9577: last;
9578: }
9579: }
9580: } else {
9581: $instcoderegexp .= $codedefaults->{$item};
9582: }
9583: }
9584: $instcoderegexp .= '$';
9585: my (@from,@to);
9586: eval {
9587: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9588: (@to) = ($clonetocode =~ /$instcoderegexp/);
9589: };
9590: if ((@from > 0) && (@to > 0)) {
9591: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9592: if (!@diffs) {
9593: $canclone = 1;
9594: }
9595: }
9596: }
9597: return $canclone;
9598: }
9599:
9600: sub default_instcode_cloning {
9601: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9602: my (%codedefaults,@code_order,$canclone);
9603: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9604: %codedefaults = %{$codedefaultsref};
9605: @code_order = @{$codeorderref};
9606: } elsif ($clonedom) {
9607: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9608: }
9609: if (($domdefclone) && (@code_order)) {
9610: my @clonecodes = split(/\+/,$domdefclone);
9611: my $instcoderegexp ='^';
9612: foreach my $item (@code_order) {
9613: if (grep(/^\Q$item\E$/,@clonecodes)) {
9614: $instcoderegexp .= '('.$codedefaults{$item}.')';
9615: } else {
9616: $instcoderegexp .= $codedefaults{$item};
9617: }
9618: }
9619: $instcoderegexp .= '$';
9620: my (@from,@to);
9621: eval {
9622: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9623: (@to) = ($clonetocode =~ /$instcoderegexp/);
9624: };
9625: if ((@from > 0) && (@to > 0)) {
9626: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9627: if (!@diffs) {
9628: $canclone = 1;
9629: }
9630: }
9631: }
9632: return $canclone;
9633: }
9634:
1.679 raeburn 9635: # ------------------------------------------------------- Course Group routines
9636:
9637: sub get_coursegroups {
1.809 raeburn 9638: my ($cdom,$cnum,$group,$namespace) = @_;
9639: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9640: }
9641:
1.679 raeburn 9642: sub modify_coursegroup {
9643: my ($cdom,$cnum,$groupsettings) = @_;
9644: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9645: }
9646:
1.809 raeburn 9647: sub toggle_coursegroup_status {
9648: my ($cdom,$cnum,$group,$action) = @_;
9649: my ($from_namespace,$to_namespace);
9650: if ($action eq 'delete') {
9651: $from_namespace = 'coursegroups';
9652: $to_namespace = 'deleted_groups';
9653: } else {
9654: $from_namespace = 'deleted_groups';
9655: $to_namespace = 'coursegroups';
9656: }
9657: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9658: if (my $tmp = &error(%curr_group)) {
9659: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9660: return ('read error',$tmp);
9661: } else {
9662: my %savedsettings = %curr_group;
1.809 raeburn 9663: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9664: my $deloutcome;
9665: if ($result eq 'ok') {
1.809 raeburn 9666: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9667: } else {
9668: return ('write error',$result);
9669: }
9670: if ($deloutcome eq 'ok') {
9671: return 'ok';
9672: } else {
9673: return ('delete error',$deloutcome);
9674: }
9675: }
9676: }
9677:
1.679 raeburn 9678: sub modify_group_roles {
1.957 raeburn 9679: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9680: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9681: my $role = 'gr/'.&escape($userprivs);
9682: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9683: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9684: if ($result eq 'ok') {
9685: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9686: }
1.679 raeburn 9687: return $result;
9688: }
9689:
9690: sub modify_coursegroup_membership {
9691: my ($cdom,$cnum,$membership) = @_;
9692: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9693: return $result;
9694: }
9695:
1.682 raeburn 9696: sub get_active_groups {
9697: my ($udom,$uname,$cdom,$cnum) = @_;
9698: my $now = time;
9699: my %groups = ();
9700: foreach my $key (keys(%env)) {
1.811 albertel 9701: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9702: my ($start,$end) = split(/\./,$env{$key});
9703: if (($end!=0) && ($end<$now)) { next; }
9704: if (($start!=0) && ($start>$now)) { next; }
9705: if ($1 eq $cdom && $2 eq $cnum) {
9706: $groups{$3} = $env{$key} ;
9707: }
9708: }
9709: }
9710: return %groups;
9711: }
9712:
1.683 raeburn 9713: sub get_group_membership {
9714: my ($cdom,$cnum,$group) = @_;
9715: return(&dump('groupmembership',$cdom,$cnum,$group));
9716: }
9717:
9718: sub get_users_groups {
9719: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9720: my @usersgroups;
1.683 raeburn 9721: my $cachetime=1800;
9722:
9723: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9724: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9725: if (defined($cached)) {
1.734 albertel 9726: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9727: } else {
9728: $grouplist = '';
1.816 raeburn 9729: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9730: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9731: my $access_end = $env{'course.'.$courseid.
9732: '.default_enrollment_end_date'};
9733: my $now = time;
9734: foreach my $key (keys(%roleshash)) {
9735: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9736: my $group = $1;
9737: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9738: my $start = $2;
9739: my $end = $1;
9740: if ($start == -1) { next; } # deleted from group
9741: if (($start!=0) && ($start>$now)) { next; }
9742: if (($end!=0) && ($end<$now)) {
9743: if ($access_end && $access_end < $now) {
9744: if ($access_end - $end < 86400) {
9745: push(@usersgroups,$group);
1.733 raeburn 9746: }
9747: }
1.817 raeburn 9748: next;
1.733 raeburn 9749: }
1.817 raeburn 9750: push(@usersgroups,$group);
1.683 raeburn 9751: }
9752: }
9753: }
1.817 raeburn 9754: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9755: $grouplist = join(':',@usersgroups);
9756: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9757: }
1.733 raeburn 9758: return @usersgroups;
1.683 raeburn 9759: }
9760:
9761: sub devalidate_getgroups_cache {
9762: my ($udom,$uname,$cdom,$cnum)=@_;
9763: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9764:
1.683 raeburn 9765: my $hashid="$udom:$uname:$courseid";
9766: &devalidate_cache_new('getgroups',$hashid);
9767: }
9768:
1.12 www 9769: # ------------------------------------------------------------------ Plain Text
9770:
9771: sub plaintext {
1.988 raeburn 9772: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9773: if ($short =~ m{^cr/}) {
1.758 albertel 9774: return (split('/',$short))[-1];
9775: }
1.742 raeburn 9776: if (!defined($cid)) {
9777: $cid = $env{'request.course.id'};
9778: }
9779: my %rolenames = (
1.1008 raeburn 9780: Course => 'std',
9781: Community => 'alt1',
1.742 raeburn 9782: );
1.1037 raeburn 9783: if ($cid ne '') {
9784: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9785: unless ($forcedefault) {
9786: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9787: &Apache::lonlocal::mt_escape(\$roletext);
9788: return &Apache::lonlocal::mt($roletext);
9789: }
9790: }
9791: }
9792: if ((defined($type)) && (defined($rolenames{$type})) &&
9793: (defined($rolenames{$type})) &&
9794: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9795: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9796: } elsif ($cid ne '') {
9797: my $crstype = $env{'course.'.$cid.'.type'};
9798: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9799: (defined($prp{$short}{$rolenames{$crstype}}))) {
9800: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9801: }
1.742 raeburn 9802: }
1.1037 raeburn 9803: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9804: }
9805:
9806: # ----------------------------------------------------------------- Assign Role
9807:
9808: sub assignrole {
1.957 raeburn 9809: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9810: $context)=@_;
1.21 www 9811: my $mrole;
9812: if ($role =~ /^cr\//) {
1.393 www 9813: my $cwosec=$url;
1.811 albertel 9814: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9815: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9816: my $refused = 1;
9817: if ($context eq 'requestcourses') {
9818: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9819: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9820: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9821: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9822: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9823: if ($crsenv{'internal.courseowner'} eq
9824: $env{'user.name'}.':'.$env{'user.domain'}) {
9825: $refused = '';
9826: }
9827: }
9828: }
9829: }
9830: }
9831: if ($refused) {
9832: &logthis('Refused custom assignrole: '.
9833: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9834: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9835: return 'refused';
9836: }
1.104 www 9837: }
1.21 www 9838: $mrole='cr';
1.678 raeburn 9839: } elsif ($role =~ /^gr\//) {
9840: my $cwogrp=$url;
1.811 albertel 9841: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9842: unless (&allowed('mdg',$cwogrp)) {
9843: &logthis('Refused group assignrole: '.
9844: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9845: $env{'user.name'}.' at '.$env{'user.domain'});
9846: return 'refused';
9847: }
9848: $mrole='gr';
1.21 www 9849: } else {
1.82 www 9850: my $cwosec=$url;
1.811 albertel 9851: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9852: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9853: my $refused;
9854: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9855: if (!(&allowed('c'.$role,$url))) {
9856: $refused = 1;
9857: }
9858: } else {
9859: $refused = 1;
9860: }
1.947 raeburn 9861: if ($refused) {
1.1045 raeburn 9862: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9863: if (!$selfenroll && $context eq 'course') {
9864: my %crsenv;
9865: if ($role eq 'cc' || $role eq 'co') {
9866: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9867: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9868: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9869: if ($crsenv{'internal.courseowner'} eq
9870: $env{'user.name'}.':'.$env{'user.domain'}) {
9871: $refused = '';
9872: }
9873: }
9874: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9875: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9876: if ($crsenv{'internal.courseowner'} eq
9877: $env{'user.name'}.':'.$env{'user.domain'}) {
9878: $refused = '';
9879: }
9880: }
9881: }
9882: }
9883: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9884: $refused = '';
1.1017 raeburn 9885: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9886: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9887: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9888: my $wrongcc;
9889: if ($cnum =~ /^$match_community$/) {
9890: $wrongcc = 1 if ($role eq 'cc');
9891: } else {
9892: $wrongcc = 1 if ($role eq 'co');
9893: }
9894: unless ($wrongcc) {
9895: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9896: if ($crsenv{'internal.courseowner'} eq
9897: $env{'user.name'}.':'.$env{'user.domain'}) {
9898: $refused = '';
9899: }
1.1017 raeburn 9900: }
9901: }
1.1172.2.9 raeburn 9902: } elsif ($context eq 'requestauthor') {
9903: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9904: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9905: if ($env{'environment.requestauthor'} eq 'automatic') {
9906: $refused = '';
9907: } else {
9908: my %domdefaults = &get_domain_defaults($udom);
9909: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9910: my $checkbystatus;
9911: if ($env{'user.adv'}) {
9912: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9913: if ($disposition eq 'automatic') {
9914: $refused = '';
9915: } elsif ($disposition eq '') {
9916: $checkbystatus = 1;
9917: }
9918: } else {
9919: $checkbystatus = 1;
9920: }
9921: if ($checkbystatus) {
9922: if ($env{'environment.inststatus'}) {
9923: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9924: foreach my $type (@inststatuses) {
9925: if (($type ne '') &&
9926: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9927: $refused = '';
9928: }
9929: }
9930: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9931: $refused = '';
9932: }
9933: }
9934: }
9935: }
9936: }
1.1017 raeburn 9937: }
9938: if ($refused) {
1.947 raeburn 9939: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9940: ' '.$role.' '.$end.' '.$start.' by '.
9941: $env{'user.name'}.' at '.$env{'user.domain'});
9942: return 'refused';
9943: }
1.932 raeburn 9944: }
1.1131 raeburn 9945: } elsif ($role eq 'au') {
9946: if ($url ne '/'.$udom.'/') {
9947: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9948: ' to assign author role for '.$uname.':'.$udom.
9949: ' in domain: '.$url.' refused (wrong domain).');
9950: return 'refused';
9951: }
1.104 www 9952: }
1.21 www 9953: $mrole=$role;
9954: }
1.620 albertel 9955: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9956: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9957: if ($end) { $command.='_'.$end; }
1.21 www 9958: if ($start) {
9959: if ($end) {
1.81 www 9960: $command.='_'.$start;
1.21 www 9961: } else {
1.81 www 9962: $command.='_0_'.$start;
1.21 www 9963: }
9964: }
1.739 raeburn 9965: my $origstart = $start;
9966: my $origend = $end;
1.957 raeburn 9967: my $delflag;
1.357 www 9968: # actually delete
9969: if ($deleteflag) {
1.373 www 9970: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9971: # modify command to delete the role
1.620 albertel 9972: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9973: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9974: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9975: # set start and finish to negative values for userrolelog
9976: $start=-1;
9977: $end=-1;
1.957 raeburn 9978: $delflag = 1;
1.357 www 9979: }
9980: }
9981: # send command
1.349 www 9982: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9983: # log new user role if status is ok
1.349 www 9984: if ($answer eq 'ok') {
1.663 raeburn 9985: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9986: if (($role eq 'cc') || ($role eq 'in') ||
9987: ($role eq 'ep') || ($role eq 'ad') ||
9988: ($role eq 'ta') || ($role eq 'st') ||
9989: ($role=~/^cr/) || ($role eq 'gr') ||
9990: ($role eq 'co')) {
1.1172.2.13 raeburn 9991: # for course roles, perform group memberships changes triggered by role change.
9992: unless ($role =~ /^gr/) {
9993: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9994: $origstart,$selfenroll,$context);
9995: }
1.1172.2.9 raeburn 9996: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9997: $selfenroll,$context);
9998: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9999: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10000: ($role eq 'da')) {
1.1172.2.9 raeburn 10001: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10002: $context);
10003: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10004: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10005: $context);
10006: }
1.1053 raeburn 10007: if ($role eq 'cc') {
10008: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10009: }
1.349 www 10010: }
10011: return $answer;
1.169 harris41 10012: }
10013:
1.1053 raeburn 10014: sub autoupdate_coowners {
10015: my ($url,$end,$start,$uname,$udom) = @_;
10016: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10017: if (($cdom ne '') && ($cnum ne '')) {
10018: my $now = time;
10019: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10020: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10021: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10022: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10023: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10024: if ($instcode ne '') {
1.1056 raeburn 10025: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10026: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10027: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10028: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10029: unless ($result eq 'valid') {
10030: if ($xlists ne '') {
10031: foreach my $xlist (split(',',$xlists)) {
10032: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10033: $result =
10034: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10035: $inst_crosslist,$uname.':'.$udom);
10036: last if ($result eq 'valid');
10037: }
10038: }
10039: }
1.1056 raeburn 10040: if ($result eq 'valid') {
10041: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10042: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10043: push(@newcoowners,$coowner);
10044: }
10045: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10046: push(@newcoowners,$uname.':'.$udom);
10047: }
10048: @newcoowners = sort(@newcoowners);
10049: } else {
10050: push(@newcoowners,$uname.':'.$udom);
10051: }
1.1172.2.141 raeburn 10052: } elsif ($coursehash{'internal.co-owners'}) {
10053: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10054: unless ($coowner eq $uname.':'.$udom) {
10055: push(@newcoowners,$coowner);
1.1053 raeburn 10056: }
10057: }
1.1172.2.141 raeburn 10058: unless (@newcoowners > 0) {
10059: $delcoowners = 1;
10060: $coowners = '';
10061: }
1.1053 raeburn 10062: }
10063: if (@newcoowners || $delcoowners) {
10064: &store_coowners($cdom,$cnum,$coursehash{'home'},
10065: $delcoowners,@newcoowners);
10066: }
10067: }
10068: }
10069: }
10070: }
10071: }
10072: }
10073:
10074: sub store_coowners {
10075: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10076: my $cid = $cdom.'_'.$cnum;
10077: my ($coowners,$delresult,$putresult);
10078: if (@newcoowners) {
10079: $coowners = join(',',@newcoowners);
10080: my %coownershash = (
10081: 'internal.co-owners' => $coowners,
10082: );
10083: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10084: if ($putresult eq 'ok') {
10085: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10086: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10087: }
10088: }
10089: }
10090: if ($delcoowners) {
10091: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10092: if ($delresult eq 'ok') {
10093: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10094: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10095: }
10096: }
10097: }
10098: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10099: my %crsinfo =
10100: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10101: if (ref($crsinfo{$cid}) eq 'HASH') {
10102: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10103: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10104: }
10105: }
10106: }
10107:
1.169 harris41 10108: # -------------------------------------------------- Modify user authentication
1.197 www 10109: # Overrides without validation
10110:
1.169 harris41 10111: sub modifyuserauth {
10112: my ($udom,$uname,$umode,$upass)=@_;
10113: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10114: my $allowed;
10115: if (&allowed('mau',$udom)) {
10116: $allowed = 1;
10117: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10118: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10119: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10120: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10121: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10122: if (($cdom ne '') && ($cnum ne '')) {
10123: my $is_owner = &is_course_owner($cdom,$cnum);
10124: if ($is_owner) {
10125: $allowed = 1;
10126: }
10127: }
10128: }
10129: unless ($allowed) { return 'refused'; }
1.197 www 10130: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10131: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10132: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10133: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10134: &escape($upass),$uhome);
1.1172.2.134 raeburn 10135: my $ip = &get_requestor_ip();
1.620 albertel 10136: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10137: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10138: '(Remote '.$ip.'): '.$reply);
1.197 www 10139: &log($udom,,$uname,$uhome,
1.620 albertel 10140: 'Authentication changed by '.$env{'user.domain'}.', '.
10141: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10142: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10143: unless ($reply eq 'ok') {
1.197 www 10144: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10145: return 'error: '.$reply;
10146: }
1.170 harris41 10147: return 'ok';
1.80 www 10148: }
10149:
1.81 www 10150: # --------------------------------------------------------------- Modify a user
1.80 www 10151:
1.81 www 10152: sub modifyuser {
1.206 matthew 10153: my ($udom, $uname, $uid,
10154: $umode, $upass, $first,
10155: $middle, $last, $gene,
1.1058 raeburn 10156: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10157: $udom= &LONCAPA::clean_domain($udom);
10158: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10159: my $showcandelete = 'none';
10160: if (ref($candelete) eq 'ARRAY') {
10161: if (@{$candelete} > 0) {
10162: $showcandelete = join(', ',@{$candelete});
10163: }
10164: }
1.81 www 10165: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10166: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10167: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10168: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10169: ' desiredhome not specified').
1.620 albertel 10170: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10171: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10172: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10173: my $newuser;
10174: if ($uhome eq 'no_host') {
10175: $newuser = 1;
10176: }
1.80 www 10177: # ----------------------------------------------------------------- Create User
1.406 albertel 10178: if (($uhome eq 'no_host') &&
10179: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10180: my $unhome='';
1.844 albertel 10181: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10182: $unhome = $desiredhome;
1.620 albertel 10183: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10184: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10185: } else { # load balancing routine for determining $unhome
1.81 www 10186: my $loadm=10000000;
1.841 albertel 10187: my %servers = &get_servers($udom,'library');
10188: foreach my $tryserver (keys(%servers)) {
10189: my $answer=reply('load',$tryserver);
10190: if (($answer=~/\d+/) && ($answer<$loadm)) {
10191: $loadm=$answer;
10192: $unhome=$tryserver;
10193: }
1.80 www 10194: }
10195: }
10196: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10197: return 'error: unable to find a home server for '.$uname.
10198: ' in domain '.$udom;
1.80 www 10199: }
10200: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10201: &escape($upass),$unhome);
10202: unless ($reply eq 'ok') {
10203: return 'error: '.$reply;
10204: }
1.230 stredwic 10205: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10206: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10207: return 'error: unable verify users home machine.';
1.80 www 10208: }
1.209 matthew 10209: } # End of creation of new user
1.80 www 10210: # ---------------------------------------------------------------------- Add ID
10211: if ($uid) {
10212: $uid=~tr/A-Z/a-z/;
10213: my %uidhash=&idrget($udom,$uname);
1.196 www 10214: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10215: && (!$forceid)) {
1.80 www 10216: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10217: return 'error: user id "'.$uid.'" does not match '.
10218: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10219: }
10220: } else {
10221: &idput($udom,($uname => $uid));
10222: }
10223: }
10224: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10225: my @tmp=&get('environment',
1.899 raeburn 10226: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10227: 'permanentemail','inststatus'],
1.134 albertel 10228: $udom,$uname);
1.1075 raeburn 10229: my (%names,%oldnames);
1.313 matthew 10230: if ($tmp[0] =~ m/^error:.*/) {
10231: %names=();
10232: } else {
10233: %names = @tmp;
1.1075 raeburn 10234: %oldnames = %names;
1.313 matthew 10235: }
1.388 www 10236: #
1.1058 raeburn 10237: # If name, email and/or uid are blank (e.g., because an uploaded file
10238: # of users did not contain them), do not overwrite existing values
10239: # unless field is in $candelete array ref.
10240: #
10241:
10242: my @fields = ('firstname','middlename','lastname','generation',
10243: 'permanentemail','id');
10244: my %newvalues;
10245: if (ref($candelete) eq 'ARRAY') {
10246: foreach my $field (@fields) {
10247: if (grep(/^\Q$field\E$/,@{$candelete})) {
10248: if ($field eq 'firstname') {
10249: $names{$field} = $first;
10250: } elsif ($field eq 'middlename') {
10251: $names{$field} = $middle;
10252: } elsif ($field eq 'lastname') {
10253: $names{$field} = $last;
10254: } elsif ($field eq 'generation') {
10255: $names{$field} = $gene;
10256: } elsif ($field eq 'permanentemail') {
10257: $names{$field} = $email;
10258: } elsif ($field eq 'id') {
10259: $names{$field} = $uid;
10260: }
10261: }
10262: }
10263: }
1.388 www 10264: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10265: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10266: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10267: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10268: if ($email) {
10269: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10270: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10271: }
1.899 raeburn 10272: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10273: if (defined($inststatus)) {
10274: $names{'inststatus'} = '';
10275: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10276: if (ref($usertypes) eq 'HASH') {
10277: my @okstatuses;
10278: foreach my $item (split(/:/,$inststatus)) {
10279: if (defined($usertypes->{$item})) {
10280: push(@okstatuses,$item);
10281: }
10282: }
10283: if (@okstatuses) {
10284: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10285: }
10286: }
10287: }
1.1075 raeburn 10288: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10289: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10290: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10291: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10292: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10293: } else {
10294: $logmsg .= ' during self creation';
10295: }
1.1075 raeburn 10296: my $changed;
10297: if ($newuser) {
10298: $changed = 1;
10299: } else {
10300: foreach my $field (@fields) {
10301: if ($names{$field} ne $oldnames{$field}) {
10302: $changed = 1;
10303: last;
10304: }
10305: }
10306: }
10307: unless ($changed) {
10308: $logmsg = 'No changes in user information needed for: '.$logmsg;
10309: &logthis($logmsg);
10310: return 'ok';
10311: }
10312: my $reply = &put('environment', \%names, $udom,$uname);
10313: if ($reply ne 'ok') {
10314: return 'error: '.$reply;
10315: }
1.1087 raeburn 10316: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10317: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10318: }
1.1075 raeburn 10319: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10320: &devalidate_cache_new('namescache',$uname.':'.$udom);
10321: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10322: &logthis($logmsg);
1.134 albertel 10323: return 'ok';
1.80 www 10324: }
10325:
1.81 www 10326: # -------------------------------------------------------------- Modify student
1.80 www 10327:
1.81 www 10328: sub modifystudent {
10329: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10330: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10331: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10332: if (!$cid) {
1.620 albertel 10333: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10334: return 'not_in_class';
10335: }
1.80 www 10336: }
10337: # --------------------------------------------------------------- Make the user
1.81 www 10338: my $reply=&modifyuser
1.209 matthew 10339: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10340: $desiredhome,$email,$inststatus);
1.80 www 10341: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10342: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10343: # student's environment
1.297 matthew 10344: $uid = undef if (!$forceid);
1.455 albertel 10345: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10346: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10347: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10348: return $reply;
10349: }
10350:
10351: sub modify_student_enrollment {
1.1172.2.23 raeburn 10352: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10353: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10354: my ($cdom,$cnum,$chome);
10355: if (!$cid) {
1.620 albertel 10356: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10357: return 'not_in_class';
10358: }
1.620 albertel 10359: $cdom=$env{'course.'.$cid.'.domain'};
10360: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10361: } else {
10362: ($cdom,$cnum)=split(/_/,$cid);
10363: }
1.620 albertel 10364: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10365: if (!$chome) {
1.457 raeburn 10366: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10367: }
1.455 albertel 10368: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10369: # Make sure the user exists
1.81 www 10370: my $uhome=&homeserver($uname,$udom);
10371: if (($uhome eq '') || ($uhome eq 'no_host')) {
10372: return 'error: no such user';
10373: }
1.297 matthew 10374: # Get student data if we were not given enough information
10375: if (!defined($first) || $first eq '' ||
10376: !defined($last) || $last eq '' ||
10377: !defined($uid) || $uid eq '' ||
10378: !defined($middle) || $middle eq '' ||
10379: !defined($gene) || $gene eq '') {
1.294 matthew 10380: # They did not supply us with enough data to enroll the student, so
10381: # we need to pick up more information.
1.297 matthew 10382: my %tmp = &get('environment',
1.294 matthew 10383: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10384: ,$udom,$uname);
10385:
1.800 albertel 10386: #foreach my $key (keys(%tmp)) {
10387: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10388: #}
1.294 matthew 10389: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10390: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10391: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10392: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10393: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10394: }
1.556 albertel 10395: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10396: my $user = "$uname:$udom";
10397: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10398: my $reply=cput('classlist',
1.1148 raeburn 10399: {$user =>
1.1172.2.76 raeburn 10400: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10401: $cdom,$cnum);
1.1148 raeburn 10402: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10403: &devalidate_getsection_cache($udom,$uname,$cid);
10404: } else {
1.81 www 10405: return 'error: '.$reply;
10406: }
1.297 matthew 10407: # Add student role to user
1.83 www 10408: my $uurl='/'.$cid;
1.81 www 10409: $uurl=~s/\_/\//g;
10410: if ($usec) {
10411: $uurl.='/'.$usec;
10412: }
1.1148 raeburn 10413: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10414: $selfenroll,$context);
10415: if ($result ne 'ok') {
10416: if ($old_entry{$user} ne '') {
10417: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10418: } else {
10419: $reply = &del('classlist',[$user],$cdom,$cnum);
10420: }
10421: }
10422: return $result;
1.21 www 10423: }
10424:
1.556 albertel 10425: sub format_name {
10426: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10427: my $name;
10428: if ($first ne 'lastname') {
10429: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10430: } else {
10431: if ($lastname=~/\S/) {
10432: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10433: $name=~s/\s+,/,/;
10434: } else {
10435: $name.= $firstname.' '.$middlename.' '.$generation;
10436: }
10437: }
10438: $name=~s/^\s+//;
10439: $name=~s/\s+$//;
10440: $name=~s/\s+/ /g;
10441: return $name;
10442: }
10443:
1.84 www 10444: # ------------------------------------------------- Write to course preferences
10445:
10446: sub writecoursepref {
10447: my ($courseid,%prefs)=@_;
10448: $courseid=~s/^\///;
10449: $courseid=~s/\_/\//g;
10450: my ($cdomain,$cnum)=split(/\//,$courseid);
10451: my $chome=homeserver($cnum,$cdomain);
10452: if (($chome eq '') || ($chome eq 'no_host')) {
10453: return 'error: no such course';
10454: }
10455: my $cstring='';
1.800 albertel 10456: foreach my $pref (keys(%prefs)) {
10457: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10458: }
1.84 www 10459: $cstring=~s/\&$//;
10460: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10461: }
10462:
10463: # ---------------------------------------------------------- Make/modify course
10464:
10465: sub createcourse {
1.741 raeburn 10466: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10467: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10468: $url=&declutter($url);
10469: my $cid='';
1.1028 raeburn 10470: if ($context eq 'requestcourses') {
10471: my $can_create = 0;
10472: my ($ownername,$ownerdom) = split(':',$course_owner);
10473: if ($udom eq $ownerdom) {
10474: if (&usertools_access($ownername,$ownerdom,$category,undef,
10475: $context)) {
10476: $can_create = 1;
10477: }
10478: } else {
10479: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10480: $category);
10481: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10482: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10483: if (@curr > 0) {
10484: my @options = qw(approval validate autolimit);
10485: my $optregex = join('|',@options);
10486: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10487: $can_create = 1;
10488: }
10489: }
10490: }
10491: }
10492: if ($can_create) {
10493: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10494: unless (&allowed('ccc',$udom)) {
10495: return 'refused';
10496: }
1.1017 raeburn 10497: }
10498: } else {
10499: return 'refused';
10500: }
1.1028 raeburn 10501: } elsif (!&allowed('ccc',$udom)) {
10502: return 'refused';
1.84 www 10503: }
1.1011 raeburn 10504: # --------------------------------------------------------------- Get Unique ID
10505: my $uname;
10506: if ($cnum =~ /^$match_courseid$/) {
10507: my $chome=&homeserver($cnum,$udom,'true');
10508: if (($chome eq '') || ($chome eq 'no_host')) {
10509: $uname = $cnum;
10510: } else {
1.1038 raeburn 10511: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10512: }
10513: } else {
1.1038 raeburn 10514: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10515: }
10516: return $uname if ($uname =~ /^error/);
10517: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10518: if (!defined($course_server)) {
10519: if (defined(&domain($udom,'primary'))) {
10520: $course_server = &domain($udom,'primary');
10521: } else {
10522: $course_server = $env{'user.home'};
10523: }
10524: }
10525: my %host_servers =
10526: &Apache::lonnet::get_servers($udom,'library');
10527: unless ($host_servers{$course_server}) {
10528: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10529: }
1.84 www 10530: # ------------------------------------------------------------- Make the course
10531: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10532: $course_server);
1.84 www 10533: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10534: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10535: if (($uhome eq '') || ($uhome eq 'no_host')) {
10536: return 'error: no such course';
10537: }
1.271 www 10538: # ----------------------------------------------------------------- Course made
1.516 raeburn 10539: # log existence
1.1029 raeburn 10540: my $now = time;
1.918 raeburn 10541: my $newcourse = {
10542: $udom.'_'.$uname => {
1.921 raeburn 10543: description => $description,
10544: inst_code => $inst_code,
10545: owner => $course_owner,
10546: type => $crstype,
1.1029 raeburn 10547: creator => $env{'user.name'}.':'.
10548: $env{'user.domain'},
10549: created => $now,
10550: context => $context,
1.918 raeburn 10551: },
10552: };
1.921 raeburn 10553: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10554: # set toplevel url
1.271 www 10555: my $topurl=$url;
10556: unless ($nonstandard) {
10557: # ------------------------------------------ For standard courses, make top url
10558: my $mapurl=&clutter($url);
1.278 www 10559: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10560: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10561: <map>
10562: <resource id="1" type="start"></resource>
10563: <resource id="2" src="$mapurl"></resource>
10564: <resource id="3" type="finish"></resource>
10565: <link index="1" from="1" to="2"></link>
10566: <link index="2" from="2" to="3"></link>
10567: </map>
10568: ENDINITMAP
10569: $topurl=&declutter(
1.638 albertel 10570: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10571: );
10572: }
10573: # ----------------------------------------------------------- Write preferences
1.84 www 10574: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10575: ('description' => $description,
10576: 'url' => $topurl,
10577: 'internal.creator' => $env{'user.name'}.':'.
10578: $env{'user.domain'},
10579: 'internal.created' => $now,
10580: 'internal.creationcontext' => $context)
10581: );
1.84 www 10582: return '/'.$udom.'/'.$uname;
10583: }
10584:
1.1011 raeburn 10585: # ------------------------------------------------------------------- Create ID
10586: sub generate_coursenum {
1.1038 raeburn 10587: my ($udom,$crstype) = @_;
1.1011 raeburn 10588: my $domdesc = &domain($udom);
10589: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10590: my $first;
10591: if ($crstype eq 'Community') {
10592: $first = '0';
10593: } else {
10594: $first = int(1+rand(9));
10595: }
10596: my $uname=$first.
1.1011 raeburn 10597: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10598: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10599: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10600: # ----------------------------------------------- Make sure that does not exist
10601: my $uhome=&homeserver($uname,$udom,'true');
10602: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10603: if ($crstype eq 'Community') {
10604: $first = '0';
10605: } else {
10606: $first = int(1+rand(9));
10607: }
10608: $uname=$first.
1.1011 raeburn 10609: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10610: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10611: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10612: $uhome=&homeserver($uname,$udom,'true');
10613: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10614: return 'error: unable to generate unique course-ID';
10615: }
10616: }
10617: return $uname;
10618: }
10619:
1.813 albertel 10620: sub is_course {
1.1167 droeschl 10621: my ($cdom, $cnum) = scalar(@_) == 1 ?
10622: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10623: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10624: my $uhome=&homeserver($cnum,$cdom);
10625: my $iscourse;
10626: if (grep { $_ eq $uhome } current_machine_ids()) {
10627: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10628: } else {
10629: my $hashid = $cdom.':'.$cnum;
10630: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10631: unless (defined($cached)) {
10632: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10633: $cnum,undef,undef,'.');
10634: $iscourse = 0;
10635: if (exists($courses{$cdom.'_'.$cnum})) {
10636: $iscourse = 1;
10637: }
10638: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10639: }
10640: }
10641: return unless($iscourse);
1.1167 droeschl 10642: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10643: }
10644:
1.1015 raeburn 10645: sub store_userdata {
10646: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10647: my $result;
1.1016 raeburn 10648: if ($datakey ne '') {
1.1013 raeburn 10649: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10650: if ($udom eq '' || $uname eq '') {
10651: $udom = $env{'user.domain'};
10652: $uname = $env{'user.name'};
10653: }
10654: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10655: if (($uhome eq '') || ($uhome eq 'no_host')) {
10656: $result = 'error: no_host';
10657: } else {
1.1172.2.138 raeburn 10658: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10659: $storehash->{'host'} = $perlvar{'lonHostID'};
10660:
10661: my $namevalue='';
10662: foreach my $key (keys(%{$storehash})) {
10663: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10664: }
10665: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10666: unless ($namespace eq 'courserequests') {
10667: $datakey = &escape($datakey);
10668: }
1.1105 raeburn 10669: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10670: $namevalue,$uhome);
1.1013 raeburn 10671: }
10672: } else {
10673: $result = 'error: data to store was not a hash reference';
10674: }
10675: } else {
10676: $result= 'error: invalid requestkey';
10677: }
10678: return $result;
10679: }
10680:
1.21 www 10681: # ---------------------------------------------------------- Assign Custom Role
10682:
10683: sub assigncustomrole {
1.957 raeburn 10684: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10685: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10686: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10687: }
10688:
10689: # ----------------------------------------------------------------- Revoke Role
10690:
10691: sub revokerole {
1.957 raeburn 10692: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10693: my $now=time;
1.965 raeburn 10694: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10695: }
10696:
10697: # ---------------------------------------------------------- Revoke Custom Role
10698:
10699: sub revokecustomrole {
1.957 raeburn 10700: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10701: my $now=time;
1.357 www 10702: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10703: $deleteflag,$selfenroll,$context);
1.17 www 10704: }
10705:
1.533 banghart 10706: # ------------------------------------------------------------ Disk usage
1.535 albertel 10707: sub diskusage {
1.955 raeburn 10708: my ($udom,$uname,$directorypath,$getpropath)=@_;
10709: $directorypath =~ s/\/$//;
10710: my $listing=&reply('du2:'.&escape($directorypath).':'
10711: .&escape($getpropath).':'.&escape($uname).':'
10712: .&escape($udom),homeserver($uname,$udom));
10713: if ($listing eq 'unknown_cmd') {
10714: if ($getpropath) {
10715: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10716: }
10717: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10718: }
1.514 albertel 10719: return $listing;
1.512 banghart 10720: }
10721:
1.566 banghart 10722: sub is_locked {
1.1096 raeburn 10723: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10724: my @check;
10725: my $is_locked;
1.1093 raeburn 10726: push (@check,$file_name);
1.613 albertel 10727: my %locked = &get('file_permissions',\@check,
1.620 albertel 10728: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10729: my ($tmp)=keys(%locked);
10730: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10731:
1.566 banghart 10732: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10733: $is_locked = 'false';
10734: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10735: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10736: $is_locked = 'true';
1.1096 raeburn 10737: if (ref($which) eq 'ARRAY') {
10738: push(@{$which},$entry);
10739: } else {
10740: last;
10741: }
1.745 raeburn 10742: }
10743: }
1.566 banghart 10744: } else {
10745: $is_locked = 'false';
10746: }
1.1093 raeburn 10747: return $is_locked;
1.566 banghart 10748: }
10749:
1.759 albertel 10750: sub declutter_portfile {
10751: my ($file) = @_;
1.833 albertel 10752: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10753: return $file;
10754: }
10755:
1.559 banghart 10756: # ------------------------------------------------------------- Mark as Read Only
10757:
10758: sub mark_as_readonly {
10759: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10760: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10761: my ($tmp)=keys(%current_permissions);
10762: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10763: foreach my $file (@{$files}) {
1.759 albertel 10764: $file = &declutter_portfile($file);
1.561 banghart 10765: push(@{$current_permissions{$file}},$what);
1.559 banghart 10766: }
1.613 albertel 10767: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10768: return;
10769: }
10770:
1.572 banghart 10771: # ------------------------------------------------------------Save Selected Files
10772:
10773: sub save_selected_files {
10774: my ($user, $path, @files) = @_;
10775: my $filename = $user."savedfiles";
1.573 banghart 10776: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10777: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10778: foreach my $file (@files) {
1.620 albertel 10779: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10780: }
10781: foreach my $file (@other_files) {
1.574 banghart 10782: print (OUT $file."\n");
1.572 banghart 10783: }
1.574 banghart 10784: close (OUT);
1.572 banghart 10785: return 'ok';
10786: }
10787:
1.574 banghart 10788: sub clear_selected_files {
10789: my ($user) = @_;
10790: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10791: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10792: print (OUT undef);
10793: close (OUT);
10794: return ("ok");
10795: }
10796:
1.572 banghart 10797: sub files_in_path {
10798: my ($user, $path) = @_;
10799: my $filename = $user."savedfiles";
10800: my %return_files;
1.1172.2.96 raeburn 10801: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10802: while (my $line_in = <IN>) {
1.574 banghart 10803: chomp ($line_in);
10804: my @paths_and_file = split (m!/!, $line_in);
10805: my $file_part = pop (@paths_and_file);
10806: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10807: $path_part.='/';
10808: my $path_and_file = $path_part.$file_part;
10809: if ($path_part eq $path) {
10810: $return_files{$file_part}= 'selected';
10811: }
10812: }
1.574 banghart 10813: close (IN);
10814: return (\%return_files);
1.572 banghart 10815: }
10816:
10817: # called in portfolio select mode, to show files selected NOT in current directory
10818: sub files_not_in_path {
10819: my ($user, $path) = @_;
10820: my $filename = $user."savedfiles";
10821: my @return_files;
10822: my $path_part;
1.1172.2.96 raeburn 10823: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10824: while (my $line = <IN>) {
1.572 banghart 10825: #ok, I know it's clunky, but I want it to work
1.800 albertel 10826: my @paths_and_file = split(m|/|, $line);
10827: my $file_part = pop(@paths_and_file);
10828: chomp($file_part);
10829: my $path_part = join('/', @paths_and_file);
1.572 banghart 10830: $path_part .= '/';
10831: my $path_and_file = $path_part.$file_part;
10832: if ($path_part ne $path) {
1.800 albertel 10833: push(@return_files, ($path_and_file));
1.572 banghart 10834: }
10835: }
1.800 albertel 10836: close(OUT);
1.574 banghart 10837: return (@return_files);
1.572 banghart 10838: }
10839:
1.745 raeburn 10840: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10841:
1.745 raeburn 10842: sub get_portfile_permissions {
10843: my ($domain,$user) = @_;
1.613 albertel 10844: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10845: my ($tmp)=keys(%current_permissions);
10846: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10847: return \%current_permissions;
10848: }
10849:
10850: #---------------------------------------------Get portfolio file access controls
10851:
1.749 raeburn 10852: sub get_access_controls {
1.745 raeburn 10853: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10854: my %access;
10855: my $real_file = $file;
10856: $file =~ s/\.meta$//;
1.745 raeburn 10857: if (defined($file)) {
1.749 raeburn 10858: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10859: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10860: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10861: }
10862: }
1.745 raeburn 10863: } else {
1.749 raeburn 10864: foreach my $key (keys(%{$current_permissions})) {
10865: if ($key =~ /\0accesscontrol$/) {
10866: if (defined($group)) {
10867: if ($key !~ m-^\Q$group\E/-) {
10868: next;
10869: }
10870: }
10871: my ($fullpath) = split(/\0/,$key);
10872: if (ref($$current_permissions{$key}) eq 'HASH') {
10873: foreach my $control (keys(%{$$current_permissions{$key}})) {
10874: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10875: }
10876: }
10877: }
10878: }
10879: }
10880: return %access;
10881: }
10882:
10883: sub modify_access_controls {
10884: my ($file_name,$changes,$domain,$user)=@_;
10885: my ($outcome,$deloutcome);
10886: my %store_permissions;
10887: my %new_values;
10888: my %new_control;
10889: my %translation;
10890: my @deletions = ();
10891: my $now = time;
10892: if (exists($$changes{'activate'})) {
10893: if (ref($$changes{'activate'}) eq 'HASH') {
10894: my @newitems = sort(keys(%{$$changes{'activate'}}));
10895: my $numnew = scalar(@newitems);
10896: for (my $i=0; $i<$numnew; $i++) {
10897: my $newkey = $newitems[$i];
10898: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10899: if ($newkey =~ /^\d+:/) {
10900: $newkey =~ s/^(\d+)/$newid/;
10901: $translation{$1} = $newid;
10902: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10903: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10904: $translation{$1} = $newid;
10905: }
1.749 raeburn 10906: $new_values{$file_name."\0".$newkey} =
10907: $$changes{'activate'}{$newitems[$i]};
10908: $new_control{$newkey} = $now;
10909: }
10910: }
10911: }
10912: my %todelete;
10913: my %changed_items;
10914: foreach my $action ('delete','update') {
10915: if (exists($$changes{$action})) {
10916: if (ref($$changes{$action}) eq 'HASH') {
10917: foreach my $key (keys(%{$$changes{$action}})) {
10918: my ($itemnum) = ($key =~ /^([^:]+):/);
10919: if ($action eq 'delete') {
10920: $todelete{$itemnum} = 1;
10921: } else {
10922: $changed_items{$itemnum} = $key;
10923: }
10924: }
1.745 raeburn 10925: }
10926: }
1.749 raeburn 10927: }
10928: # get lock on access controls for file.
10929: my $lockhash = {
10930: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10931: ':'.$env{'user.domain'},
10932: };
10933: my $tries = 0;
10934: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10935:
1.1172.2.79 raeburn 10936: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10937: $tries ++;
1.1172.2.79 raeburn 10938: sleep(0.1);
1.749 raeburn 10939: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10940: }
10941: if ($gotlock eq 'ok') {
10942: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10943: my ($tmp)=keys(%curr_permissions);
10944: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10945: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10946: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10947: if (ref($curr_controls) eq 'HASH') {
10948: foreach my $control_item (keys(%{$curr_controls})) {
10949: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10950: if (defined($todelete{$itemnum})) {
10951: push(@deletions,$file_name."\0".$control_item);
10952: } else {
10953: if (defined($changed_items{$itemnum})) {
10954: $new_control{$changed_items{$itemnum}} = $now;
10955: push(@deletions,$file_name."\0".$control_item);
10956: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10957: } else {
10958: $new_control{$control_item} = $$curr_controls{$control_item};
10959: }
10960: }
1.745 raeburn 10961: }
10962: }
10963: }
1.970 raeburn 10964: my ($group);
10965: if (&is_course($domain,$user)) {
10966: ($group,my $file) = split(/\//,$file_name,2);
10967: }
1.749 raeburn 10968: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10969: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10970: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10971: # remove lock
10972: my @del_lock = ($file_name."\0".'locked_access_records');
10973: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10974: my $sqlresult =
1.970 raeburn 10975: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10976: $group);
1.749 raeburn 10977: } else {
10978: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10979: }
1.749 raeburn 10980: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10981: }
10982:
1.827 raeburn 10983: sub make_public_indefinitely {
10984: my ($requrl) = @_;
10985: my $now = time;
10986: my $action = 'activate';
10987: my $aclnum = 0;
10988: if (&is_portfolio_url($requrl)) {
10989: my (undef,$udom,$unum,$file_name,$group) =
10990: &parse_portfolio_url($requrl);
10991: my $current_perms = &get_portfile_permissions($udom,$unum);
10992: my %access_controls = &get_access_controls($current_perms,
10993: $group,$file_name);
10994: foreach my $key (keys(%{$access_controls{$file_name}})) {
10995: my ($num,$scope,$end,$start) =
10996: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10997: if ($scope eq 'public') {
10998: if ($start <= $now && $end == 0) {
10999: $action = 'none';
11000: } else {
11001: $action = 'update';
11002: $aclnum = $num;
11003: }
11004: last;
11005: }
11006: }
11007: if ($action eq 'none') {
11008: return 'ok';
11009: } else {
11010: my %changes;
11011: my $newend = 0;
11012: my $newstart = $now;
11013: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11014: $changes{$action}{$newkey} = {
11015: type => 'public',
11016: time => {
11017: start => $newstart,
11018: end => $newend,
11019: },
11020: };
11021: my ($outcome,$deloutcome,$new_values,$translation) =
11022: &modify_access_controls($file_name,\%changes,$udom,$unum);
11023: return $outcome;
11024: }
11025: } else {
11026: return 'invalid';
11027: }
11028: }
11029:
1.745 raeburn 11030: #------------------------------------------------------Get Marked as Read Only
11031:
11032: sub get_marked_as_readonly {
11033: my ($domain,$user,$what,$group) = @_;
11034: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11035: my @readonly_files;
1.629 banghart 11036: my $cmp1=$what;
11037: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11038: while (my ($file_name,$value) = each(%{$current_permissions})) {
11039: if (defined($group)) {
11040: if ($file_name !~ m-^\Q$group\E/-) {
11041: next;
11042: }
11043: }
1.561 banghart 11044: if (ref($value) eq "ARRAY"){
11045: foreach my $stored_what (@{$value}) {
1.629 banghart 11046: my $cmp2=$stored_what;
1.759 albertel 11047: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11048: $cmp2=join('',@{$stored_what});
1.745 raeburn 11049: }
1.629 banghart 11050: if ($cmp1 eq $cmp2) {
1.561 banghart 11051: push(@readonly_files, $file_name);
1.745 raeburn 11052: last;
1.563 banghart 11053: } elsif (!defined($what)) {
11054: push(@readonly_files, $file_name);
1.745 raeburn 11055: last;
1.561 banghart 11056: }
11057: }
1.745 raeburn 11058: }
1.561 banghart 11059: }
11060: return @readonly_files;
11061: }
1.577 banghart 11062: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11063:
1.577 banghart 11064: sub get_marked_as_readonly_hash {
1.745 raeburn 11065: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11066: my %readonly_files;
1.745 raeburn 11067: while (my ($file_name,$value) = each(%{$current_permissions})) {
11068: if (defined($group)) {
11069: if ($file_name !~ m-^\Q$group\E/-) {
11070: next;
11071: }
11072: }
1.577 banghart 11073: if (ref($value) eq "ARRAY"){
11074: foreach my $stored_what (@{$value}) {
1.745 raeburn 11075: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11076: foreach my $lock_descriptor(@{$stored_what}) {
11077: if ($lock_descriptor eq 'graded') {
11078: $readonly_files{$file_name} = 'graded';
11079: } elsif ($lock_descriptor eq 'handback') {
11080: $readonly_files{$file_name} = 'handback';
11081: } else {
11082: if (!exists($readonly_files{$file_name})) {
11083: $readonly_files{$file_name} = 'locked';
11084: }
11085: }
1.745 raeburn 11086: }
1.750 banghart 11087: }
1.577 banghart 11088: }
11089: }
11090: }
11091: return %readonly_files;
11092: }
1.559 banghart 11093: # ------------------------------------------------------------ Unmark as Read Only
11094:
11095: sub unmark_as_readonly {
1.629 banghart 11096: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11097: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11098: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11099: $file_name = &declutter_portfile($file_name);
1.634 albertel 11100: my $symb_crs = $what;
11101: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11102: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11103: my ($tmp)=keys(%current_permissions);
11104: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11105: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11106: foreach my $file (@readonly_files) {
1.759 albertel 11107: my $clean_file = &declutter_portfile($file);
11108: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11109: my $current_locks = $current_permissions{$file};
1.563 banghart 11110: my @new_locks;
11111: my @del_keys;
11112: if (ref($current_locks) eq "ARRAY"){
11113: foreach my $locker (@{$current_locks}) {
1.632 albertel 11114: my $compare=$locker;
1.749 raeburn 11115: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11116: $compare=join('',@{$locker});
1.746 raeburn 11117: if ($compare ne $symb_crs) {
11118: push(@new_locks, $locker);
11119: }
1.563 banghart 11120: }
11121: }
1.650 albertel 11122: if (scalar(@new_locks) > 0) {
1.563 banghart 11123: $current_permissions{$file} = \@new_locks;
11124: } else {
11125: push(@del_keys, $file);
1.613 albertel 11126: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11127: delete($current_permissions{$file});
1.563 banghart 11128: }
11129: }
1.561 banghart 11130: }
1.613 albertel 11131: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11132: return;
11133: }
1.512 banghart 11134:
1.17 www 11135: # ------------------------------------------------------------ Directory lister
11136:
11137: sub dirlist {
1.955 raeburn 11138: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11139: $uri=~s/^\///;
11140: $uri=~s/\/$//;
1.253 stredwic 11141: my ($udom, $uname);
1.955 raeburn 11142: if ($getuserdir) {
1.253 stredwic 11143: $udom = $userdomain;
11144: $uname = $username;
1.955 raeburn 11145: } else {
11146: (undef,$udom,$uname)=split(/\//,$uri);
11147: if(defined($userdomain)) {
11148: $udom = $userdomain;
11149: }
11150: if(defined($username)) {
11151: $uname = $username;
11152: }
1.253 stredwic 11153: }
1.955 raeburn 11154: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11155:
1.955 raeburn 11156: $dirRoot = $perlvar{'lonDocRoot'};
11157: if (defined($getpropath)) {
11158: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11159: $dirRoot =~ s/\/$//;
1.955 raeburn 11160: } elsif (defined($getuserdir)) {
11161: my $subdir=$uname.'__';
11162: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11163: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11164: ."/$udom/$subdir/$uname";
11165: } elsif (defined($alternateRoot)) {
11166: $dirRoot = $alternateRoot;
1.751 banghart 11167: }
1.253 stredwic 11168:
11169: if($udom) {
11170: if($uname) {
1.1135 raeburn 11171: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11172: if ($uhome eq 'no_host') {
11173: return ([],'no_host');
11174: }
1.955 raeburn 11175: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11176: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11177: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11178: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11179: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11180: } else {
11181: @listing_results = map { &unescape($_); } split(/:/,$listing);
11182: }
1.605 matthew 11183: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11184: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11185: @listing_results = split(/:/,$listing);
11186: } else {
11187: @listing_results = map { &unescape($_); } split(/:/,$listing);
11188: }
1.1135 raeburn 11189: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11190: ($listing eq 'rejected') || ($listing eq 'refused') ||
11191: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11192: return ([],$listing);
11193: } else {
11194: return (\@listing_results);
1.1135 raeburn 11195: }
1.955 raeburn 11196: } elsif(!$alternateRoot) {
1.1136 raeburn 11197: my (%allusers,%listerror);
1.841 albertel 11198: my %servers = &get_servers($udom,'library');
1.955 raeburn 11199: foreach my $tryserver (keys(%servers)) {
11200: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11201: &escape($udom),$tryserver);
11202: if ($listing eq 'unknown_cmd') {
11203: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11204: $udom, $tryserver);
11205: } else {
11206: @listing_results = map { &unescape($_); } split(/:/,$listing);
11207: }
1.841 albertel 11208: if ($listing eq 'unknown_cmd') {
11209: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11210: $udom, $tryserver);
11211: @listing_results = split(/:/,$listing);
11212: } else {
11213: @listing_results =
11214: map { &unescape($_); } split(/:/,$listing);
11215: }
1.1136 raeburn 11216: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11217: ($listing eq 'rejected') || ($listing eq 'refused') ||
11218: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11219: $listerror{$tryserver} = $listing;
11220: } else {
1.841 albertel 11221: foreach my $line (@listing_results) {
11222: my ($entry) = split(/&/,$line,2);
11223: $allusers{$entry} = 1;
11224: }
11225: }
1.253 stredwic 11226: }
1.1136 raeburn 11227: my @alluserslist=();
1.800 albertel 11228: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11229: push(@alluserslist,$user.'&user');
1.253 stredwic 11230: }
1.1172.2.80 raeburn 11231: if (!%listerror) {
11232: # no errors
11233: return (\@alluserslist);
11234: } elsif (scalar(keys(%servers)) == 1) {
11235: # one library server, one error
11236: my ($key) = keys(%listerror);
11237: return (\@alluserslist, $listerror{$key});
11238: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11239: # con_lost indicates that we might miss data from at least one
11240: # library server
11241: return (\@alluserslist, 'con_lost');
11242: } else {
11243: # multiple library servers and no con_lost -> data should be
11244: # complete.
11245: return (\@alluserslist);
11246: }
11247:
1.253 stredwic 11248: } else {
1.1136 raeburn 11249: return ([],'missing username');
1.253 stredwic 11250: }
1.955 raeburn 11251: } elsif(!defined($getpropath)) {
1.1136 raeburn 11252: my $path = $perlvar{'lonDocRoot'}.'/res/';
11253: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11254: return (\@all_domains);
1.955 raeburn 11255: } else {
1.1136 raeburn 11256: return ([],'missing domain');
1.275 stredwic 11257: }
11258: }
11259:
11260: # --------------------------------------------- GetFileTimestamp
11261: # This function utilizes dirlist and returns the date stamp for
11262: # when it was last modified. It will also return an error of -1
11263: # if an error occurs
11264:
11265: sub GetFileTimestamp {
1.955 raeburn 11266: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11267: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11268: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11269: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11270: undef,$getuserdir);
11271: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11272: return -1;
11273: }
11274: if (ref($fileref) eq 'ARRAY') {
11275: my @stats = split('&',$fileref->[0]);
1.375 matthew 11276: # @stats contains first the filename, then the stat output
11277: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11278: } else {
11279: return -1;
1.253 stredwic 11280: }
1.26 www 11281: }
11282:
1.712 albertel 11283: sub stat_file {
11284: my ($uri) = @_;
1.787 albertel 11285: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11286:
1.955 raeburn 11287: my ($udom,$uname,$file);
1.712 albertel 11288: if ($uri =~ m-^/(uploaded|editupload)/-) {
11289: ($udom,$uname,$file) =
1.811 albertel 11290: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11291: $file = 'userfiles/'.$file;
11292: }
11293: if ($uri =~ m-^/res/-) {
11294: ($udom,$uname) =
1.807 albertel 11295: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11296: $file = $uri;
11297: }
11298:
11299: if (!$udom || !$uname || !$file) {
11300: # unable to handle the uri
11301: return ();
11302: }
1.956 raeburn 11303: my $getpropath;
11304: if ($file =~ /^userfiles\//) {
11305: $getpropath = 1;
11306: }
1.1136 raeburn 11307: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11308: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11309: return ();
11310: } else {
11311: if (ref($listref) eq 'ARRAY') {
11312: my @stats = split('&',$listref->[0]);
11313: shift(@stats); #filename is first
11314: return @stats;
11315: }
1.712 albertel 11316: }
11317: return ();
11318: }
11319:
1.26 www 11320: # -------------------------------------------------------- Value of a Condition
11321:
1.713 albertel 11322: # gets the value of a specific preevaluated condition
11323: # stored in the string $env{user.state.<cid>}
11324: # or looks up a condition reference in the bighash and if if hasn't
11325: # already been evaluated recurses into docondval to get the value of
11326: # the condition, then memoizing it to
11327: # $env{user.state.<cid>.<condition>}
1.40 www 11328: sub directcondval {
11329: my $number=shift;
1.620 albertel 11330: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11331: &Apache::lonuserstate::evalstate();
11332: }
1.713 albertel 11333: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11334: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11335: } elsif ($number =~ /^_/) {
11336: my $sub_condition;
11337: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11338: &GDBM_READER(),0640)) {
11339: $sub_condition=$bighash{'conditions'.$number};
11340: untie(%bighash);
11341: }
11342: my $value = &docondval($sub_condition);
1.949 raeburn 11343: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11344: return $value;
11345: }
1.620 albertel 11346: if ($env{'user.state.'.$env{'request.course.id'}}) {
11347: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11348: } else {
11349: return 2;
11350: }
11351: }
11352:
1.713 albertel 11353: # get the collection of conditions for this resource
1.26 www 11354: sub condval {
11355: my $condidx=shift;
1.54 www 11356: my $allpathcond='';
1.713 albertel 11357: foreach my $cond (split(/\|/,$condidx)) {
11358: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11359: $allpathcond.=
11360: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11361: }
1.191 harris41 11362: }
1.54 www 11363: $allpathcond=~s/\|$//;
1.713 albertel 11364: return &docondval($allpathcond);
11365: }
11366:
11367: #evaluates an expression of conditions
11368: sub docondval {
11369: my ($allpathcond) = @_;
11370: my $result=0;
11371: if ($env{'request.course.id'}
11372: && defined($allpathcond)) {
11373: my $operand='|';
11374: my @stack;
11375: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11376: if ($chunk eq '(') {
11377: push @stack,($operand,$result);
11378: } elsif ($chunk eq ')') {
11379: my $before=pop @stack;
11380: if (pop @stack eq '&') {
11381: $result=$result>$before?$before:$result;
11382: } else {
11383: $result=$result>$before?$result:$before;
11384: }
11385: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11386: $operand=$chunk;
11387: } else {
11388: my $new=directcondval($chunk);
11389: if ($operand eq '&') {
11390: $result=$result>$new?$new:$result;
11391: } else {
11392: $result=$result>$new?$result:$new;
11393: }
11394: }
11395: }
1.26 www 11396: }
11397: return $result;
1.421 albertel 11398: }
11399:
11400: # ---------------------------------------------------- Devalidate courseresdata
11401:
11402: sub devalidatecourseresdata {
11403: my ($coursenum,$coursedomain)=@_;
11404: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11405: &devalidate_cache_new('courseres',$hashid);
1.28 www 11406: }
11407:
1.763 www 11408:
1.200 www 11409: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11410: #
11411: # Parameters:
11412: # $coursenum - Number of the course.
11413: # $coursedomain - Domain at which the course was created.
11414: # Returns:
11415: # A hash of the course parameters along (I think) with timestamps
11416: # and version info.
1.877 foxr 11417:
1.624 albertel 11418: sub get_courseresdata {
11419: my ($coursenum,$coursedomain)=@_;
1.200 www 11420: my $coursehom=&homeserver($coursenum,$coursedomain);
11421: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11422: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11423: my %dumpreply;
1.417 albertel 11424: unless (defined($cached)) {
1.624 albertel 11425: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11426: $result=\%dumpreply;
1.251 albertel 11427: my ($tmp) = keys(%dumpreply);
11428: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11429: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11430: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11431: return $tmp;
1.416 albertel 11432: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11433: $result=undef;
1.599 albertel 11434: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11435: }
11436: }
1.624 albertel 11437: return $result;
11438: }
11439:
1.633 albertel 11440: sub devalidateuserresdata {
11441: my ($uname,$udom)=@_;
11442: my $hashid="$udom:$uname";
11443: &devalidate_cache_new('userres',$hashid);
11444: }
11445:
1.624 albertel 11446: sub get_userresdata {
11447: my ($uname,$udom)=@_;
11448: #most student don\'t have any data set, check if there is some data
11449: if (&EXT_cache_status($udom,$uname)) { return undef; }
11450:
11451: my $hashid="$udom:$uname";
11452: my ($result,$cached)=&is_cached_new('userres',$hashid);
11453: if (!defined($cached)) {
11454: my %resourcedata=&dump('resourcedata',$udom,$uname);
11455: $result=\%resourcedata;
11456: &do_cache_new('userres',$hashid,$result,600);
11457: }
11458: my ($tmp)=keys(%$result);
11459: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11460: return $result;
11461: }
11462: #error 2 occurs when the .db doesn't exist
11463: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11464: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11465: &logthis("<font color=\"blue\">WARNING:".
11466: " Trying to get resource data for ".
11467: $uname." at ".$udom.": ".
11468: $tmp."</font>");
11469: }
1.624 albertel 11470: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11471: #&EXT_cache_set($udom,$uname);
11472: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11473: undef($tmp); # not really an error so don't send it back
1.624 albertel 11474: }
11475: return $tmp;
11476: }
1.879 foxr 11477: #----------------------------------------------- resdata - return resource data
11478: # Purpose:
11479: # Return resource data for either users or for a course.
11480: # Parameters:
11481: # $name - Course/user name.
11482: # $domain - Name of the domain the user/course is registered on.
11483: # $type - Type of thing $name is (must be 'course' or 'user'
11484: # @which - Array of names of resources desired.
11485: # Returns:
11486: # The value of the first reasource in @which that is found in the
11487: # resource hash.
11488: # Exceptional Conditions:
11489: # If the $type passed in is not valid (not the string 'course' or
11490: # 'user', an undefined reference is returned.
11491: # If none of the resources are found, an undef is returned
1.624 albertel 11492: sub resdata {
11493: my ($name,$domain,$type,@which)=@_;
11494: my $result;
11495: if ($type eq 'course') {
11496: $result=&get_courseresdata($name,$domain);
11497: } elsif ($type eq 'user') {
11498: $result=&get_userresdata($name,$domain);
11499: }
11500: if (!ref($result)) { return $result; }
1.251 albertel 11501: foreach my $item (@which) {
1.927 albertel 11502: if (defined($result->{$item->[0]})) {
11503: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11504: }
1.250 albertel 11505: }
1.291 albertel 11506: return undef;
1.200 www 11507: }
11508:
1.1172.2.31 raeburn 11509: sub get_numsuppfiles {
11510: my ($cnum,$cdom,$ignorecache)=@_;
11511: my $hashid=$cnum.':'.$cdom;
11512: my ($suppcount,$cached);
11513: unless ($ignorecache) {
11514: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11515: }
11516: unless (defined($cached)) {
11517: my $chome=&homeserver($cnum,$cdom);
11518: unless ($chome eq 'no_host') {
11519: ($suppcount,my $errors) = (0,0);
11520: my $suppmap = 'supplemental.sequence';
11521: ($suppcount,$errors) =
11522: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11523: }
11524: &do_cache_new('suppcount',$hashid,$suppcount,600);
11525: }
11526: return $suppcount;
11527: }
11528:
1.379 matthew 11529: #
11530: # EXT resource caching routines
11531: #
11532:
11533: sub clear_EXT_cache_status {
1.383 albertel 11534: &delenv('cache.EXT.');
1.379 matthew 11535: }
11536:
11537: sub EXT_cache_status {
11538: my ($target_domain,$target_user) = @_;
1.383 albertel 11539: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11540: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11541: # We know already the user has no data
11542: return 1;
11543: } else {
11544: return 0;
11545: }
11546: }
11547:
11548: sub EXT_cache_set {
11549: my ($target_domain,$target_user) = @_;
1.383 albertel 11550: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11551: #&appenv({$cachename => time});
1.379 matthew 11552: }
11553:
1.28 www 11554: # --------------------------------------------------------- Value of a Variable
1.58 www 11555: sub EXT {
1.715 albertel 11556:
1.1172.2.28 raeburn 11557: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11558: unless ($varname) { return ''; }
1.218 albertel 11559: #get real user name/domain, courseid and symb
11560: my $courseid;
1.359 albertel 11561: my $publicuser;
1.427 www 11562: if ($symbparm) {
11563: $symbparm=&get_symb_from_alias($symbparm);
11564: }
1.218 albertel 11565: if (!($uname && $udom)) {
1.790 albertel 11566: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11567: if (!$symbparm) { $symbparm=$cursymb; }
11568: } else {
1.620 albertel 11569: $courseid=$env{'request.course.id'};
1.218 albertel 11570: }
1.48 www 11571: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11572: my $rest;
1.320 albertel 11573: if (defined($therest[0])) {
1.48 www 11574: $rest=join('.',@therest);
11575: } else {
11576: $rest='';
11577: }
1.320 albertel 11578:
1.57 www 11579: my $qualifierrest=$qualifier;
11580: if ($rest) { $qualifierrest.='.'.$rest; }
11581: my $spacequalifierrest=$space;
11582: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11583: if ($realm eq 'user') {
1.48 www 11584: # --------------------------------------------------------------- user.resource
11585: if ($space eq 'resource') {
1.651 albertel 11586: if ( (defined($Apache::lonhomework::parsing_a_problem)
11587: || defined($Apache::lonhomework::parsing_a_task))
11588: &&
1.1172.2.142 raeburn 11589: ($symbparm eq &symbread()) ) {
1.744 albertel 11590: # if we are in the middle of processing the resource the
11591: # get the value we are planning on committing
11592: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11593: return $Apache::lonhomework::results{$qualifierrest};
11594: } else {
11595: return $Apache::lonhomework::history{$qualifierrest};
11596: }
1.335 albertel 11597: } else {
1.359 albertel 11598: my %restored;
1.620 albertel 11599: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11600: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11601: } else {
11602: %restored=&restore($symbparm,$courseid,$udom,$uname);
11603: }
1.335 albertel 11604: return $restored{$qualifierrest};
11605: }
1.48 www 11606: # ----------------------------------------------------------------- user.access
11607: } elsif ($space eq 'access') {
1.218 albertel 11608: # FIXME - not supporting calls for a specific user
1.48 www 11609: return &allowed($qualifier,$rest);
11610: # ------------------------------------------ user.preferences, user.environment
11611: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11612: if (($uname eq $env{'user.name'}) &&
11613: ($udom eq $env{'user.domain'})) {
11614: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11615: } else {
1.359 albertel 11616: my %returnhash;
11617: if (!$publicuser) {
11618: %returnhash=&userenvironment($udom,$uname,
11619: $qualifierrest);
11620: }
1.218 albertel 11621: return $returnhash{$qualifierrest};
11622: }
1.48 www 11623: # ----------------------------------------------------------------- user.course
11624: } elsif ($space eq 'course') {
1.218 albertel 11625: # FIXME - not supporting calls for a specific user
1.620 albertel 11626: return $env{join('.',('request.course',$qualifier))};
1.48 www 11627: # ------------------------------------------------------------------- user.role
11628: } elsif ($space eq 'role') {
1.218 albertel 11629: # FIXME - not supporting calls for a specific user
1.620 albertel 11630: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11631: if ($qualifier eq 'value') {
11632: return $role;
11633: } elsif ($qualifier eq 'extent') {
11634: return $where;
11635: }
11636: # ----------------------------------------------------------------- user.domain
11637: } elsif ($space eq 'domain') {
1.218 albertel 11638: return $udom;
1.48 www 11639: # ------------------------------------------------------------------- user.name
11640: } elsif ($space eq 'name') {
1.218 albertel 11641: return $uname;
1.48 www 11642: # ---------------------------------------------------- Any other user namespace
1.29 www 11643: } else {
1.359 albertel 11644: my %reply;
11645: if (!$publicuser) {
11646: %reply=&get($space,[$qualifierrest],$udom,$uname);
11647: }
11648: return $reply{$qualifierrest};
1.48 www 11649: }
1.236 www 11650: } elsif ($realm eq 'query') {
11651: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11652: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11653: [$spacequalifierrest]);
1.620 albertel 11654: return $env{'form.'.$spacequalifierrest};
1.236 www 11655: } elsif ($realm eq 'request') {
1.48 www 11656: # ------------------------------------------------------------- request.browser
11657: if ($space eq 'browser') {
1.1145 bisitz 11658: return $env{'browser.'.$qualifier};
1.57 www 11659: # ------------------------------------------------------------ request.filename
11660: } else {
1.620 albertel 11661: return $env{'request.'.$spacequalifierrest};
1.29 www 11662: }
1.28 www 11663: } elsif ($realm eq 'course') {
1.48 www 11664: # ---------------------------------------------------------- course.description
1.620 albertel 11665: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11666: } elsif ($realm eq 'resource') {
1.165 www 11667:
1.620 albertel 11668: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11669: if (!$symbparm) { $symbparm=&symbread(); }
11670: }
1.693 albertel 11671:
1.1172.2.30 raeburn 11672: if ($qualifier eq '') {
11673: if ($space eq 'title') {
11674: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11675: return &gettitle($symbparm);
11676: }
1.693 albertel 11677:
1.1172.2.30 raeburn 11678: if ($space eq 'map') {
11679: my ($map) = &decode_symb($symbparm);
11680: return &symbread($map);
11681: }
11682: if ($space eq 'maptitle') {
11683: my ($map) = &decode_symb($symbparm);
11684: return &gettitle($map);
11685: }
11686: if ($space eq 'filename') {
11687: if ($symbparm) {
11688: return &clutter((&decode_symb($symbparm))[2]);
11689: }
11690: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11691: }
1.1172.2.30 raeburn 11692:
11693: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11694: if ($space eq 'visibleparts') {
11695: my $navmap = Apache::lonnavmaps::navmap->new();
11696: my $item;
11697: if (ref($navmap)) {
11698: my $res = $navmap->getBySymb($symbparm);
11699: my $parts = $res->parts();
11700: if (ref($parts) eq 'ARRAY') {
11701: $item = join(',',@{$parts});
11702: }
11703: undef($navmap);
11704: }
11705: return $item;
11706: }
11707: }
11708: }
1.693 albertel 11709:
11710: my ($section, $group, @groups);
1.593 albertel 11711: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11712: if (($courseid eq '') && ($cid)) {
11713: $courseid = $cid;
11714: }
11715: if (($symbparm && $courseid) &&
11716: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11717:
1.218 albertel 11718: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11719:
1.60 www 11720: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11721: my $symbp=$symbparm;
1.735 albertel 11722: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11723:
11724: my $symbparm=$symbp.'.'.$spacequalifierrest;
11725: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11726:
1.620 albertel 11727: if (($env{'user.name'} eq $uname) &&
11728: ($env{'user.domain'} eq $udom)) {
11729: $section=$env{'request.course.sec'};
1.733 raeburn 11730: @groups = split(/:/,$env{'request.course.groups'});
11731: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11732: } else {
1.539 albertel 11733: if (! defined($usection)) {
1.551 albertel 11734: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11735: } else {
11736: $section = $usection;
11737: }
1.733 raeburn 11738: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11739: }
11740:
11741: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11742: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11743: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11744:
1.593 albertel 11745: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11746: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11747: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11748:
1.60 www 11749: # ----------------------------------------------------------- first, check user
1.624 albertel 11750:
11751: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11752: ([$courselevelr,'resource'],
11753: [$courselevelm,'map' ],
11754: [$courselevel, 'course' ]));
1.931 albertel 11755: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11756:
1.594 albertel 11757: # ------------------------------------------------ second, check some of course
1.684 raeburn 11758: my $coursereply;
1.691 raeburn 11759: if (@groups > 0) {
11760: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11761: $mapparm,$spacequalifierrest);
1.927 albertel 11762: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11763: }
1.96 www 11764:
1.684 raeburn 11765: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11766: $env{'course.'.$courseid.'.domain'},
11767: 'course',
11768: ([$seclevelr, 'resource'],
11769: [$seclevelm, 'map' ],
11770: [$seclevel, 'course' ],
11771: [$courselevelr,'resource']));
11772: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11773:
1.60 www 11774: # ------------------------------------------------------ third, check map parms
1.218 albertel 11775: my %parmhash=();
11776: my $thisparm='';
11777: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11778: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11779: &GDBM_READER(),0640)) {
1.218 albertel 11780: $thisparm=$parmhash{$symbparm};
11781: untie(%parmhash);
11782: }
1.927 albertel 11783: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11784: }
1.594 albertel 11785: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11786:
1.218 albertel 11787: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11788: my $filename;
11789: if (!$symbparm) { $symbparm=&symbread(); }
11790: if ($symbparm) {
1.409 www 11791: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11792: } else {
1.620 albertel 11793: $filename=$env{'request.filename'};
1.282 albertel 11794: }
11795: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11796: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11797: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11798: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11799:
1.927 albertel 11800: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11801: if ($symbparm && defined($courseid) &&
1.620 albertel 11802: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11803: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11804: $env{'course.'.$courseid.'.domain'},
11805: 'course',
1.927 albertel 11806: ([$courselevelm,'map' ],
11807: [$courselevel, 'course']));
11808: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11809: }
1.145 www 11810: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11811: unless ($space eq '0') {
1.336 albertel 11812: my @parts=split(/_/,$space);
11813: my $id=pop(@parts);
11814: my $part=join('_',@parts);
11815: if ($part eq '') { $part='0'; }
1.927 albertel 11816: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11817: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11818: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11819: }
1.395 albertel 11820: if ($recurse) { return undef; }
11821: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11822: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11823: # ---------------------------------------------------- Any other user namespace
11824: } elsif ($realm eq 'environment') {
11825: # ----------------------------------------------------------------- environment
1.620 albertel 11826: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11827: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11828: } else {
1.770 albertel 11829: if ($uname eq 'anonymous' && $udom eq '') {
11830: return '';
11831: }
1.219 albertel 11832: my %returnhash=&userenvironment($udom,$uname,
11833: $spacequalifierrest);
11834: return $returnhash{$spacequalifierrest};
11835: }
1.28 www 11836: } elsif ($realm eq 'system') {
1.48 www 11837: # ----------------------------------------------------------------- system.time
11838: if ($space eq 'time') {
11839: return time;
11840: }
1.696 albertel 11841: } elsif ($realm eq 'server') {
11842: # ----------------------------------------------------------------- system.time
11843: if ($space eq 'name') {
11844: return $ENV{'SERVER_NAME'};
11845: }
1.28 www 11846: }
1.48 www 11847: return '';
1.61 www 11848: }
11849:
1.927 albertel 11850: sub get_reply {
11851: my ($reply_value) = @_;
1.940 raeburn 11852: if (ref($reply_value) eq 'ARRAY') {
11853: if (wantarray) {
11854: return @$reply_value;
11855: }
11856: return $reply_value->[0];
11857: } else {
11858: return $reply_value;
1.927 albertel 11859: }
11860: }
11861:
1.691 raeburn 11862: sub check_group_parms {
11863: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11864: my @groupitems = ();
11865: my $resultitem;
1.927 albertel 11866: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11867: foreach my $group (@{$groups}) {
11868: foreach my $level (@levels) {
1.927 albertel 11869: my $item = $courseid.'.['.$group.'].'.$level->[0];
11870: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11871: }
11872: }
11873: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11874: $env{'course.'.$courseid.'.domain'},
11875: 'course',@groupitems);
11876: return $coursereply;
11877: }
11878:
11879: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11880: my ($courseid,@groups) = @_;
11881: @groups = sort(@groups);
1.691 raeburn 11882: return @groups;
11883: }
11884:
1.395 albertel 11885: sub packages_tab_default {
11886: my ($uri,$varname)=@_;
11887: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11888:
11889: my (@extension,@specifics,$do_default);
11890: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11891: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11892: if ($pack_type eq 'default') {
11893: $do_default=1;
11894: } elsif ($pack_type eq 'extension') {
11895: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11896: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11897: # only look at packages defaults for packages that this id is
1.738 albertel 11898: push(@specifics,[$package,$pack_type,$pack_part]);
11899: }
11900: }
11901: # first look for a package that matches the requested part id
11902: foreach my $package (@specifics) {
11903: my (undef,$pack_type,$pack_part)=@{$package};
11904: next if ($pack_part ne $part);
11905: if (defined($packagetab{"$pack_type&$name&default"})) {
11906: return $packagetab{"$pack_type&$name&default"};
11907: }
11908: }
11909: # look for any possible matching non extension_ package
11910: foreach my $package (@specifics) {
11911: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11912: if (defined($packagetab{"$pack_type&$name&default"})) {
11913: return $packagetab{"$pack_type&$name&default"};
11914: }
1.585 albertel 11915: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11916: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11917: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11918: }
11919: }
1.738 albertel 11920: # look for any posible extension_ match
11921: foreach my $package (@extension) {
11922: my ($package,$pack_type)=@{$package};
11923: if (defined($packagetab{"$pack_type&$name&default"})) {
11924: return $packagetab{"$pack_type&$name&default"};
11925: }
11926: if (defined($packagetab{$package."&$name&default"})) {
11927: return $packagetab{$package."&$name&default"};
11928: }
11929: }
11930: # look for a global default setting
11931: if ($do_default && defined($packagetab{"default&$name&default"})) {
11932: return $packagetab{"default&$name&default"};
11933: }
1.395 albertel 11934: return undef;
11935: }
11936:
1.334 albertel 11937: sub add_prefix_and_part {
11938: my ($prefix,$part)=@_;
11939: my $keyroot;
11940: if (defined($prefix) && $prefix !~ /^__/) {
11941: # prefix that has a part already
11942: $keyroot=$prefix;
11943: } elsif (defined($prefix)) {
11944: # prefix that is missing a part
11945: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11946: } else {
11947: # no prefix at all
11948: if (defined($part)) { $keyroot='_'.$part; }
11949: }
11950: return $keyroot;
11951: }
11952:
1.71 www 11953: # ---------------------------------------------------------------- Get metadata
11954:
1.599 albertel 11955: my %metaentry;
1.1070 www 11956: my %importedpartids;
1.1172.2.99 raeburn 11957: my %importedrespids;
1.71 www 11958: sub metadata {
1.176 www 11959: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11960: $uri=&declutter($uri);
1.288 albertel 11961: # if it is a non metadata possible uri return quickly
1.529 albertel 11962: if (($uri eq '') ||
11963: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11964: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11965: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11966: return undef;
11967: }
1.1172.2.49 raeburn 11968: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11969: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11970: return undef;
1.288 albertel 11971: }
1.73 www 11972: my $filename=$uri;
11973: $uri=~s/\.meta$//;
1.172 www 11974: #
11975: # Is the metadata already cached?
1.177 www 11976: # Look at timestamp of caching
1.172 www 11977: # Everything is cached by the main uri, libraries are never directly cached
11978: #
1.428 albertel 11979: if (!defined($liburi)) {
1.599 albertel 11980: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11981: if (defined($cached)) { return $result->{':'.$what}; }
11982: }
11983: {
1.1069 www 11984: # Imported parts would go here
1.1172.2.99 raeburn 11985: my @origfiletagids=();
1.1069 www 11986: my $importedparts=0;
1.1172.2.99 raeburn 11987:
11988: # Imported responseids would go here
11989: my $importedresponses=0;
1.172 www 11990: #
11991: # Is this a recursive call for a library?
11992: #
1.599 albertel 11993: # if (! exists($metacache{$uri})) {
11994: # $metacache{$uri}={};
11995: # }
1.924 albertel 11996: my $cachetime = 60*60;
1.171 www 11997: if ($liburi) {
11998: $liburi=&declutter($liburi);
11999: $filename=$liburi;
1.401 bowersj2 12000: } else {
1.599 albertel 12001: &devalidate_cache_new('meta',$uri);
12002: undef(%metaentry);
1.401 bowersj2 12003: }
1.140 www 12004: my %metathesekeys=();
1.73 www 12005: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12006: my $metastring;
1.1140 www 12007: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12008: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12009: $metastring =
1.929 albertel 12010: &Apache::lonnet::ssi_body($which,
1.924 albertel 12011: ('grade_target' => 'meta'));
12012: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12013: } elsif (($uri !~ m -^(editupload)/-) &&
12014: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12015: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12016: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12017: $metastring=&getfile($file);
1.489 albertel 12018: }
1.208 albertel 12019: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12020: my $token;
1.140 www 12021: undef %metathesekeys;
1.71 www 12022: while ($token=$parser->get_token) {
1.339 albertel 12023: if ($token->[0] eq 'S') {
12024: if (defined($token->[2]->{'package'})) {
1.172 www 12025: #
12026: # This is a package - get package info
12027: #
1.339 albertel 12028: my $package=$token->[2]->{'package'};
12029: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12030: if (defined($token->[2]->{'id'})) {
12031: $keyroot.='_'.$token->[2]->{'id'};
12032: }
1.599 albertel 12033: if ($metaentry{':packages'}) {
12034: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12035: } else {
1.599 albertel 12036: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12037: }
1.736 albertel 12038: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12039: my $part=$keyroot;
12040: $part=~s/^\_//;
1.736 albertel 12041: if ($pack_entry=~/^\Q$package\E\&/ ||
12042: $pack_entry=~/^\Q$package\E_0\&/) {
12043: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12044: # ignore package.tab specified default values
12045: # here &package_tab_default() will fetch those
12046: if ($subp eq 'default') { next; }
1.736 albertel 12047: my $value=$packagetab{$pack_entry};
1.432 albertel 12048: my $unikey;
12049: if ($pack =~ /_0$/) {
12050: $unikey='parameter_0_'.$name;
12051: $part=0;
12052: } else {
12053: $unikey='parameter'.$keyroot.'_'.$name;
12054: }
1.339 albertel 12055: if ($subp eq 'display') {
12056: $value.=' [Part: '.$part.']';
12057: }
1.599 albertel 12058: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12059: $metathesekeys{$unikey}=1;
1.599 albertel 12060: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12061: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12062: }
1.599 albertel 12063: if (defined($metaentry{':'.$unikey.'.default'})) {
12064: $metaentry{':'.$unikey}=
12065: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12066: }
1.339 albertel 12067: }
12068: }
12069: } else {
1.172 www 12070: #
12071: # This is not a package - some other kind of start tag
1.339 albertel 12072: #
12073: my $entry=$token->[1];
1.1068 www 12074: my $unikey='';
1.175 www 12075:
1.339 albertel 12076: if ($entry eq 'import') {
1.175 www 12077: #
12078: # Importing a library here
1.339 albertel 12079: #
1.1067 www 12080: my $location=$parser->get_text('/import');
12081: my $dir=$filename;
12082: $dir=~s|[^/]*$||;
12083: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12084:
12085: my $importid=$token->[2]->{'id'};
1.1068 www 12086: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12087: #
12088: # Check metadata for imported file to
12089: # see if it contained response items
12090: #
12091: my %currmetaentry = %metaentry;
12092: my $libresponseorder = &metadata($location,'responseorder');
12093: my $origfile;
12094: if ($libresponseorder ne '') {
12095: if ($#origfiletagids<0) {
12096: undef(%importedrespids);
12097: undef(%importedpartids);
12098: }
12099: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12100: if (@{$importedrespids{$importid}} > 0) {
12101: $importedresponses = 1;
12102: # We need to get the original file and the imported file to get the response order correct
12103: # Load and inspect original file
12104: if ($#origfiletagids<0) {
12105: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12106: $origfile=&getfile($origfilelocation);
12107: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12108: }
12109: }
12110: }
12111: # Do not overwrite contents of %metaentry hash for resource itself with
12112: # hash populated for imported library file
12113: %metaentry = %currmetaentry;
12114: undef(%currmetaentry);
1.1068 www 12115: if ($importmode eq 'problem') {
1.1069 www 12116: # Import as problem/response
1.1068 www 12117: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12118: } elsif ($importmode eq 'part') {
12119: # Import as part(s)
1.1069 www 12120: $importedparts=1;
12121: # We need to get the original file and the imported file to get the part order correct
12122: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12123: # Load and inspect original file if we didn't do that already
12124: if ($#origfiletagids<0) {
12125: undef(%importedrespids);
12126: undef(%importedpartids);
12127: if ($origfile eq '') {
12128: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12129: $origfile=&getfile($origfilelocation);
12130: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12131: }
1.1070 www 12132: }
12133:
1.1069 www 12134: # Load and inspect imported file
12135: my $impfile=&getfile($location);
12136: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12137: if ($#impfilepartids>=0) {
12138: # This problem had parts
1.1070 www 12139: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12140: } else {
12141: # Importing by turning a single problem into a problem part
12142: # It gets the import-tags ID as part-ID
12143: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12144: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12145: }
1.1068 www 12146: } else {
12147: # Normal import
12148: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12149: if (defined($token->[2]->{'id'})) {
12150: $unikey.='_'.$token->[2]->{'id'};
12151: }
1.1067 www 12152: }
12153:
1.339 albertel 12154: if ($depthcount<20) {
1.736 albertel 12155: my $metadata =
12156: &metadata($uri,'keys', $location,$unikey,
12157: $depthcount+1);
12158: foreach my $meta (split(',',$metadata)) {
12159: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12160: $metathesekeys{$meta}=1;
1.339 albertel 12161: }
1.1068 www 12162:
12163: }
1.1067 www 12164: } else {
12165: #
12166: # Not importing, some other kind of non-package, non-library start tag
12167: #
12168: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12169: if (defined($token->[2]->{'id'})) {
12170: $unikey.='_'.$token->[2]->{'id'};
12171: }
1.339 albertel 12172: if (defined($token->[2]->{'name'})) {
12173: $unikey.='_'.$token->[2]->{'name'};
12174: }
12175: $metathesekeys{$unikey}=1;
1.736 albertel 12176: foreach my $param (@{$token->[3]}) {
12177: $metaentry{':'.$unikey.'.'.$param} =
12178: $token->[2]->{$param};
1.339 albertel 12179: }
12180: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12181: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12182: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12183: # only ws inside the tag, and not in default, so use default
12184: # as value
1.599 albertel 12185: $metaentry{':'.$unikey}=$default;
1.908 albertel 12186: } elsif ( $internaltext =~ /\S/ ) {
12187: # something interesting inside the tag
12188: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12189: } else {
1.908 albertel 12190: # no interesting values, don't set a default
1.339 albertel 12191: }
1.172 www 12192: # end of not-a-package not-a-library import
1.339 albertel 12193: }
1.172 www 12194: # end of not-a-package start tag
1.339 albertel 12195: }
1.172 www 12196: # the next is the end of "start tag"
1.339 albertel 12197: }
12198: }
1.483 albertel 12199: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12200: $extension = lc($extension);
12201: if ($extension eq 'htm') { $extension='html'; }
12202:
1.737 albertel 12203: foreach my $key (keys(%packagetab)) {
1.483 albertel 12204: #no specific packages #how's our extension
12205: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12206: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12207: \%metathesekeys);
12208: }
1.883 albertel 12209:
12210: if (!exists($metaentry{':packages'})
12211: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12212: foreach my $key (keys(%packagetab)) {
1.483 albertel 12213: #no specific packages well let's get default then
12214: if ($key!~/^default&/) { next; }
1.488 albertel 12215: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12216: \%metathesekeys);
12217: }
12218: }
1.338 www 12219: # are there custom rights to evaluate
1.599 albertel 12220: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12221:
1.338 www 12222: #
12223: # Importing a rights file here
1.339 albertel 12224: #
12225: unless ($depthcount) {
1.599 albertel 12226: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12227: my $dir=$filename;
12228: $dir=~s|[^/]*$||;
12229: $location=&filelocation($dir,$location);
1.736 albertel 12230: my $rights_metadata =
12231: &metadata($uri,'keys',$location,'_rights',
12232: $depthcount+1);
12233: foreach my $rights (split(',',$rights_metadata)) {
12234: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12235: $metathesekeys{$rights}=1;
1.339 albertel 12236: }
12237: }
12238: }
1.737 albertel 12239: # uniqifiy package listing
12240: my %seen;
12241: my @uniq_packages =
12242: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12243: $metaentry{':packages'} = join(',',@uniq_packages);
12244:
1.1172.2.99 raeburn 12245: if (($importedresponses) || ($importedparts)) {
12246: if ($importedparts) {
1.1070 www 12247: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12248: $metaentry{':partorder'}='';
12249: $metathesekeys{'partorder'}=1;
12250: }
12251: if ($importedresponses) {
12252: # We had imported responses and need to rebuild responseorder
12253: $metaentry{':responseorder'}='';
12254: $metathesekeys{'responseorder'}=1;
12255: }
12256: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12257: my $origid = $origfiletagids[$index+1];
12258: if ($origfiletagids[$index] eq 'part') {
12259: # Original part, part of the problem
12260: if ($importedparts) {
12261: $metaentry{':partorder'}.=','.$origid;
12262: }
12263: } elsif ($origfiletagids[$index] eq 'import') {
12264: if ($importedparts) {
12265: # We have imported parts at this position
12266: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12267: }
12268: if ($importedresponses) {
12269: # We have imported responses at this position
12270: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12271: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12272: }
12273: }
12274: } else {
12275: # Original response item, part of the problem
12276: if ($importedresponses) {
12277: $metaentry{':responseorder'}.=','.$origid;
12278: }
12279: }
12280: }
12281: if ($importedparts) {
12282: $metaentry{':partorder'}=~s/^\,//;
12283: }
12284: if ($importedresponses) {
12285: $metaentry{':responseorder'}=~s/^\,//;
12286: }
1.1070 www 12287: }
12288:
1.737 albertel 12289: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12290: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12291: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12292: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12293: # this is the end of "was not already recently cached
1.71 www 12294: }
1.599 albertel 12295: return $metaentry{':'.$what};
1.261 albertel 12296: }
12297:
1.488 albertel 12298: sub metadata_create_package_def {
1.483 albertel 12299: my ($uri,$key,$package,$metathesekeys)=@_;
12300: my ($pack,$name,$subp)=split(/\&/,$key);
12301: if ($subp eq 'default') { next; }
12302:
1.599 albertel 12303: if (defined($metaentry{':packages'})) {
12304: $metaentry{':packages'}.=','.$package;
1.483 albertel 12305: } else {
1.599 albertel 12306: $metaentry{':packages'}=$package;
1.483 albertel 12307: }
12308: my $value=$packagetab{$key};
12309: my $unikey;
12310: $unikey='parameter_0_'.$name;
1.599 albertel 12311: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12312: $$metathesekeys{$unikey}=1;
1.599 albertel 12313: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12314: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12315: }
1.599 albertel 12316: if (defined($metaentry{':'.$unikey.'.default'})) {
12317: $metaentry{':'.$unikey}=
12318: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12319: }
12320: }
12321:
1.261 albertel 12322: sub metadata_generate_part0 {
12323: my ($metadata,$metacache,$uri) = @_;
12324: my %allnames;
1.737 albertel 12325: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12326: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12327: my $part=$$metacache{':'.$metakey.'.part'};
12328: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12329: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12330: $allnames{$name}=$part;
12331: }
12332: }
12333: }
12334: foreach my $name (keys(%allnames)) {
12335: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12336: my $key=":parameter_0_$name";
1.261 albertel 12337: $$metacache{"$key.part"}='0';
12338: $$metacache{"$key.name"}=$name;
1.428 albertel 12339: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12340: $allnames{$name}.'_'.$name.
12341: '.type'};
1.428 albertel 12342: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12343: '.display'};
1.644 www 12344: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12345: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12346: $$metacache{"$key.display"}=$olddis;
12347: }
1.71 www 12348: }
12349:
1.764 albertel 12350: # ------------------------------------------------------ Devalidate title cache
12351:
12352: sub devalidate_title_cache {
12353: my ($url)=@_;
12354: if (!$env{'request.course.id'}) { return; }
12355: my $symb=&symbread($url);
12356: if (!$symb) { return; }
12357: my $key=$env{'request.course.id'}."\0".$symb;
12358: &devalidate_cache_new('title',$key);
12359: }
12360:
1.1014 droeschl 12361: # ------------------------------------------------- Get the title of a course
12362:
12363: sub current_course_title {
12364: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12365: }
1.301 www 12366: # ------------------------------------------------- Get the title of a resource
12367:
12368: sub gettitle {
12369: my $urlsymb=shift;
12370: my $symb=&symbread($urlsymb);
1.534 albertel 12371: if ($symb) {
1.620 albertel 12372: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12373: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12374: if (defined($cached)) {
12375: return $result;
12376: }
1.534 albertel 12377: my ($map,$resid,$url)=&decode_symb($symb);
12378: my $title='';
1.907 albertel 12379: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12380: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12381: } else {
12382: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12383: &GDBM_READER(),0640)) {
12384: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12385: $title=$bighash{'title_'.$mapid.'.'.$resid};
12386: untie(%bighash);
12387: }
1.534 albertel 12388: }
12389: $title=~s/\&colon\;/\:/gs;
12390: if ($title) {
1.1159 www 12391: # Remember both $symb and $title for dynamic metadata
12392: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12393: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12394: # Cache this title and then return it
1.599 albertel 12395: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12396: }
12397: $urlsymb=$url;
12398: }
12399: my $title=&metadata($urlsymb,'title');
12400: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12401: return $title;
1.301 www 12402: }
1.613 albertel 12403:
1.614 albertel 12404: sub get_slot {
12405: my ($which,$cnum,$cdom)=@_;
12406: if (!$cnum || !$cdom) {
1.790 albertel 12407: (undef,my $courseid)=&whichuser();
1.620 albertel 12408: $cdom=$env{'course.'.$courseid.'.domain'};
12409: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12410: }
1.703 albertel 12411: my $key=join("\0",'slots',$cdom,$cnum,$which);
12412: my %slotinfo;
12413: if (exists($remembered{$key})) {
12414: $slotinfo{$which} = $remembered{$key};
12415: } else {
12416: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12417: &Apache::lonhomework::showhash(%slotinfo);
12418: my ($tmp)=keys(%slotinfo);
12419: if ($tmp=~/^error:/) { return (); }
12420: $remembered{$key} = $slotinfo{$which};
12421: }
1.616 albertel 12422: if (ref($slotinfo{$which}) eq 'HASH') {
12423: return %{$slotinfo{$which}};
12424: }
12425: return $slotinfo{$which};
1.614 albertel 12426: }
1.1150 raeburn 12427:
12428: sub get_reservable_slots {
12429: my ($cnum,$cdom,$uname,$udom) = @_;
12430: my $now = time;
12431: my $reservable_info;
12432: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12433: if (exists($remembered{$key})) {
12434: $reservable_info = $remembered{$key};
12435: } else {
12436: my %resv;
12437: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12438: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12439: $reservable_info = \%resv;
12440: $remembered{$key} = $reservable_info;
12441: }
12442: return $reservable_info;
12443: }
12444:
12445: sub get_course_slots {
12446: my ($cnum,$cdom) = @_;
12447: my $hashid=$cnum.':'.$cdom;
12448: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12449: if (defined($cached)) {
12450: if (ref($result) eq 'HASH') {
12451: return %{$result};
12452: }
12453: } else {
12454: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12455: my ($tmp) = keys(%slots);
12456: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12457: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12458: return %slots;
12459: }
12460: }
12461: return;
12462: }
12463:
12464: sub devalidate_slots_cache {
12465: my ($cnum,$cdom)=@_;
12466: my $hashid=$cnum.':'.$cdom;
12467: &devalidate_cache_new('allslots',$hashid);
12468: }
12469:
1.1172.2.8 raeburn 12470: sub get_coursechange {
12471: my ($cdom,$cnum) = @_;
12472: if ($cdom eq '' || $cnum eq '') {
12473: return unless ($env{'request.course.id'});
12474: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12475: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12476: }
12477: my $hashid=$cdom.'_'.$cnum;
12478: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12479: if ((defined($cached)) && ($change ne '')) {
12480: return $change;
12481: } else {
12482: my %crshash;
12483: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12484: if ($crshash{'internal.contentchange'} eq '') {
12485: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12486: if ($change eq '') {
12487: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12488: $change = $crshash{'internal.created'};
12489: }
12490: } else {
12491: $change = $crshash{'internal.contentchange'};
12492: }
12493: my $cachetime = 600;
12494: &do_cache_new('crschange',$hashid,$change,$cachetime);
12495: }
12496: return $change;
12497: }
12498:
12499: sub devalidate_coursechange_cache {
12500: my ($cnum,$cdom)=@_;
12501: my $hashid=$cnum.':'.$cdom;
12502: &devalidate_cache_new('crschange',$hashid);
12503: }
12504:
1.31 www 12505: # ------------------------------------------------- Update symbolic store links
12506:
12507: sub symblist {
12508: my ($mapname,%newhash)=@_;
1.438 www 12509: $mapname=&deversion(&declutter($mapname));
1.31 www 12510: my %hash;
1.620 albertel 12511: if (($env{'request.course.fn'}) && (%newhash)) {
12512: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12513: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12514: foreach my $url (keys(%newhash)) {
1.711 albertel 12515: next if ($url eq 'last_known'
12516: && $env{'form.no_update_last_known'});
12517: $hash{declutter($url)}=&encode_symb($mapname,
12518: $newhash{$url}->[1],
12519: $newhash{$url}->[0]);
1.191 harris41 12520: }
1.31 www 12521: if (untie(%hash)) {
12522: return 'ok';
12523: }
12524: }
12525: }
12526: return 'error';
1.212 www 12527: }
12528:
12529: # --------------------------------------------------------------- Verify a symb
12530:
12531: sub symbverify {
1.1172.2.11 raeburn 12532: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12533: my $thisfn=$thisurl;
1.439 www 12534: $thisfn=&declutter($thisfn);
1.215 www 12535: # direct jump to resource in page or to a sequence - will construct own symbs
12536: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12537: # check URL part
1.409 www 12538: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12539:
1.431 www 12540: unless ($url eq $thisfn) { return 0; }
1.213 www 12541:
1.216 www 12542: $symb=&symbclean($symb);
1.510 www 12543: $thisurl=&deversion($thisurl);
1.439 www 12544: $thisfn=&deversion($thisfn);
1.213 www 12545:
12546: my %bighash;
12547: my $okay=0;
1.431 www 12548:
1.620 albertel 12549: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12550: &GDBM_READER(),0640)) {
1.1032 raeburn 12551: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12552: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12553: if ($map =~ m{^uploaded/.+\.page$}) {
12554: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12555: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12556: }
12557: }
12558: my $ids;
1.1172.2.122 raeburn 12559: if ($map =~ m{^uploaded/.+\.page$}) {
12560: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12561: } else {
12562: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12563: }
1.1102 raeburn 12564: unless ($ids) {
1.1172.2.13 raeburn 12565: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12566: $ids=$bighash{$idkey};
1.216 www 12567: }
12568: if ($ids) {
12569: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12570: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12571: $symb =~ s/\?.+$//;
12572: }
1.800 albertel 12573: foreach my $id (split(/\,/,$ids)) {
12574: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12575: if (
12576: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12577: eq $symb) {
1.1172.2.11 raeburn 12578: if (ref($encstate)) {
12579: $$encstate = $bighash{'encrypted_'.$id};
12580: }
1.1172.2.13 raeburn 12581: if (($env{'request.role.adv'}) ||
12582: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12583: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12584: $okay=1;
12585: last;
12586: }
12587: }
12588: }
1.216 www 12589: }
1.213 www 12590: untie(%bighash);
12591: }
12592: return $okay;
1.31 www 12593: }
12594:
1.210 www 12595: # --------------------------------------------------------------- Clean-up symb
12596:
12597: sub symbclean {
12598: my $symb=shift;
1.568 albertel 12599: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12600: # remove version from map
12601: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12602:
1.210 www 12603: # remove version from URL
12604: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12605:
1.507 www 12606: # remove wrapper
12607:
1.510 www 12608: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12609: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12610: return $symb;
1.409 www 12611: }
12612:
12613: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12614:
12615: sub encode_symb {
12616: my ($map,$resid,$url)=@_;
12617: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12618: }
1.409 www 12619:
12620: sub decode_symb {
1.568 albertel 12621: my $symb=shift;
12622: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12623: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12624: return (&fixversion($map),$resid,&fixversion($url));
12625: }
12626:
12627: sub fixversion {
12628: my $fn=shift;
1.609 banghart 12629: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12630: my %bighash;
12631: my $uri=&clutter($fn);
1.620 albertel 12632: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12633: # is this cached?
1.599 albertel 12634: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12635: if (defined($cached)) { return $result; }
12636: # unfortunately not cached, or expired
1.620 albertel 12637: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12638: &GDBM_READER(),0640)) {
12639: if ($bighash{'version_'.$uri}) {
12640: my $version=$bighash{'version_'.$uri};
1.444 www 12641: unless (($version eq 'mostrecent') ||
12642: ($version==&getversion($uri))) {
1.440 www 12643: $uri=~s/\.(\w+)$/\.$version\.$1/;
12644: }
12645: }
12646: untie %bighash;
1.413 www 12647: }
1.599 albertel 12648: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12649: }
12650:
12651: sub deversion {
12652: my $url=shift;
12653: $url=~s/\.\d+\.(\w+)$/\.$1/;
12654: return $url;
1.210 www 12655: }
12656:
1.31 www 12657: # ------------------------------------------------------ Return symb list entry
12658:
12659: sub symbread {
1.1172.2.126 raeburn 12660: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12661: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12662: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12663: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12664: unless (ref($possibles) eq 'HASH') {
12665: if ($ignorecachednull) {
12666: return $env{$cache_str} unless ($env{$cache_str} eq '');
12667: } else {
12668: return $env{$cache_str};
12669: }
1.1172.2.66 raeburn 12670: }
12671: }
1.242 www 12672: # no filename provided? try from environment
1.1172.2.54 raeburn 12673: unless ($thisfn) {
1.620 albertel 12674: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12675: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12676: }
12677: $thisfn=$env{'request.filename'};
1.44 www 12678: }
1.569 albertel 12679: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12680: # is that filename actually a symb? Verify, clean, and return
12681: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12682: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12683: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12684: }
1.242 www 12685: }
1.44 www 12686: $thisfn=declutter($thisfn);
1.31 www 12687: my %hash;
1.37 www 12688: my %bighash;
12689: my $syval='';
1.620 albertel 12690: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12691: my $targetfn = $thisfn;
1.609 banghart 12692: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12693: $targetfn = 'adm/wrapper/'.$thisfn;
12694: }
1.687 albertel 12695: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12696: $targetfn=$1;
12697: }
1.1172.2.128 raeburn 12698: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12699: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12700: &GDBM_READER(),0640)) {
12701: $syval=$hash{$targetfn};
12702: untie(%hash);
12703: }
1.1172.2.128 raeburn 12704: if ($syval && $checkforblock) {
12705: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12706: if (@blockers) {
12707: $syval='';
12708: }
12709: }
1.37 www 12710: }
12711: # ---------------------------------------------------------- There was an entry
12712: if ($syval) {
1.601 albertel 12713: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12714: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12715: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12716: #return $env{$cache_str}='';
1.601 albertel 12717: #}
12718: #$syval.=$1;
12719: #}
1.37 www 12720: } else {
12721: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12722: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12723: &GDBM_READER(),0640)) {
1.37 www 12724: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12725: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12726: unless ($ids) {
12727: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12728: }
12729: unless ($ids) {
12730: # alias?
12731: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12732: }
1.37 www 12733: if ($ids) {
12734: # ------------------------------------------------------------------- Has ID(s)
12735: my @possibilities=split(/\,/,$ids);
1.39 www 12736: if ($#possibilities==0) {
12737: # ----------------------------------------------- There is only one possibility
1.37 www 12738: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12739: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12740: $resid,$thisfn);
1.1172.2.66 raeburn 12741: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12742: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12743: $possibles->{$syval} = 1;
12744: }
1.1172.2.66 raeburn 12745: }
12746: if ($checkforblock) {
1.1172.2.126 raeburn 12747: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12748: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12749: if (@blockers) {
12750: $syval = '';
12751: untie(%bighash);
12752: return $env{$cache_str}='';
12753: }
1.1172.2.66 raeburn 12754: }
12755: }
12756: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12757: # ------------------------------------------ There is more than one possibility
12758: my $realpossible=0;
1.800 albertel 12759: foreach my $id (@possibilities) {
12760: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12761: my $canaccess;
12762: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12763: $canaccess = 1;
12764: } else {
12765: $canaccess = &allowed('bre',$file);
12766: }
12767: if ($canaccess) {
12768: my ($mapid,$resid)=split(/\./,$id);
12769: if ($bighash{'map_type_'.$mapid} ne 'page') {
12770: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12771: $resid,$thisfn);
1.1172.2.126 raeburn 12772: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12773: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12774: if ($checkforblock) {
1.1172.2.127 raeburn 12775: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12776: if (@blockers > 0) {
12777: $syval = '';
12778: } else {
1.1172.2.66 raeburn 12779: $syval = $poss_syval;
12780: $realpossible++;
12781: }
12782: } else {
12783: $syval = $poss_syval;
12784: $realpossible++;
12785: }
1.1172.2.126 raeburn 12786: if ($syval) {
12787: if (ref($possibles) eq 'HASH') {
12788: $possibles->{$syval} = 1;
12789: }
12790: }
1.1172.2.66 raeburn 12791: }
1.39 www 12792: }
1.191 harris41 12793: }
1.39 www 12794: if ($realpossible!=1) { $syval=''; }
1.249 www 12795: } else {
12796: $syval='';
1.37 www 12797: }
12798: }
1.1172.2.66 raeburn 12799: untie(%bighash);
1.481 raeburn 12800: }
1.31 www 12801: }
1.62 www 12802: if ($syval) {
1.1172.2.128 raeburn 12803: return $env{$cache_str}=$syval;
1.62 www 12804: }
1.31 www 12805: }
1.949 raeburn 12806: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12807: return $env{$cache_str}='';
1.31 www 12808: }
12809:
12810: # ---------------------------------------------------------- Return random seed
12811:
1.32 www 12812: sub numval {
12813: my $txt=shift;
12814: $txt=~tr/A-J/0-9/;
12815: $txt=~tr/a-j/0-9/;
12816: $txt=~tr/K-T/0-9/;
12817: $txt=~tr/k-t/0-9/;
12818: $txt=~tr/U-Z/0-5/;
12819: $txt=~tr/u-z/0-5/;
12820: $txt=~s/\D//g;
1.564 albertel 12821: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12822: return int($txt);
1.368 albertel 12823: }
12824:
1.484 albertel 12825: sub numval2 {
12826: my $txt=shift;
12827: $txt=~tr/A-J/0-9/;
12828: $txt=~tr/a-j/0-9/;
12829: $txt=~tr/K-T/0-9/;
12830: $txt=~tr/k-t/0-9/;
12831: $txt=~tr/U-Z/0-5/;
12832: $txt=~tr/u-z/0-5/;
12833: $txt=~s/\D//g;
12834: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12835: my $total;
12836: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12837: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12838: return int($total);
12839: }
12840:
1.575 albertel 12841: sub numval3 {
12842: use integer;
12843: my $txt=shift;
12844: $txt=~tr/A-J/0-9/;
12845: $txt=~tr/a-j/0-9/;
12846: $txt=~tr/K-T/0-9/;
12847: $txt=~tr/k-t/0-9/;
12848: $txt=~tr/U-Z/0-5/;
12849: $txt=~tr/u-z/0-5/;
12850: $txt=~s/\D//g;
12851: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12852: my $total;
12853: foreach my $val (@txts) { $total+=$val; }
12854: if ($_64bit) { $total=(($total<<32)>>32); }
12855: return $total;
12856: }
12857:
1.675 albertel 12858: sub digest {
12859: my ($data)=@_;
12860: my $digest=&Digest::MD5::md5($data);
12861: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12862: my ($e,$f);
12863: {
12864: use integer;
12865: $e=($a+$b);
12866: $f=($c+$d);
12867: if ($_64bit) {
12868: $e=(($e<<32)>>32);
12869: $f=(($f<<32)>>32);
12870: }
12871: }
12872: if (wantarray) {
12873: return ($e,$f);
12874: } else {
12875: my $g;
12876: {
12877: use integer;
12878: $g=($e+$f);
12879: if ($_64bit) {
12880: $g=(($g<<32)>>32);
12881: }
12882: }
12883: return $g;
12884: }
12885: }
12886:
1.368 albertel 12887: sub latest_rnd_algorithm_id {
1.675 albertel 12888: return '64bit5';
1.366 albertel 12889: }
1.32 www 12890:
1.503 albertel 12891: sub get_rand_alg {
12892: my ($courseid)=@_;
1.790 albertel 12893: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12894: if ($courseid) {
1.620 albertel 12895: return $env{"course.$courseid.rndseed"};
1.503 albertel 12896: }
12897: return &latest_rnd_algorithm_id();
12898: }
12899:
1.562 albertel 12900: sub validCODE {
12901: my ($CODE)=@_;
12902: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12903: return 0;
12904: }
12905:
1.491 albertel 12906: sub getCODE {
1.620 albertel 12907: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12908: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12909: defined($Apache::lonhomework::parsing_a_task) ) &&
12910: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12911: return $Apache::lonhomework::history{'resource.CODE'};
12912: }
12913: return undef;
12914: }
1.1133 foxr 12915: #
12916: # Determines the random seed for a specific context:
12917: #
12918: # parameters:
12919: # symb - in course context the symb for the seed.
12920: # course_id - The course id of the form domain_coursenum.
12921: # domain - Domain for the user.
12922: # course - Course for the user.
12923: # cenv - environment of the course.
12924: #
12925: # NOTE:
12926: # All parameters are picked out of the environment if missing
12927: # or not defined.
12928: # If a symb cannot be determined the current time is used instead.
12929: #
12930: # For a given well defined symb, courside, domain, username,
12931: # and course environment, the seed is reproducible.
12932: #
1.31 www 12933: sub rndseed {
1.1133 foxr 12934: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12935: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12936: if (!defined($symb)) {
1.366 albertel 12937: unless ($symb=$wsymb) { return time; }
12938: }
1.1146 foxr 12939: if (!defined $courseid) {
12940: $courseid=$wcourseid;
12941: }
12942: if (!defined $domain) { $domain=$wdomain; }
12943: if (!defined $username) { $username=$wusername }
1.1133 foxr 12944:
12945: my $which;
12946: if (defined($cenv->{'rndseed'})) {
12947: $which = $cenv->{'rndseed'};
12948: } else {
12949: $which =&get_rand_alg($courseid);
12950: }
1.491 albertel 12951: if (defined(&getCODE())) {
1.675 albertel 12952: if ($which eq '64bit5') {
12953: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12954: } elsif ($which eq '64bit4') {
1.575 albertel 12955: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12956: } else {
12957: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12958: }
1.675 albertel 12959: } elsif ($which eq '64bit5') {
12960: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12961: } elsif ($which eq '64bit4') {
12962: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12963: } elsif ($which eq '64bit3') {
12964: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12965: } elsif ($which eq '64bit2') {
12966: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12967: } elsif ($which eq '64bit') {
12968: return &rndseed_64bit($symb,$courseid,$domain,$username);
12969: }
12970: return &rndseed_32bit($symb,$courseid,$domain,$username);
12971: }
12972:
12973: sub rndseed_32bit {
12974: my ($symb,$courseid,$domain,$username)=@_;
12975: {
12976: use integer;
12977: my $symbchck=unpack("%32C*",$symb) << 27;
12978: my $symbseed=numval($symb) << 22;
12979: my $namechck=unpack("%32C*",$username) << 17;
12980: my $nameseed=numval($username) << 12;
12981: my $domainseed=unpack("%32C*",$domain) << 7;
12982: my $courseseed=unpack("%32C*",$courseid);
12983: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12984: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12985: #&logthis("rndseed :$num:$symb");
1.564 albertel 12986: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12987: return $num;
12988: }
12989: }
12990:
12991: sub rndseed_64bit {
12992: my ($symb,$courseid,$domain,$username)=@_;
12993: {
12994: use integer;
12995: my $symbchck=unpack("%32S*",$symb) << 21;
12996: my $symbseed=numval($symb) << 10;
12997: my $namechck=unpack("%32S*",$username);
12998:
12999: my $nameseed=numval($username) << 21;
13000: my $domainseed=unpack("%32S*",$domain) << 10;
13001: my $courseseed=unpack("%32S*",$courseid);
13002:
13003: my $num1=$symbchck+$symbseed+$namechck;
13004: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13005: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13006: #&logthis("rndseed :$num:$symb");
1.564 albertel 13007: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13008: return "$num1,$num2";
1.155 albertel 13009: }
1.366 albertel 13010: }
13011:
1.443 albertel 13012: sub rndseed_64bit2 {
13013: my ($symb,$courseid,$domain,$username)=@_;
13014: {
13015: use integer;
13016: # strings need to be an even # of cahracters long, it it is odd the
13017: # last characters gets thrown away
13018: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13019: my $symbseed=numval($symb) << 10;
13020: my $namechck=unpack("%32S*",$username.' ');
13021:
13022: my $nameseed=numval($username) << 21;
1.501 albertel 13023: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13024: my $courseseed=unpack("%32S*",$courseid.' ');
13025:
13026: my $num1=$symbchck+$symbseed+$namechck;
13027: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13028: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13029: #&logthis("rndseed :$num:$symb");
1.803 albertel 13030: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13031: return "$num1,$num2";
13032: }
13033: }
13034:
13035: sub rndseed_64bit3 {
13036: my ($symb,$courseid,$domain,$username)=@_;
13037: {
13038: use integer;
13039: # strings need to be an even # of cahracters long, it it is odd the
13040: # last characters gets thrown away
13041: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13042: my $symbseed=numval2($symb) << 10;
13043: my $namechck=unpack("%32S*",$username.' ');
13044:
13045: my $nameseed=numval2($username) << 21;
1.443 albertel 13046: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13047: my $courseseed=unpack("%32S*",$courseid.' ');
13048:
13049: my $num1=$symbchck+$symbseed+$namechck;
13050: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13051: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13052: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13053: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13054:
1.503 albertel 13055: return "$num1:$num2";
1.443 albertel 13056: }
13057: }
13058:
1.575 albertel 13059: sub rndseed_64bit4 {
13060: my ($symb,$courseid,$domain,$username)=@_;
13061: {
13062: use integer;
13063: # strings need to be an even # of cahracters long, it it is odd the
13064: # last characters gets thrown away
13065: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13066: my $symbseed=numval3($symb) << 10;
13067: my $namechck=unpack("%32S*",$username.' ');
13068:
13069: my $nameseed=numval3($username) << 21;
13070: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13071: my $courseseed=unpack("%32S*",$courseid.' ');
13072:
13073: my $num1=$symbchck+$symbseed+$namechck;
13074: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13075: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13076: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13077: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13078:
1.575 albertel 13079: return "$num1:$num2";
13080: }
13081: }
13082:
1.675 albertel 13083: sub rndseed_64bit5 {
13084: my ($symb,$courseid,$domain,$username)=@_;
13085: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13086: return "$num1:$num2";
13087: }
13088:
1.366 albertel 13089: sub rndseed_CODE_64bit {
13090: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13091: {
1.366 albertel 13092: use integer;
1.443 albertel 13093: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13094: my $symbseed=numval2($symb);
1.491 albertel 13095: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13096: my $CODEseed=numval(&getCODE());
1.443 albertel 13097: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13098: my $num1=$symbseed+$CODEchck;
13099: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13100: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13101: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13102: if ($_64bit) { $num1=(($num1<<32)>>32); }
13103: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13104: return "$num1:$num2";
1.366 albertel 13105: }
13106: }
13107:
1.575 albertel 13108: sub rndseed_CODE_64bit4 {
13109: my ($symb,$courseid,$domain,$username)=@_;
13110: {
13111: use integer;
13112: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13113: my $symbseed=numval3($symb);
13114: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13115: my $CODEseed=numval3(&getCODE());
13116: my $courseseed=unpack("%32S*",$courseid.' ');
13117: my $num1=$symbseed+$CODEchck;
13118: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13119: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13120: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13121: if ($_64bit) { $num1=(($num1<<32)>>32); }
13122: if ($_64bit) { $num2=(($num2<<32)>>32); }
13123: return "$num1:$num2";
13124: }
13125: }
13126:
1.675 albertel 13127: sub rndseed_CODE_64bit5 {
13128: my ($symb,$courseid,$domain,$username)=@_;
13129: my $code = &getCODE();
13130: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13131: return "$num1:$num2";
13132: }
13133:
1.366 albertel 13134: sub setup_random_from_rndseed {
13135: my ($rndseed)=@_;
1.503 albertel 13136: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13137: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13138: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13139: &Math::Random::random_set_seed_from_phrase($rndseed);
13140: } else {
13141: &Math::Random::random_set_seed($num1,$num2);
13142: }
1.366 albertel 13143: } else {
13144: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13145: }
1.36 albertel 13146: }
13147:
1.474 albertel 13148: sub latest_receipt_algorithm_id {
1.835 albertel 13149: return 'receipt3';
1.474 albertel 13150: }
13151:
1.480 www 13152: sub recunique {
13153: my $fucourseid=shift;
13154: my $unique;
1.835 albertel 13155: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13156: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13157: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13158: } else {
13159: $unique=$perlvar{'lonReceipt'};
13160: }
13161: return unpack("%32C*",$unique);
13162: }
13163:
13164: sub recprefix {
13165: my $fucourseid=shift;
13166: my $prefix;
1.835 albertel 13167: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13168: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13169: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13170: } else {
13171: $prefix=$perlvar{'lonHostID'};
13172: }
13173: return unpack("%32C*",$prefix);
13174: }
13175:
1.76 www 13176: sub ireceipt {
1.474 albertel 13177: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13178:
13179: my $return =&recprefix($fucourseid).'-';
13180:
13181: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13182: $env{'request.state'} eq 'construct') {
13183: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13184: return $return;
13185: }
13186:
1.76 www 13187: my $cuname=unpack("%32C*",$funame);
13188: my $cudom=unpack("%32C*",$fudom);
13189: my $cucourseid=unpack("%32C*",$fucourseid);
13190: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13191: my $cunique=&recunique($fucourseid);
1.474 albertel 13192: my $cpart=unpack("%32S*",$part);
1.835 albertel 13193: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13194:
1.790 albertel 13195: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13196:
13197: $return.= ($cunique%$cuname+
13198: $cunique%$cudom+
13199: $cusymb%$cuname+
13200: $cusymb%$cudom+
13201: $cucourseid%$cuname+
13202: $cucourseid%$cudom+
13203: $cpart%$cuname+
13204: $cpart%$cudom);
13205: } else {
13206: $return.= ($cunique%$cuname+
13207: $cunique%$cudom+
13208: $cusymb%$cuname+
13209: $cusymb%$cudom+
13210: $cucourseid%$cuname+
13211: $cucourseid%$cudom);
13212: }
13213: return $return;
1.76 www 13214: }
13215:
13216: sub receipt {
1.474 albertel 13217: my ($part)=@_;
1.790 albertel 13218: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13219: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13220: }
1.260 ng 13221:
1.790 albertel 13222: sub whichuser {
13223: my ($passedsymb)=@_;
13224: my ($symb,$courseid,$domain,$name,$publicuser);
13225: if (defined($env{'form.grade_symb'})) {
13226: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13227: my $allowed=&allowed('vgr',$tmp_courseid);
13228: if (!$allowed &&
13229: exists($env{'request.course.sec'}) &&
13230: $env{'request.course.sec'} !~ /^\s*$/) {
13231: $allowed=&allowed('vgr',$tmp_courseid.
13232: '/'.$env{'request.course.sec'});
13233: }
13234: if ($allowed) {
13235: ($symb)=&get_env_multiple('form.grade_symb');
13236: $courseid=$tmp_courseid;
13237: ($domain)=&get_env_multiple('form.grade_domain');
13238: ($name)=&get_env_multiple('form.grade_username');
13239: return ($symb,$courseid,$domain,$name,$publicuser);
13240: }
13241: }
13242: if (!$passedsymb) {
13243: $symb=&symbread();
13244: } else {
13245: $symb=$passedsymb;
13246: }
13247: $courseid=$env{'request.course.id'};
13248: $domain=$env{'user.domain'};
13249: $name=$env{'user.name'};
13250: if ($name eq 'public' && $domain eq 'public') {
13251: if (!defined($env{'form.username'})) {
13252: $env{'form.username'}.=time.rand(10000000);
13253: }
13254: $name.=$env{'form.username'};
13255: }
13256: return ($symb,$courseid,$domain,$name,$publicuser);
13257:
13258: }
13259:
1.36 albertel 13260: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13261: # returns either the contents of the file or
13262: # -1 if the file doesn't exist
1.481 raeburn 13263: #
13264: # if the target is a file that was uploaded via DOCS,
13265: # a check will be made to see if a current copy exists on the local server,
13266: # if it does this will be served, otherwise a copy will be retrieved from
13267: # the home server for the course and stored in /home/httpd/html/userfiles on
13268: # the local server.
1.472 albertel 13269:
1.36 albertel 13270: sub getfile {
1.538 albertel 13271: my ($file) = @_;
1.609 banghart 13272: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13273: &repcopy($file);
13274: return &readfile($file);
13275: }
13276:
13277: sub repcopy_userfile {
13278: my ($file)=@_;
1.1142 raeburn 13279: my $londocroot = $perlvar{'lonDocRoot'};
13280: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13281: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13282: my ($cdom,$cnum,$filename) =
1.811 albertel 13283: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13284: my $uri="/uploaded/$cdom/$cnum/$filename";
13285: if (-e "$file") {
1.828 www 13286: # we already have a local copy, check it out
1.538 albertel 13287: my @fileinfo = stat($file);
1.828 www 13288: my $rtncode;
13289: my $info;
1.538 albertel 13290: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13291: if ($lwpresp ne 'ok') {
1.828 www 13292: # there is no such file anymore, even though we had a local copy
1.482 albertel 13293: if ($rtncode eq '404') {
1.538 albertel 13294: unlink($file);
1.482 albertel 13295: }
13296: return -1;
13297: }
13298: if ($info < $fileinfo[9]) {
1.828 www 13299: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13300: return 'ok';
1.828 www 13301: } else {
13302: # the file is outdated, get rid of it
13303: unlink($file);
1.482 albertel 13304: }
1.828 www 13305: }
13306: # one way or the other, at this point, we don't have the file
13307: # construct the correct path for the file
13308: my @parts = ($cdom,$cnum);
13309: if ($filename =~ m|^(.+)/[^/]+$|) {
13310: push @parts, split(/\//,$1);
13311: }
13312: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13313: foreach my $part (@parts) {
13314: $path .= '/'.$part;
13315: if (!-e $path) {
13316: mkdir($path,0770);
1.482 albertel 13317: }
13318: }
1.828 www 13319: # now the path exists for sure
13320: # get a user agent
13321: my $ua=new LWP::UserAgent;
13322: my $transferfile=$file.'.in.transfer';
13323: # FIXME: this should flock
13324: if (-e $transferfile) { return 'ok'; }
13325: my $request;
13326: $uri=~s/^\///;
1.980 raeburn 13327: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13328: my $hostname = &hostname($homeserver);
1.980 raeburn 13329: my $protocol = $protocol{$homeserver};
13330: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13331: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13332: my $response=$ua->request($request,$transferfile);
13333: # did it work?
13334: if ($response->is_error()) {
13335: unlink($transferfile);
13336: &logthis("Userfile repcopy failed for $uri");
13337: return -1;
13338: }
13339: # worked, rename the transfer file
13340: rename($transferfile,$file);
1.607 raeburn 13341: return 'ok';
1.481 raeburn 13342: }
13343:
1.517 albertel 13344: sub tokenwrapper {
13345: my $uri=shift;
1.980 raeburn 13346: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13347: $uri=~s|^/||;
1.620 albertel 13348: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13349: my $token=$1;
1.552 albertel 13350: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13351: if ($udom && $uname && $file) {
13352: $file=~s|(\?\.*)*$||;
1.949 raeburn 13353: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13354: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13355: my $hostname = &hostname($homeserver);
1.980 raeburn 13356: my $protocol = $protocol{$homeserver};
13357: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13358: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13359: (($uri=~/\?/)?'&':'?').'token='.$token.
13360: '&tokenissued='.$perlvar{'lonHostID'};
13361: } else {
13362: return '/adm/notfound.html';
13363: }
13364: }
13365:
1.828 www 13366: # call with reqtype HEAD: get last modification time
13367: # call with reqtype GET: get the file contents
13368: # Do not call this with reqtype GET for large files! It loads everything into memory
13369: #
1.481 raeburn 13370: sub getuploaded {
13371: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13372: $uri=~s/^\///;
1.980 raeburn 13373: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13374: my $hostname = &hostname($homeserver);
1.980 raeburn 13375: my $protocol = $protocol{$homeserver};
13376: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13377: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13378: my $ua=new LWP::UserAgent;
13379: my $request=new HTTP::Request($reqtype,$uri);
13380: my $response=$ua->request($request);
13381: $$rtncode = $response->code;
1.482 albertel 13382: if (! $response->is_success()) {
13383: return 'failed';
13384: }
13385: if ($reqtype eq 'HEAD') {
1.486 www 13386: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13387: } elsif ($reqtype eq 'GET') {
13388: $$info = $response->content;
1.472 albertel 13389: }
1.482 albertel 13390: return 'ok';
1.36 albertel 13391: }
13392:
1.481 raeburn 13393: sub readfile {
13394: my $file = shift;
13395: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13396: my $fh;
1.1172.2.96 raeburn 13397: open($fh,"<",$file);
1.481 raeburn 13398: my $a='';
1.800 albertel 13399: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13400: return $a;
13401: }
13402:
1.36 albertel 13403: sub filelocation {
1.590 banghart 13404: my ($dir,$file) = @_;
13405: my $location;
13406: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13407:
13408: if ($file =~ m-^/adm/-) {
13409: $file=~s-^/adm/wrapper/-/-;
13410: $file=~s-^/adm/coursedocs/showdoc/-/-;
13411: }
1.882 albertel 13412:
1.1139 www 13413: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13414: $location = $file;
1.609 banghart 13415: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13416: my ($udom,$uname,$filename)=
1.811 albertel 13417: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13418: my $home=&homeserver($uname,$udom);
13419: my $is_me=0;
13420: my @ids=¤t_machine_ids();
13421: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13422: if ($is_me) {
1.1117 foxr 13423: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13424: } else {
13425: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13426: $udom.'/'.$uname.'/'.$filename;
13427: }
1.882 albertel 13428: } elsif ($file =~ m-^/adm/-) {
13429: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13430: } else {
13431: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13432: $file=~s:^/(res|priv)/:/:;
13433: my $space=$1;
1.590 banghart 13434: if ( !( $file =~ m:^/:) ) {
13435: $location = $dir. '/'.$file;
13436: } else {
1.1142 raeburn 13437: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13438: }
1.59 albertel 13439: }
1.590 banghart 13440: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13441: while ($location=~m{/\.\./}) {
13442: if ($location =~ m{/[^/]+/\.\./}) {
13443: $location=~ s{/[^/]+/\.\./}{/}g;
13444: } else {
13445: $location=~ s{/\.\./}{/}g;
13446: }
13447: } #remove dir/..
1.590 banghart 13448: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13449: return $location;
1.46 www 13450: }
1.36 albertel 13451:
1.46 www 13452: sub hreflocation {
13453: my ($dir,$file)=@_;
1.980 raeburn 13454: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13455: $file=filelocation($dir,$file);
1.700 albertel 13456: } elsif ($file=~m-^/adm/-) {
13457: $file=~s-^/adm/wrapper/-/-;
13458: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13459: }
13460: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13461: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13462: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13463: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13464: {/uploaded/$1/$2/}x;
1.46 www 13465: }
1.913 albertel 13466: if ($file=~ m{^/userfiles/}) {
13467: $file =~ s{^/userfiles/}{/uploaded/};
13468: }
1.462 albertel 13469: return $file;
1.465 albertel 13470: }
13471:
1.1139 www 13472:
13473:
13474:
13475:
1.465 albertel 13476: sub current_machine_domains {
1.853 albertel 13477: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13478: }
13479:
13480: sub machine_domains {
13481: my ($hostname) = @_;
1.465 albertel 13482: my @domains;
1.838 albertel 13483: my %hostname = &all_hostnames();
1.465 albertel 13484: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13485: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13486: if ($hostname eq $name) {
1.844 albertel 13487: push(@domains,&host_domain($id));
1.465 albertel 13488: }
13489: }
13490: return @domains;
13491: }
13492:
13493: sub current_machine_ids {
1.853 albertel 13494: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13495: }
13496:
13497: sub machine_ids {
13498: my ($hostname) = @_;
13499: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13500: my @ids;
1.888 albertel 13501: my %name_to_host = &all_names();
1.889 albertel 13502: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13503: return @{ $name_to_host{$hostname} };
13504: }
13505: return;
1.31 www 13506: }
13507:
1.824 raeburn 13508: sub additional_machine_domains {
13509: my @domains;
1.1172.2.142 raeburn 13510: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13511: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13512: while( my $line = <$fh>) {
13513: chomp($line);
13514: $line =~ s/\s//g;
13515: push(@domains,$line);
13516: }
13517: close($fh);
13518: }
1.824 raeburn 13519: }
13520: return @domains;
13521: }
13522:
13523: sub default_login_domain {
13524: my $domain = $perlvar{'lonDefDomain'};
13525: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13526: foreach my $posdom (¤t_machine_domains(),
13527: &additional_machine_domains()) {
13528: if (lc($posdom) eq lc($testdomain)) {
13529: $domain=$posdom;
13530: last;
13531: }
13532: }
13533: return $domain;
13534: }
13535:
1.1172.2.106 raeburn 13536: sub shared_institution {
1.1172.2.136 raeburn 13537: my ($dom,$lonhost) = @_;
13538: if ($lonhost eq '') {
13539: $lonhost = $perlvar{'lonHostID'};
13540: }
1.1172.2.106 raeburn 13541: my $same_intdom;
1.1172.2.136 raeburn 13542: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13543: if ($hostintdom ne '') {
13544: my %iphost = &get_iphost();
13545: my $primary_id = &domain($dom,'primary');
13546: my $primary_ip = &get_host_ip($primary_id);
13547: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13548: foreach my $id (@{$iphost{$primary_ip}}) {
13549: my $intdom = &internet_dom($id);
13550: if ($intdom eq $hostintdom) {
13551: $same_intdom = 1;
13552: last;
13553: }
13554: }
13555: }
13556: }
13557: return $same_intdom;
13558: }
13559:
1.1172.2.120 raeburn 13560: sub uses_sts {
13561: my ($ignore_cache) = @_;
13562: my $lonhost = $perlvar{'lonHostID'};
13563: my $hostname = &hostname($lonhost);
13564: my $sts_on;
13565: if ($protocol{$lonhost} eq 'https') {
13566: my $cachetime = 12*3600;
13567: if (!$ignore_cache) {
13568: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13569: if (defined($cached)) {
13570: return $sts_on;
13571: }
13572: }
1.1172.2.121 raeburn 13573: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13574: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13575: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13576: my $response=$ua->request($request);
1.1172.2.120 raeburn 13577: if ($response->is_success) {
13578: my $has_sts = $response->header('Strict-Transport-Security');
13579: if ($has_sts eq '') {
13580: $sts_on = 0;
13581: } else {
13582: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13583: my $maxage = $1;
13584: if ($maxage) {
13585: $sts_on = 1;
13586: } else {
13587: $sts_on = 0;
13588: }
13589: } else {
13590: $sts_on = 0;
13591: }
13592: }
13593: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13594: }
13595: }
13596: return;
13597: }
13598:
1.1172.2.142 raeburn 13599: sub waf_allssl {
13600: my ($host_name) = @_;
13601: my $alias = &get_proxy_alias();
13602: if ($host_name eq '') {
13603: $host_name = $ENV{'SERVER_NAME'};
13604: }
13605: if (($host_name ne '') && ($alias eq $host_name)) {
13606: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13607: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13608: if ($defdomdefaults{'waf_sslopt'}) {
13609: return $defdomdefaults{'waf_sslopt'};
13610: }
13611: }
13612: return;
13613: }
13614:
1.1172.2.134 raeburn 13615: sub get_requestor_ip {
13616: my ($r,$nolookup,$noproxy) = @_;
13617: my $from_ip;
13618: if (ref($r)) {
1.1172.2.142 raeburn 13619: if ($r->can('useragent_ip')) {
13620: if ($noproxy && $r->can('client_ip')) {
13621: $from_ip = $r->client_ip();
13622: } else {
13623: $from_ip = $r->useragent_ip();
13624: }
13625: } elsif ($r->connection->can('remote_ip')) {
13626: $from_ip = $r->connection->remote_ip();
13627: } else {
13628: $from_ip = $r->get_remote_host($nolookup);
13629: }
1.1172.2.134 raeburn 13630: } else {
13631: $from_ip = $ENV{'REMOTE_ADDR'};
13632: }
1.1172.2.142 raeburn 13633: return $from_ip if ($noproxy);
13634: # Who controls proxy settings for server
13635: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13636: my $proxyinfo = &get_proxy_settings($dom_in_use);
13637: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13638: if ($proxyinfo->{'vpnint'}) {
13639: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13640: return $from_ip;
13641: }
13642: }
13643: if ($proxyinfo->{'trusted'}) {
13644: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13645: my $ipheader = $proxyinfo->{'ipheader'};
13646: my ($ip,$xfor);
13647: if (ref($r)) {
13648: if ($ipheader) {
13649: $ip = $r->headers_in->{$ipheader};
13650: }
13651: $xfor = $r->headers_in->{'X-Forwarded-For'};
13652: } else {
13653: if ($ipheader) {
13654: $ip = $ENV{'HTTP_'.uc($ipheader)};
13655: }
13656: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13657: }
13658: if (($ip eq '') && ($xfor ne '')) {
13659: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13660: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13661: $ip = $poss_ip;
13662: last;
13663: }
13664: }
13665: }
13666: if ($ip ne '') {
13667: return $ip;
13668: }
13669: }
13670: }
13671: }
1.1172.2.134 raeburn 13672: return $from_ip;
13673: }
13674:
1.1172.2.142 raeburn 13675: sub get_proxy_settings {
13676: my ($dom_in_use) = @_;
13677: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13678: my $proxyinfo = {
13679: ipheader => $domdefaults{'waf_ipheader'},
13680: trusted => $domdefaults{'waf_trusted'},
13681: vpnint => $domdefaults{'waf_vpnint'},
13682: vpnext => $domdefaults{'waf_vpnext'},
13683: sslopt => $domdefaults{'waf_sslopt'},
13684: };
13685: return $proxyinfo;
13686: }
13687:
13688: sub ip_match {
13689: my ($ip,$pattern_str) = @_;
13690: $ip=Net::CIDR::cidrvalidate($ip);
13691: if ($ip) {
13692: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13693: }
13694: return;
13695: }
13696:
13697: sub get_proxy_alias {
13698: my ($lonid) = @_;
13699: if ($lonid eq '') {
13700: $lonid = $perlvar{'lonHostID'};
13701: }
13702: if (!defined(&hostname($lonid))) {
13703: return;
13704: }
13705: if ($lonid ne '') {
13706: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13707: if ($cached) {
13708: return $alias;
13709: }
13710: my $dom = &Apache::lonnet::host_domain($lonid);
13711: if ($dom ne '') {
13712: my $cachetime = 60*60*24;
13713: my %domconfig =
13714: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13715: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13716: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13717: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13718: }
13719: }
13720: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13721: }
13722: }
13723: return;
13724: }
13725:
13726: sub use_proxy_alias {
13727: my ($r,$lonid) = @_;
13728: my $alias = &get_proxy_alias($lonid);
13729: if ($alias) {
13730: my $dom = &host_domain($lonid);
13731: if ($dom ne '') {
13732: my $proxyinfo = &get_proxy_settings($dom);
13733: my ($vpnint,$remote_ip);
13734: if (ref($proxyinfo) eq 'HASH') {
13735: $vpnint = $proxyinfo->{'vpnint'};
13736: if ($vpnint) {
13737: $remote_ip = &get_requestor_ip($r,1,1);
13738: }
13739: }
13740: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13741: return $alias;
13742: }
13743: }
13744: }
13745: return;
13746: }
13747:
13748: sub alias_sso {
13749: my ($lonid) = @_;
13750: if ($lonid eq '') {
13751: $lonid = $perlvar{'lonHostID'};
13752: }
13753: if (!defined(&hostname($lonid))) {
13754: return;
13755: }
13756: if ($lonid ne '') {
13757: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13758: if ($cached) {
13759: return $use_alias;
13760: }
13761: my $dom = &Apache::lonnet::host_domain($lonid);
13762: if ($dom ne '') {
13763: my $cachetime = 60*60*24;
13764: my %domconfig =
13765: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13766: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13767: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13768: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13769: }
13770: }
13771: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13772: }
13773: }
13774: return;
13775: }
13776:
13777: sub get_saml_landing {
13778: my ($lonid) = @_;
13779: if ($lonid eq '') {
13780: my $defdom = &default_login_domain();
13781: my @hosts = ¤t_machine_ids();
13782: if (@hosts > 1) {
13783: foreach my $hostid (@hosts) {
13784: if (&host_domain($hostid) eq $defdom) {
13785: $lonid = $hostid;
13786: last;
13787: }
13788: }
13789: } else {
13790: $lonid = $perlvar{'lonHostID'};
13791: }
13792: if ($lonid) {
13793: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13794: return;
13795: }
13796: } else {
13797: return;
13798: }
13799: } elsif (!defined(&hostname($lonid))) {
13800: return;
13801: }
13802: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13803: if ($cached) {
13804: return $landing;
13805: }
13806: my $dom = &Apache::lonnet::host_domain($lonid);
13807: if ($dom ne '') {
13808: my $cachetime = 60*60*24;
13809: my %domconfig =
13810: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13811: if (ref($domconfig{'login'}) eq 'HASH') {
13812: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13813: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13814: $landing = 1;
13815: }
13816: }
13817: }
13818: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13819: }
13820: return;
13821: }
13822:
1.31 www 13823: # ------------------------------------------------------------- Declutters URLs
13824:
13825: sub declutter {
13826: my $thisfn=shift;
1.569 albertel 13827: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13828: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13829: $thisfn=~s{^/home/httpd/html}{};
13830: }
1.31 www 13831: $thisfn=~s/^\///;
1.697 albertel 13832: $thisfn=~s|^adm/wrapper/||;
13833: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13834: $thisfn=~s/^res\///;
1.1172 bisitz 13835: $thisfn=~s/^priv\///;
1.1032 raeburn 13836: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13837: $thisfn=~s/\?.+$//;
13838: }
1.268 www 13839: return $thisfn;
13840: }
13841:
13842: # ------------------------------------------------------------- Clutter up URLs
13843:
13844: sub clutter {
13845: my $thisfn='/'.&declutter(shift);
1.887 albertel 13846: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13847: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13848: $thisfn='/res'.$thisfn;
13849: }
1.1031 raeburn 13850: if ($thisfn !~m|^/adm|) {
13851: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13852: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13853: } else {
13854: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13855: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13856: if ($embstyle eq 'ssi'
13857: || ($embstyle eq 'hdn')
13858: || ($embstyle eq 'rat')
13859: || ($embstyle eq 'prv')
13860: || ($embstyle eq 'ign')) {
13861: #do nothing with these
13862: } elsif (($embstyle eq 'img')
1.695 albertel 13863: || ($embstyle eq 'emb')
13864: || ($embstyle eq 'wrp')) {
13865: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13866: } elsif ($embstyle eq 'unk'
13867: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13868: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13869: } else {
1.718 www 13870: # &logthis("Got a blank emb style");
1.695 albertel 13871: }
1.694 albertel 13872: }
13873: }
1.31 www 13874: return $thisfn;
1.12 www 13875: }
13876:
1.787 albertel 13877: sub clutter_with_no_wrapper {
13878: my $uri = &clutter(shift);
13879: if ($uri =~ m-^/adm/-) {
13880: $uri =~ s-^/adm/wrapper/-/-;
13881: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13882: }
13883: return $uri;
13884: }
13885:
1.557 albertel 13886: sub freeze_escape {
13887: my ($value)=@_;
13888: if (ref($value)) {
13889: $value=&nfreeze($value);
13890: return '__FROZEN__'.&escape($value);
13891: }
13892: return &escape($value);
13893: }
13894:
1.11 www 13895:
1.557 albertel 13896: sub thaw_unescape {
13897: my ($value)=@_;
13898: if ($value =~ /^__FROZEN__/) {
13899: substr($value,0,10,undef);
13900: $value=&unescape($value);
13901: return &thaw($value);
13902: }
13903: return &unescape($value);
13904: }
13905:
1.436 albertel 13906: sub correct_line_ends {
13907: my ($result)=@_;
13908: $$result =~s/\r\n/\n/mg;
13909: $$result =~s/\r/\n/mg;
1.415 albertel 13910: }
1.1 albertel 13911: # ================================================================ Main Program
13912:
1.184 www 13913: sub goodbye {
1.204 albertel 13914: &logthis("Starting Shut down");
1.443 albertel 13915: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13916: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13917: #converted
1.599 albertel 13918: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13919: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13920: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13921: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13922: #1.1 only
1.870 albertel 13923: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13924: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13925: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13926: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13927: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13928: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13929: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13930: &flushcourselogs();
13931: &logthis("Shutting down");
13932: }
13933:
1.852 albertel 13934: sub get_dns {
1.1172.2.17 raeburn 13935: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13936: if (!$ignore_cache) {
13937: my ($content,$cached)=
13938: &Apache::lonnet::is_cached_new('dns',$url);
13939: if ($cached) {
1.1172.2.17 raeburn 13940: &$func($content,$hashref);
1.869 albertel 13941: return;
13942: }
13943: }
13944:
13945: my %alldns;
1.1172.2.96 raeburn 13946: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13947: foreach my $dns (<$config>) {
13948: next if ($dns !~ /^\^(\S*)/x);
13949: my $line = $1;
13950: my ($host,$protocol) = split(/:/,$line);
13951: if ($protocol ne 'https') {
13952: $protocol = 'http';
13953: }
13954: $alldns{$host} = $protocol;
1.979 raeburn 13955: }
1.1172.2.96 raeburn 13956: close($config);
1.869 albertel 13957: }
13958: while (%alldns) {
1.1172.2.52 raeburn 13959: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13960: my @content;
13961: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13962: my $command = (split('/',$url))[3];
13963: my ($dir,$file) = &parse_getdns_url($command,$url);
13964: delete($alldns{$dns});
13965: next if (($dir eq '') || ($file eq ''));
13966: if (open(my $config,'<',"$dir/$file")) {
13967: @content = <$config>;
13968: close($config);
13969: }
13970: } else {
13971: my $ua=new LWP::UserAgent;
13972: $ua->timeout(30);
13973: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13974: my $response=$ua->request($request);
13975: delete($alldns{$dns});
13976: next if ($response->is_error());
13977: @content = split("\n",$response->content);
13978: }
1.1172.2.17 raeburn 13979: unless ($nocache) {
1.1172.2.23 raeburn 13980: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13981: }
13982: &$func(\@content,$hashref);
1.869 albertel 13983: return;
1.852 albertel 13984: }
1.871 albertel 13985: my $which = (split('/',$url))[3];
13986: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13987: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13988: my @content = <$config>;
13989: &$func(\@content,$hashref);
13990: }
1.1172.2.17 raeburn 13991: return;
13992: }
13993:
13994: # ------------------------------------------------------Get DNS checksums file
13995: sub parse_dns_checksums_tab {
13996: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13997: my $lonhost = $perlvar{'lonHostID'};
13998: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13999: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14000: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14001: my $webconfdir = '/etc/httpd/conf';
14002: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14003: $webconfdir = '/etc/apache2';
14004: } elsif ($distro =~ /^sles(\d+)$/) {
14005: if ($1 >= 10) {
14006: $webconfdir = '/etc/apache2';
14007: }
14008: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14009: if ($1 >= 10.0) {
14010: $webconfdir = '/etc/apache2';
14011: }
14012: }
1.1172.2.17 raeburn 14013: my ($release,$timestamp) = split(/\-/,$loncaparev);
14014: my (%chksum,%revnum);
14015: if (ref($lines) eq 'ARRAY') {
14016: chomp(@{$lines});
1.1172.2.34 raeburn 14017: my $version = shift(@{$lines});
14018: if ($version eq $release) {
1.1172.2.17 raeburn 14019: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14020: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14021: if ($file =~ m{^/etc/httpd/conf}) {
14022: if ($webconfdir eq '/etc/apache2') {
14023: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14024: }
14025: }
1.1172.2.34 raeburn 14026: $chksum{$file} = $shasum;
14027: $revnum{$file} = $version;
1.1172.2.17 raeburn 14028: }
14029: if (ref($hashref) eq 'HASH') {
14030: %{$hashref} = (
14031: sums => \%chksum,
14032: versions => \%revnum,
14033: );
14034: }
14035: }
14036: }
1.869 albertel 14037: return;
1.852 albertel 14038: }
1.1172.2.17 raeburn 14039:
14040: sub fetch_dns_checksums {
14041: my %checksums;
1.1172.2.34 raeburn 14042: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14043: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14044: my ($release,$timestamp) = split(/\-/,$loncaparev);
14045: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14046: \%checksums);
14047: return \%checksums;
14048: }
14049:
1.1172.2.142 raeburn 14050: sub parse_getdns_url {
14051: my ($command,$url) = @_;
14052: my $dir = $perlvar{'lonTabDir'};
14053: my $file;
14054: if ($command eq 'hosts') {
14055: $file = 'dns_hosts.tab';
14056: } elsif ($command eq 'domain') {
14057: $file = 'dns_domain.tab';
14058: } elsif ($command eq 'checksums') {
14059: my $version = (split('/',$url))[4];
14060: $file = "dns_checksums/$version.tab",
14061: }
14062: return ($dir,$file);
14063: }
14064:
1.327 albertel 14065: # ------------------------------------------------------------ Read domain file
14066: {
1.852 albertel 14067: my $loaded;
1.846 albertel 14068: my %domain;
14069:
1.852 albertel 14070: sub parse_domain_tab {
14071: my ($lines) = @_;
14072: foreach my $line (@$lines) {
14073: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14074:
1.846 albertel 14075: chomp($line);
1.852 albertel 14076: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14077: my %this_domain;
14078: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14079: 'lang_def', 'city', 'longi', 'lati',
14080: 'primary') {
14081: $this_domain{$field} = shift(@elements);
14082: }
14083: $domain{$name} = \%this_domain;
1.852 albertel 14084: }
14085: }
1.864 albertel 14086:
14087: sub reset_domain_info {
14088: undef($loaded);
14089: undef(%domain);
14090: }
14091:
1.852 albertel 14092: sub load_domain_tab {
1.1172.2.70 raeburn 14093: my ($ignore_cache,$nocache) = @_;
14094: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14095: my $fh;
1.1172.2.96 raeburn 14096: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14097: my @lines = <$fh>;
14098: &parse_domain_tab(\@lines);
1.448 albertel 14099: }
1.852 albertel 14100: close($fh);
14101: $loaded = 1;
1.327 albertel 14102: }
1.846 albertel 14103:
14104: sub domain {
1.852 albertel 14105: &load_domain_tab() if (!$loaded);
14106:
1.846 albertel 14107: my ($name,$what) = @_;
14108: return if ( !exists($domain{$name}) );
14109:
14110: if (!$what) {
14111: return $domain{$name}{'description'};
14112: }
14113: return $domain{$name}{$what};
14114: }
1.974 raeburn 14115:
14116: sub domain_info {
14117: &load_domain_tab() if (!$loaded);
14118: return %domain;
14119: }
14120:
1.327 albertel 14121: }
14122:
14123:
1.1 albertel 14124: # ------------------------------------------------------------- Read hosts file
14125: {
1.838 albertel 14126: my %hostname;
1.844 albertel 14127: my %hostdom;
1.845 albertel 14128: my %libserv;
1.852 albertel 14129: my $loaded;
1.888 albertel 14130: my %name_to_host;
1.1074 raeburn 14131: my %internetdom;
1.1107 raeburn 14132: my %LC_dns_serv;
1.852 albertel 14133:
14134: sub parse_hosts_tab {
14135: my ($file) = @_;
14136: foreach my $configline (@$file) {
14137: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14138: chomp($configline);
14139: if ($configline =~ /^\^/) {
14140: if ($configline =~ /^\^([\w.\-]+)/) {
14141: $LC_dns_serv{$1} = 1;
14142: }
14143: next;
14144: }
1.1074 raeburn 14145: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14146: $name=~s/\s//g;
14147: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14148: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14149: my $curr = $hostname{$id};
14150: my $skip;
14151: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14152: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14153: $skip = 1;
14154: } else {
14155: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14156: }
14157: }
14158: unless ($skip) {
14159: push(@{$name_to_host{$name}},$id);
14160: }
14161: } else {
14162: push(@{$name_to_host{$name}},$id);
14163: }
1.852 albertel 14164: $hostname{$id}=$name;
14165: $hostdom{$id}=$domain;
14166: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14167: if (defined($protocol)) {
14168: if ($protocol eq 'https') {
14169: $protocol{$id} = $protocol;
14170: } else {
14171: $protocol{$id} = 'http';
14172: }
1.968 raeburn 14173: } else {
1.969 raeburn 14174: $protocol{$id} = 'http';
1.968 raeburn 14175: }
1.1074 raeburn 14176: if (defined($intdom)) {
14177: $internetdom{$id} = $intdom;
14178: }
1.852 albertel 14179: }
14180: }
14181: }
1.864 albertel 14182:
14183: sub reset_hosts_info {
1.897 albertel 14184: &purge_remembered();
1.864 albertel 14185: &reset_domain_info();
14186: &reset_hosts_ip_info();
1.892 albertel 14187: undef(%name_to_host);
1.864 albertel 14188: undef(%hostname);
14189: undef(%hostdom);
14190: undef(%libserv);
14191: undef($loaded);
14192: }
1.1 albertel 14193:
1.852 albertel 14194: sub load_hosts_tab {
1.1172.2.70 raeburn 14195: my ($ignore_cache,$nocache) = @_;
14196: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14197: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14198: my @config = <$config>;
14199: &parse_hosts_tab(\@config);
14200: close($config);
14201: $loaded=1;
1.1 albertel 14202: }
1.852 albertel 14203:
1.838 albertel 14204: sub hostname {
1.852 albertel 14205: &load_hosts_tab() if (!$loaded);
14206:
1.838 albertel 14207: my ($lonid) = @_;
14208: return $hostname{$lonid};
14209: }
1.845 albertel 14210:
1.838 albertel 14211: sub all_hostnames {
1.852 albertel 14212: &load_hosts_tab() if (!$loaded);
14213:
1.838 albertel 14214: return %hostname;
14215: }
1.845 albertel 14216:
1.888 albertel 14217: sub all_names {
1.1172.2.70 raeburn 14218: my ($ignore_cache,$nocache) = @_;
14219: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14220:
14221: return %name_to_host;
14222: }
14223:
1.974 raeburn 14224: sub all_host_domain {
14225: &load_hosts_tab() if (!$loaded);
14226: return %hostdom;
14227: }
14228:
1.845 albertel 14229: sub is_library {
1.852 albertel 14230: &load_hosts_tab() if (!$loaded);
14231:
1.845 albertel 14232: return exists($libserv{$_[0]});
14233: }
14234:
14235: sub all_library {
1.852 albertel 14236: &load_hosts_tab() if (!$loaded);
14237:
1.845 albertel 14238: return %libserv;
14239: }
14240:
1.1062 droeschl 14241: sub unique_library {
14242: #2x reverse removes all hostnames that appear more than once
14243: my %unique = reverse &all_library();
14244: return reverse %unique;
14245: }
14246:
1.841 albertel 14247: sub get_servers {
1.852 albertel 14248: &load_hosts_tab() if (!$loaded);
14249:
1.841 albertel 14250: my ($domain,$type) = @_;
14251: my %possible_hosts = ($type eq 'library') ? %libserv
14252: : %hostname;
14253: my %result;
1.842 albertel 14254: if (ref($domain) eq 'ARRAY') {
14255: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14256: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14257: $result{$host} = $hostname;
14258: }
14259: }
14260: } else {
14261: while ( my ($host,$hostname) = each(%possible_hosts)) {
14262: if ($hostdom{$host} eq $domain) {
14263: $result{$host} = $hostname;
14264: }
1.841 albertel 14265: }
14266: }
14267: return %result;
14268: }
1.845 albertel 14269:
1.1062 droeschl 14270: sub get_unique_servers {
14271: my %unique = reverse &get_servers(@_);
14272: return reverse %unique;
14273: }
14274:
1.844 albertel 14275: sub host_domain {
1.852 albertel 14276: &load_hosts_tab() if (!$loaded);
14277:
1.844 albertel 14278: my ($lonid) = @_;
14279: return $hostdom{$lonid};
14280: }
14281:
1.841 albertel 14282: sub all_domains {
1.852 albertel 14283: &load_hosts_tab() if (!$loaded);
14284:
1.841 albertel 14285: my %seen;
14286: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14287: return @uniq;
14288: }
1.1074 raeburn 14289:
14290: sub internet_dom {
14291: &load_hosts_tab() if (!$loaded);
14292:
14293: my ($lonid) = @_;
14294: return $internetdom{$lonid};
14295: }
1.1107 raeburn 14296:
14297: sub is_LC_dns {
14298: &load_hosts_tab() if (!$loaded);
14299:
14300: my ($hostname) = @_;
14301: return exists($LC_dns_serv{$hostname});
14302: }
14303:
1.1 albertel 14304: }
14305:
1.847 albertel 14306: {
14307: my %iphost;
1.856 albertel 14308: my %name_to_ip;
14309: my %lonid_to_ip;
1.869 albertel 14310:
1.847 albertel 14311: sub get_hosts_from_ip {
14312: my ($ip) = @_;
14313: my %iphosts = &get_iphost();
14314: if (ref($iphosts{$ip})) {
14315: return @{$iphosts{$ip}};
14316: }
14317: return;
1.839 albertel 14318: }
1.864 albertel 14319:
14320: sub reset_hosts_ip_info {
14321: undef(%iphost);
14322: undef(%name_to_ip);
14323: undef(%lonid_to_ip);
14324: }
1.856 albertel 14325:
14326: sub get_host_ip {
14327: my ($lonid) = @_;
14328: if (exists($lonid_to_ip{$lonid})) {
14329: return $lonid_to_ip{$lonid};
14330: }
14331: my $name=&hostname($lonid);
14332: my $ip = gethostbyname($name);
14333: return if (!$ip || length($ip) ne 4);
14334: $ip=inet_ntoa($ip);
14335: $name_to_ip{$name} = $ip;
14336: $lonid_to_ip{$lonid} = $ip;
14337: return $ip;
14338: }
1.847 albertel 14339:
14340: sub get_iphost {
1.1172.2.70 raeburn 14341: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14342:
1.869 albertel 14343: if (!$ignore_cache) {
14344: if (%iphost) {
14345: return %iphost;
14346: }
14347: my ($ip_info,$cached)=
14348: &Apache::lonnet::is_cached_new('iphost','iphost');
14349: if ($cached) {
14350: %iphost = %{$ip_info->[0]};
14351: %name_to_ip = %{$ip_info->[1]};
14352: %lonid_to_ip = %{$ip_info->[2]};
14353: return %iphost;
14354: }
14355: }
1.894 albertel 14356:
14357: # get yesterday's info for fallback
14358: my %old_name_to_ip;
14359: my ($ip_info,$cached)=
14360: &Apache::lonnet::is_cached_new('iphost','iphost');
14361: if ($cached) {
14362: %old_name_to_ip = %{$ip_info->[1]};
14363: }
14364:
1.1172.2.70 raeburn 14365: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14366: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14367: my $ip;
14368: if (!exists($name_to_ip{$name})) {
14369: $ip = gethostbyname($name);
14370: if (!$ip || length($ip) ne 4) {
1.894 albertel 14371: if (defined($old_name_to_ip{$name})) {
14372: $ip = $old_name_to_ip{$name};
14373: &logthis("Can't find $name defaulting to old $ip");
14374: } else {
14375: &logthis("Name $name no IP found");
14376: next;
14377: }
14378: } else {
14379: $ip=inet_ntoa($ip);
1.847 albertel 14380: }
14381: $name_to_ip{$name} = $ip;
14382: } else {
14383: $ip = $name_to_ip{$name};
1.653 albertel 14384: }
1.888 albertel 14385: foreach my $id (@{ $name_to_host{$name} }) {
14386: $lonid_to_ip{$id} = $ip;
14387: }
14388: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14389: }
1.1172.2.70 raeburn 14390: unless ($nocache) {
14391: &do_cache_new('iphost','iphost',
14392: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14393: 48*60*60);
14394: }
1.869 albertel 14395:
1.847 albertel 14396: return %iphost;
1.598 albertel 14397: }
14398:
1.992 raeburn 14399: #
14400: # Given a DNS returns the loncapa host name for that DNS
14401: #
14402: sub host_from_dns {
14403: my ($dns) = @_;
14404: my @hosts;
14405: my $ip;
14406:
1.993 raeburn 14407: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14408: $ip = $name_to_ip{$dns};
14409: }
14410: if (!$ip) {
14411: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14412: if (length($ip) == 4) {
14413: $ip = &IO::Socket::inet_ntoa($ip);
14414: }
14415: }
14416: if ($ip) {
14417: @hosts = get_hosts_from_ip($ip);
14418: return $hosts[0];
14419: }
14420: return undef;
1.986 foxr 14421: }
1.992 raeburn 14422:
1.1074 raeburn 14423: sub get_internet_names {
14424: my ($lonid) = @_;
14425: return if ($lonid eq '');
14426: my ($idnref,$cached)=
14427: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14428: if ($cached) {
14429: return $idnref;
14430: }
14431: my $ip = &get_host_ip($lonid);
14432: my @hosts = &get_hosts_from_ip($ip);
14433: my %iphost = &get_iphost();
14434: my (@idns,%seen);
14435: foreach my $id (@hosts) {
14436: my $dom = &host_domain($id);
14437: my $prim_id = &domain($dom,'primary');
14438: my $prim_ip = &get_host_ip($prim_id);
14439: next if ($seen{$prim_ip});
14440: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14441: foreach my $id (@{$iphost{$prim_ip}}) {
14442: my $intdom = &internet_dom($id);
14443: unless (grep(/^\Q$intdom\E$/,@idns)) {
14444: push(@idns,$intdom);
14445: }
14446: }
14447: }
14448: $seen{$prim_ip} = 1;
14449: }
1.1172.2.23 raeburn 14450: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14451: }
14452:
1.986 foxr 14453: }
14454:
1.1079 raeburn 14455: sub all_loncaparevs {
1.1172.2.39 raeburn 14456: 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 14457: }
14458:
1.1172.2.27 raeburn 14459: # ------------------------------------------------------- Read loncaparev table
14460: {
14461: sub load_loncaparevs {
14462: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14463: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14464: while (my $configline=<$config>) {
14465: chomp($configline);
14466: my ($hostid,$loncaparev)=split(/:/,$configline);
14467: $loncaparevs{$hostid}=$loncaparev;
14468: }
14469: close($config);
14470: }
14471: }
14472: }
14473: }
14474:
14475: # ----------------------------------------------------- Read serverhostID table
14476: {
14477: sub load_serverhomeIDs {
14478: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14479: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14480: while (my $configline=<$config>) {
14481: chomp($configline);
14482: my ($name,$id)=split(/:/,$configline);
14483: $serverhomeIDs{$name}=$id;
14484: }
14485: close($config);
14486: }
14487: }
14488: }
14489: }
14490:
14491:
1.862 albertel 14492: BEGIN {
14493:
14494: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14495: unless ($readit) {
14496: {
14497: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14498: %perlvar = (%perlvar,%{$configvars});
14499: }
14500:
14501:
1.1 albertel 14502: # ------------------------------------------------------ Read spare server file
14503: {
1.1172.2.96 raeburn 14504: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14505:
14506: while (my $configline=<$config>) {
14507: chomp($configline);
1.284 matthew 14508: if ($configline) {
1.784 albertel 14509: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14510: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14511: push(@{ $spareid{$type} }, $host);
1.1 albertel 14512: }
14513: }
1.448 albertel 14514: close($config);
1.1 albertel 14515: }
1.11 www 14516: # ------------------------------------------------------------ Read permissions
14517: {
1.1172.2.96 raeburn 14518: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14519:
14520: while (my $configline=<$config>) {
1.448 albertel 14521: chomp($configline);
14522: if ($configline) {
14523: my ($role,$perm)=split(/ /,$configline);
14524: if ($perm ne '') { $pr{$role}=$perm; }
14525: }
1.11 www 14526: }
1.448 albertel 14527: close($config);
1.11 www 14528: }
14529:
14530: # -------------------------------------------- Read plain texts for permissions
14531: {
1.1172.2.96 raeburn 14532: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14533:
14534: while (my $configline=<$config>) {
1.448 albertel 14535: chomp($configline);
14536: if ($configline) {
1.742 raeburn 14537: my ($short,@plain)=split(/:/,$configline);
14538: %{$prp{$short}} = ();
14539: if (@plain > 0) {
14540: $prp{$short}{'std'} = $plain[0];
14541: for (my $i=1; $i<@plain; $i++) {
14542: $prp{$short}{'alt'.$i} = $plain[$i];
14543: }
14544: }
1.448 albertel 14545: }
1.135 www 14546: }
1.448 albertel 14547: close($config);
1.135 www 14548: }
14549:
14550: # ---------------------------------------------------------- Read package table
14551: {
1.1172.2.96 raeburn 14552: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14553:
14554: while (my $configline=<$config>) {
1.483 albertel 14555: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14556: chomp($configline);
14557: my ($short,$plain)=split(/:/,$configline);
14558: my ($pack,$name)=split(/\&/,$short);
14559: if ($plain ne '') {
14560: $packagetab{$pack.'&'.$name.'&name'}=$name;
14561: $packagetab{$short}=$plain;
14562: }
1.11 www 14563: }
1.448 albertel 14564: close($config);
1.329 matthew 14565: }
14566:
1.1172.2.27 raeburn 14567: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14568:
1.1172.2.27 raeburn 14569: &load_loncaparevs();
14570:
14571: # ------------------------------------------------------- Read serverhostID table
14572:
14573: &load_serverhomeIDs();
1.1074 raeburn 14574:
1.1172.2.27 raeburn 14575: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14576: {
14577: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14578: if (-e $file) {
14579: my $parser = HTML::LCParser->new($file);
14580: while (my $token = $parser->get_token()) {
14581: if ($token->[0] eq 'S') {
14582: my $item = $token->[1];
14583: my $name = $token->[2]{'name'};
14584: my $value = $token->[2]{'value'};
14585: if ($item ne '' && $name ne '' && $value ne '') {
14586: my $release = $parser->get_text();
14587: $release =~ s/(^\s*|\s*$ )//gx;
14588: $needsrelease{$item.':'.$name.':'.$value} = $release;
14589: }
14590: }
14591: }
14592: }
1.1073 raeburn 14593: }
14594:
1.1138 raeburn 14595: # ---------------------------------------------------------- Read managers table
14596: {
14597: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14598: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14599: while (my $configline=<$config>) {
14600: chomp($configline);
14601: next if ($configline =~ /^\#/);
14602: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14603: $managerstab{$configline} = 1;
14604: }
14605: }
14606: close($config);
14607: }
14608: }
14609: }
14610:
1.329 matthew 14611: # ------------- set up temporary directory
14612: {
1.1117 foxr 14613: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14614:
1.11 www 14615: }
14616:
1.1172.2.104 raeburn 14617: # ------------- set default texengine (domain default overrides this)
14618: {
14619: $deftex = LONCAPA::texengine();
14620: }
14621:
1.1172.2.114 raeburn 14622: # ------------- set default minimum length for passwords for internal auth users
14623: {
14624: $passwdmin = LONCAPA::passwd_min();
14625: }
14626:
1.794 albertel 14627: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14628: 'compress_threshold'=> 20_000,
14629: });
1.185 www 14630:
1.281 www 14631: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14632: $dumpcount=0;
1.958 www 14633: $locknum=0;
1.22 www 14634:
1.163 harris41 14635: &logtouch();
1.672 albertel 14636: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14637: $readit=1;
1.564 albertel 14638: {
14639: use integer;
14640: my $test=(2**32)+1;
1.568 albertel 14641: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14642: &logthis(" Detected 64bit platform ($_64bit)");
14643: }
1.195 www 14644: }
1.1 albertel 14645: }
1.179 www 14646:
1.1 albertel 14647: 1;
1.191 harris41 14648: __END__
14649:
1.243 albertel 14650: =pod
14651:
1.191 harris41 14652: =head1 NAME
14653:
1.243 albertel 14654: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14655:
14656: =head1 SYNOPSIS
14657:
1.243 albertel 14658: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14659:
14660: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14661:
1.243 albertel 14662: Common parameters:
14663:
14664: =over 4
14665:
14666: =item *
14667:
14668: $uname : an internal username (if $cname expecting a course Id specifically)
14669:
14670: =item *
14671:
14672: $udom : a domain (if $cdom expecting a course's domain specifically)
14673:
14674: =item *
14675:
14676: $symb : a resource instance identifier
14677:
14678: =item *
14679:
14680: $namespace : the name of a .db file that contains the data needed or
14681: being set.
14682:
14683: =back
14684:
1.394 bowersj2 14685: =head1 OVERVIEW
1.191 harris41 14686:
1.394 bowersj2 14687: lonnet provides subroutines which interact with the
14688: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14689: about classes, users, and resources.
1.243 albertel 14690:
14691: For many of these objects you can also use this to store data about
14692: them or modify them in various ways.
1.191 harris41 14693:
1.394 bowersj2 14694: =head2 Symbs
1.191 harris41 14695:
1.394 bowersj2 14696: To identify a specific instance of a resource, LON-CAPA uses symbols
14697: or "symbs"X<symb>. These identifiers are built from the URL of the
14698: map, the resource number of the resource in the map, and the URL of
14699: the resource itself. The latter is somewhat redundant, but might help
14700: if maps change.
14701:
14702: An example is
14703:
14704: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14705:
14706: The respective map entry is
14707:
14708: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14709: title="Problem 2">
14710: </resource>
14711:
14712: Symbs are used by the random number generator, as well as to store and
14713: restore data specific to a certain instance of for example a problem.
14714:
14715: =head2 Storing And Retrieving Data
14716:
14717: X<store()>X<cstore()>X<restore()>Three of the most important functions
14718: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14719: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14720: is is the non-critical message twin of cstore. These functions are for
14721: handlers to store a perl hash to a user's permanent data space in an
14722: easy manner, and to retrieve it again on another call. It is expected
14723: that a handler would use this once at the beginning to retrieve data,
14724: and then again once at the end to send only the new data back.
14725:
14726: The data is stored in the user's data directory on the user's
14727: homeserver under the ID of the course.
14728:
14729: The hash that is returned by restore will have all of the previous
14730: value for all of the elements of the hash.
14731:
14732: Example:
14733:
14734: #creating a hash
14735: my %hash;
14736: $hash{'foo'}='bar';
14737:
14738: #storing it
14739: &Apache::lonnet::cstore(\%hash);
14740:
14741: #changing a value
14742: $hash{'foo'}='notbar';
14743:
14744: #adding a new value
14745: $hash{'bar'}='foo';
14746: &Apache::lonnet::cstore(\%hash);
14747:
14748: #retrieving the hash
14749: my %history=&Apache::lonnet::restore();
14750:
14751: #print the hash
14752: foreach my $key (sort(keys(%history))) {
14753: print("\%history{$key} = $history{$key}");
14754: }
14755:
14756: Will print out:
1.191 harris41 14757:
1.394 bowersj2 14758: %history{1:foo} = bar
14759: %history{1:keys} = foo:timestamp
14760: %history{1:timestamp} = 990455579
14761: %history{2:bar} = foo
14762: %history{2:foo} = notbar
14763: %history{2:keys} = foo:bar:timestamp
14764: %history{2:timestamp} = 990455580
14765: %history{bar} = foo
14766: %history{foo} = notbar
14767: %history{timestamp} = 990455580
14768: %history{version} = 2
14769:
14770: Note that the special hash entries C<keys>, C<version> and
14771: C<timestamp> were added to the hash. C<version> will be equal to the
14772: total number of versions of the data that have been stored. The
14773: C<timestamp> attribute will be the UNIX time the hash was
14774: stored. C<keys> is available in every historical section to list which
14775: keys were added or changed at a specific historical revision of a
14776: hash.
14777:
14778: B<Warning>: do not store the hash that restore returns directly. This
14779: will cause a mess since it will restore the historical keys as if the
14780: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14781:
1.394 bowersj2 14782: Calling convention:
1.191 harris41 14783:
1.1172.2.27 raeburn 14784: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14785: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14786:
1.394 bowersj2 14787: For more detailed information, see lonnet specific documentation.
1.191 harris41 14788:
1.394 bowersj2 14789: =head1 RETURN MESSAGES
1.191 harris41 14790:
1.394 bowersj2 14791: =over 4
1.191 harris41 14792:
1.394 bowersj2 14793: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14794:
1.394 bowersj2 14795: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14796: when the connection is brought back up
1.191 harris41 14797:
1.394 bowersj2 14798: =item * B<con_failed>: unable to contact remote host and unable to save message
14799: for later delivery
1.191 harris41 14800:
1.967 bisitz 14801: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14802:
1.394 bowersj2 14803: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14804: that was requested
1.191 harris41 14805:
1.243 albertel 14806: =back
1.191 harris41 14807:
1.243 albertel 14808: =head1 PUBLIC SUBROUTINES
1.191 harris41 14809:
1.243 albertel 14810: =head2 Session Environment Functions
1.191 harris41 14811:
1.243 albertel 14812: =over 4
1.191 harris41 14813:
1.394 bowersj2 14814: =item *
14815: X<appenv()>
1.949 raeburn 14816: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14817: the user envirnoment file, and will be restored for each access this
1.620 albertel 14818: user makes during this session, also modifies the %env for the current
1.949 raeburn 14819: process. Optional rolesarrayref - if defined contains a reference to an array
14820: of roles which are exempt from the restriction on modifying user.role entries
14821: in the user's environment.db and in %env.
1.191 harris41 14822:
14823: =item *
1.394 bowersj2 14824: X<delenv()>
1.987 raeburn 14825: B<delenv($delthis,$regexp)>: removes all items from the session
14826: environment file that begin with $delthis. If the
14827: optional second arg - $regexp - is true, $delthis is treated as a
14828: regular expression, otherwise \Q$delthis\E is used.
14829: The values are also deleted from the current processes %env.
1.191 harris41 14830:
1.795 albertel 14831: =item * get_env_multiple($name)
14832:
14833: gets $name from the %env hash, it seemlessly handles the cases where multiple
14834: values may be defined and end up as an array ref.
14835:
14836: returns an array of values
14837:
1.243 albertel 14838: =back
14839:
14840: =head2 User Information
1.191 harris41 14841:
1.243 albertel 14842: =over 4
1.191 harris41 14843:
14844: =item *
1.394 bowersj2 14845: X<queryauthenticate()>
14846: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14847: authentication scheme
14848:
14849: =item *
1.394 bowersj2 14850: X<authenticate()>
1.1073 raeburn 14851: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14852: authenticate user from domain's lib servers (first use the current
14853: one). C<$upass> should be the users password.
1.1073 raeburn 14854: $checkdefauth is optional (value is 1 if a check should be made to
14855: authenticate user using default authentication method, and allow
14856: account creation if username does not have account in the domain).
14857: $clientcancheckhost is optional (value is 1 if checking whether the
14858: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14859:
14860: =item *
1.394 bowersj2 14861: X<homeserver()>
14862: B<homeserver($uname,$udom)>: find the server which has
14863: the user's directory and files (there must be only one), this caches
14864: the answer, and also caches if there is a borken connection.
1.191 harris41 14865:
14866: =item *
1.394 bowersj2 14867: X<idget()>
14868: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14869: (IDs are a unique resource in a domain, there must be only 1 ID per
14870: username, and only 1 username per ID in a specific domain) (returns
14871: hash: id=>name,id=>name)
1.191 harris41 14872:
14873: =item *
1.394 bowersj2 14874: X<idrget()>
14875: B<idrget($udom,@unames)>: find the IDs behind a list of
14876: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14877:
14878: =item *
1.394 bowersj2 14879: X<idput()>
14880: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14881:
14882: =item *
1.394 bowersj2 14883: X<rolesinit()>
1.1169 droeschl 14884: B<rolesinit($udom,$username)>: get user privileges.
14885: returns user role, first access and timer interval hashes
1.243 albertel 14886:
14887: =item *
1.1171 droeschl 14888: X<privileged()>
14889: B<privileged($username,$domain)>: returns a true if user has a
14890: privileged and active role (i.e. su or dc), false otherwise.
14891:
14892: =item *
1.551 albertel 14893: X<getsection()>
14894: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14895: course $cname, return section name/number or '' for "not in course"
14896: and '-1' for "no section"
14897:
14898: =item *
1.394 bowersj2 14899: X<userenvironment()>
14900: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14901: passed in @what from the requested user's environment, returns a hash
14902:
1.858 raeburn 14903: =item *
14904: X<userlog_query()>
1.859 albertel 14905: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14906: activity.log file. %filters defines filters applied when parsing the
14907: log file. These can be start or end timestamps, or the type of action
14908: - log to look for Login or Logout events, check for Checkin or
14909: Checkout, role for role selection. The response is in the form
14910: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14911: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14912:
1.243 albertel 14913: =back
14914:
14915: =head2 User Roles
14916:
14917: =over 4
14918:
14919: =item *
14920:
1.1172.2.65 raeburn 14921: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14922: returns codes for allowed actions.
14923:
14924: The first argument is required, all others are optional.
14925:
14926: $priv is the privilege being checked.
14927: $uri contains additional information about what is being checked for access (e.g.,
14928: URL, course ID etc.).
14929: $symb is the unique resource instance identifier in a course; if needed,
14930: but not provided, it will be retrieved via a call to &symbread().
14931: $role is the role for which a priv is being checked (only used if priv is evb).
14932: $clientip is the user's IP address (only used when checking for access to portfolio
14933: files).
14934: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14935: prevents recursive calls to &allowed.
14936:
1.243 albertel 14937: F: full access
14938: U,I,K: authentication modes (cxx only)
14939: '': forbidden
14940: 1: user needs to choose course
14941: 2: browse allowed
1.766 albertel 14942: A: passphrase authentication needed
1.1172.2.65 raeburn 14943: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14944:
14945: =item *
14946:
1.1172.2.13 raeburn 14947: constructaccess($url,$setpriv) : check for access to construction space URL
14948:
14949: See if the owner domain and name in the URL match those in the
14950: expected environment. If so, return three element list
14951: ($ownername,$ownerdomain,$ownerhome).
14952:
14953: Otherwise return the null string.
14954:
14955: If second argument 'setpriv' is true, it assigns the privileges,
14956: and returns the same three element list, unless the owner has
14957: blocked "ad hoc" Domain Coordinator access to the Author Space,
14958: in which case the null string is returned.
14959:
14960: =item *
14961:
1.1172.2.84 raeburn 14962: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14963: define a custom role rolename set privileges in format of lonTabs/roles.tab
14964: for system, domain, and course level. $uname and $udom are optional (current
14965: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14966:
14967: =item *
14968:
1.988 raeburn 14969: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14970: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14971: $type is Course (default) or Community.
1.988 raeburn 14972: If $forcedefault evaluates to true, text returned will be default
14973: text for $type. Otherwise, if this is a course, the text returned
14974: will be a custom name for the role (if defined in the course's
14975: environment). If no custom name is defined the default is returned.
14976:
1.832 raeburn 14977: =item *
14978:
1.1172.2.23 raeburn 14979: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14980: All arguments are optional. Returns a hash of a roles, either for
14981: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14982: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14983: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14984: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14985: For each key, value is set to colon-separated start and end times for
14986: the role. If no username and domain are specified, will default to
1.934 raeburn 14987: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14988: of role statuses (active, future or previous), roles
14989: (e.g., cc,in, st etc.) and domains of the roles which can be used
14990: to restrict the list of roles reported. If no array ref is
14991: provided for types, will default to return only active roles.
1.834 albertel 14992:
1.1172.2.13 raeburn 14993: =item *
14994:
14995: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14996: user: $uname:$udom has a role in the course: $cdom_$cnum.
14997:
14998: Additional optional arguments are: $type (if role checking is to be restricted
14999: to certain user status types -- previous (expired roles), active (currently
15000: available roles) or future (roles available in the future), and
15001: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15002: have active Domain Coordinator role in course's domain or in additional
15003: domains (specified in 'Domains to check for privileged users' in course
15004: environment -- set via: Course Settings -> Classlists and staff listing).
15005:
15006: =item *
15007:
15008: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15009: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15010: $possdomains and $possroles are optional array refs -- to domains to check and
15011: roles to check. If $possdomains is not specified, a dump will be done of the
15012: users' roles.db to check for a dc or su role in any domain. This can be
15013: time consuming if &privileged is called repeatedly (e.g., when displaying a
15014: classlist), so in such cases, supplying a $possdomains array is preferred, as
15015: this then allows &privileged_by_domain() to be used, which caches the identity
15016: of privileged users, eliminating the need for repeated calls to &dump().
15017:
15018: =item *
15019:
15020: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15021: where the outer hash keys are domains specified in the $possdomains array ref,
15022: next inner hash keys are privileged roles specified in the $roles array ref,
15023: and the innermost hash contains key = value pairs for username:domain = end:start
15024: for active or future "privileged" users with that role in that domain. To avoid
15025: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15026: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15027:
1.243 albertel 15028: =back
15029:
15030: =head2 User Modification
15031:
15032: =over 4
15033:
15034: =item *
15035:
1.957 raeburn 15036: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15037: user for the level given by URL. Optional start and end dates (leave empty
15038: string or zero for "no date")
1.191 harris41 15039:
15040: =item *
15041:
1.243 albertel 15042: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15043: change a users, password, possible return values are: ok,
15044: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15045: refused
1.191 harris41 15046:
15047: =item *
15048:
1.243 albertel 15049: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15050:
15051: =item *
15052:
1.1058 raeburn 15053: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15054: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15055:
15056: will update user information (firstname,middlename,lastname,generation,
15057: permanentemail), and if forceid is true, student/employee ID also.
15058: A user's institutional affiliation(s) can also be updated.
15059: User information fields will not be overwritten with empty entries
15060: unless the field is included in the $candelete array reference.
15061: This array is included when a single user is modified via "Manage Users",
15062: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15063:
15064: =item *
15065:
1.286 matthew 15066: modifystudent
15067:
1.957 raeburn 15068: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15069: The course id is resolved based on the current user's environment.
15070: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15071: associated with a course.
15072:
1.297 matthew 15073: This call is essentially a wrapper for lonnet::modifyuser and
15074: lonnet::modify_student_enrollment
1.286 matthew 15075:
15076: Inputs:
15077:
15078: =over 4
15079:
1.957 raeburn 15080: =item B<$udom> Student's loncapa domain
1.286 matthew 15081:
1.957 raeburn 15082: =item B<$uname> Student's loncapa login name
1.286 matthew 15083:
1.964 bisitz 15084: =item B<$uid> Student/Employee ID
1.286 matthew 15085:
1.957 raeburn 15086: =item B<$umode> Student's authentication mode
1.286 matthew 15087:
1.957 raeburn 15088: =item B<$upass> Student's password
1.286 matthew 15089:
1.957 raeburn 15090: =item B<$first> Student's first name
1.286 matthew 15091:
1.957 raeburn 15092: =item B<$middle> Student's middle name
1.286 matthew 15093:
1.957 raeburn 15094: =item B<$last> Student's last name
1.286 matthew 15095:
1.957 raeburn 15096: =item B<$gene> Student's generation
1.286 matthew 15097:
1.957 raeburn 15098: =item B<$usec> Student's section in course
1.286 matthew 15099:
15100: =item B<$end> Unix time of the roles expiration
15101:
15102: =item B<$start> Unix time of the roles start date
15103:
15104: =item B<$forceid> If defined, allow $uid to be changed
15105:
15106: =item B<$desiredhome> server to use as home server for student
15107:
1.957 raeburn 15108: =item B<$email> Student's permanent e-mail address
15109:
15110: =item B<$type> Type of enrollment (auto or manual)
15111:
1.963 raeburn 15112: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15113:
15114: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15115:
1.963 raeburn 15116: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15117:
1.963 raeburn 15118: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15119:
1.1172.2.19 raeburn 15120: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15121:
15122: =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 15123:
1.286 matthew 15124: =back
1.297 matthew 15125:
15126: =item *
15127:
15128: modify_student_enrollment
15129:
1.1172.2.31 raeburn 15130: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15131: 'role.request.course' must be defined for this function to proceed.
15132:
15133: Inputs:
15134:
15135: =over 4
15136:
1.1172.2.31 raeburn 15137: =item $udom, student's domain
1.297 matthew 15138:
1.1172.2.31 raeburn 15139: =item $uname, student's name
1.297 matthew 15140:
1.1172.2.31 raeburn 15141: =item $uid, student's user id
1.297 matthew 15142:
1.1172.2.31 raeburn 15143: =item $first, student's first name
1.297 matthew 15144:
15145: =item $middle
15146:
15147: =item $last
15148:
15149: =item $gene
15150:
15151: =item $usec
15152:
15153: =item $end
15154:
15155: =item $start
15156:
1.957 raeburn 15157: =item $type
15158:
15159: =item $locktype
15160:
15161: =item $cid
15162:
15163: =item $selfenroll
15164:
15165: =item $context
15166:
1.1172.2.19 raeburn 15167: =item $credits, number of credits student will earn from this class
15168:
1.1172.2.76 raeburn 15169: =item $instsec, institutional course section code for student
15170:
1.297 matthew 15171: =back
15172:
1.191 harris41 15173:
15174: =item *
15175:
1.243 albertel 15176: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15177: custom role; give a custom role to a user for the level given by URL. Specify
15178: name and domain of role author, and role name
1.191 harris41 15179:
15180: =item *
15181:
1.243 albertel 15182: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15183:
15184: =item *
15185:
1.243 albertel 15186: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15187:
15188: =back
15189:
15190: =head2 Course Infomation
15191:
15192: =over 4
1.191 harris41 15193:
15194: =item *
15195:
1.1118 foxr 15196: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15197: specified course id, including all environment settings for the
15198: course, the description of the course will be in the hash under the
15199: key 'description'
1.191 harris41 15200:
1.1118 foxr 15201: $options is an optional parameter that if supplied is a hash reference that controls
15202: what how this function works. It has the following key/values:
15203:
15204: =over 4
15205:
15206: =item freshen_cache
15207:
15208: If defined, and the environment cache for the course is valid, it is
15209: returned in the returned hash.
15210:
15211: =item one_time
15212:
15213: If defined, the last cache time is set to _now_
15214:
15215: =item user
15216:
15217: If defined, the supplied username is used instead of the current user.
15218:
15219:
15220: =back
15221:
1.191 harris41 15222: =item *
15223:
1.624 albertel 15224: resdata($name,$domain,$type,@which) : request for current parameter
15225: setting for a specific $type, where $type is either 'course' or 'user',
15226: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15227: answers for 10 minutes.
1.243 albertel 15228:
1.877 foxr 15229: =item *
15230:
15231: get_courseresdata($courseid, $domain) : dump the entire course resource
15232: data base, returning a hash that is keyed by the resource name and has
15233: values that are the resource value. I believe that the timestamps and
15234: versions are also returned.
15235:
1.1172.2.31 raeburn 15236: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15237: supplemental content area. This routine caches the number of files for
15238: 10 minutes.
15239:
1.243 albertel 15240: =back
15241:
15242: =head2 Course Modification
15243:
15244: =over 4
1.191 harris41 15245:
15246: =item *
15247:
1.243 albertel 15248: writecoursepref($courseid,%prefs) : write preferences (environment
15249: database) for a course
1.191 harris41 15250:
15251: =item *
15252:
1.1011 raeburn 15253: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15254:
15255: =item *
15256:
1.1038 raeburn 15257: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15258:
1.1167 droeschl 15259: =item *
15260:
15261: is_course($courseid), is_course($cdom, $cnum)
15262:
15263: Accepts either a combined $courseid (in the form of domain_courseid) or the
15264: two component version $cdom, $cnum. It checks if the specified course exists.
15265:
15266: Returns:
15267: undef if the course doesn't exist, otherwise
15268: in scalar context the combined courseid.
15269: in list context the two components of the course identifier, domain and
15270: courseid.
15271:
1.243 albertel 15272: =back
15273:
1.1172.2.109 raeburn 15274: =head2 Bubblesheet Configuration
15275:
15276: =over 4
15277:
15278: =item *
15279:
15280: get_scantron_config($which)
15281:
15282: $which - the name of the configuration to parse from the file.
15283:
15284: Parses and returns the bubblesheet configuration line selected as a
15285: hash of configuration file fields.
15286:
15287:
15288: Returns:
15289: If the named configuration is not in the file, an empty
15290: hash is returned.
15291:
15292: a hash with the fields
15293: name - internal name for the this configuration setup
15294: description - text to display to operator that describes this config
15295: CODElocation - if 0 or the string 'none'
15296: - no CODE exists for this config
15297: if -1 || the string 'letter'
15298: - a CODE exists for this config and is
15299: a string of letters
15300: Unsupported value (but planned for future support)
15301: if a positive integer
15302: - The CODE exists as the first n items from
15303: the question section of the form
15304: if the string 'number'
15305: - The CODE exists for this config and is
15306: a string of numbers
15307: CODEstart - (only matter if a CODE exists) column in the line where
15308: the CODE starts
15309: CODElength - length of the CODE
15310: IDstart - column where the student/employee ID starts
15311: IDlength - length of the student/employee ID info
15312: Qstart - column where the information from the bubbled
15313: 'questions' start
15314: Qlength - number of columns comprising a single bubble line from
15315: the sheet. (usually either 1 or 10)
15316: Qon - either a single character representing the character used
15317: to signal a bubble was chosen in the positional setup, or
15318: the string 'letter' if the letter of the chosen bubble is
15319: in the final, or 'number' if a number representing the
15320: chosen bubble is in the file (1->A 0->J)
15321: Qoff - the character used to represent that a bubble was
15322: left blank
15323: PaperID - if the scanning process generates a unique number for each
15324: sheet scanned the column that this ID number starts in
15325: PaperIDlength - number of columns that comprise the unique ID number
15326: for the sheet of paper
15327: FirstName - column that the first name starts in
15328: FirstNameLength - number of columns that the first name spans
15329: LastName - column that the last name starts in
15330: LastNameLength - number of columns that the last name spans
15331: BubblesPerRow - number of bubbles available in each row used to
15332: bubble an answer. (If not specified, 10 assumed).
15333:
15334:
15335: =item *
15336:
15337: get_scantronformat_file($cdom)
15338:
15339: $cdom - the course's domain (optional); if not supplied, uses
15340: domain for current $env{'request.course.id'}.
15341:
15342: Returns an array containing lines from the scantron format file for
15343: the domain of the course.
15344:
15345: If a url for a custom.tab file is listed in domain's configuration.db,
15346: lines are from this file.
15347:
15348: Otherwise, if a default.tab has been published in RES space by the
15349: domainconfig user, lines are from this file.
15350:
15351: Otherwise, fall back to getting lines from the legacy file on the
15352: local server: /home/httpd/lonTabs/default_scantronformat.tab
15353:
15354: =back
15355:
1.243 albertel 15356: =head2 Resource Subroutines
15357:
15358: =over 4
1.191 harris41 15359:
15360: =item *
15361:
1.243 albertel 15362: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15363:
15364: =item *
15365:
1.243 albertel 15366: repcopy($filename) : subscribes to the requested file, and attempts to
15367: replicate from the owning library server, Might return
1.607 raeburn 15368: 'unavailable', 'not_found', 'forbidden', 'ok', or
15369: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15370: resource. Expects the local filesystem pathname
15371: (/home/httpd/html/res/....)
15372:
15373: =back
15374:
15375: =head2 Resource Information
15376:
15377: =over 4
1.191 harris41 15378:
15379: =item *
15380:
1.1172.2.28 raeburn 15381: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15382: and returns the value of a variety of different possible values,
15383: $varname should be a request string, and the other parameters can be
15384: used to specify who and what one is asking about. Ordinarily, $cid
15385: does not need to be specified, as it is retrived from
15386: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15387: within lonuserstate::loadmap() when initializing a course, before
15388: $env{'request.course.id'} has been set, so it needs to be provided
15389: in that one case.
1.243 albertel 15390:
15391: Possible values for $varname are environment.lastname (or other item
15392: from the envirnment hash), user.name (or someother aspect about the
15393: user), resource.0.maxtries (or some other part and parameter of a
15394: resource)
1.204 albertel 15395:
15396: =item *
15397:
1.243 albertel 15398: directcondval($number) : get current value of a condition; reads from a state
15399: string
1.204 albertel 15400:
15401: =item *
15402:
1.243 albertel 15403: condval($condidx) : value of condition index based on state
1.204 albertel 15404:
15405: =item *
15406:
1.243 albertel 15407: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15408: resource's metadata, $what should be either a specific key, or either
15409: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15410: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15411:
15412: this function automatically caches all requests
1.191 harris41 15413:
15414: =item *
15415:
1.243 albertel 15416: metadata_query($query,$custom,$customshow) : make a metadata query against the
15417: network of library servers; returns file handle of where SQL and regex results
15418: will be stored for query
1.191 harris41 15419:
15420: =item *
15421:
1.1172.2.66 raeburn 15422: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15423: return symbolic list entry (all arguments optional).
15424:
15425: Args: filename is the filename (including path) for the file for which a symb
15426: is required; donotrecurse, if true will prevent calls to allowed() being made
15427: to check access status if more than one resource was found in the bighash
15428: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15429: a randompick); ignorecachednull, if true will prevent a symb of '' being
15430: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15431: cause possible symbs to be checked to determine if they are subject to content
15432: blocking, if so they will not be included as possible symbs; possibles is a
15433: ref to a hash, which, as a side effect, will be populated with all possible
15434: symbs (content blocking not tested).
15435:
1.243 albertel 15436: returns the data handle
1.191 harris41 15437:
15438: =item *
15439:
1.1172.2.17 raeburn 15440: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15441: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15442: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15443: on failure, user must be in a course, as it assumes the existence of
15444: the course initial hash, and uses $env('request.course.id'}. The third
15445: arg is an optional reference to a scalar. If this arg is passed in the
15446: call to symbverify, it will be set to 1 if the symb has been set to be
15447: encrypted; otherwise it will be null.
1.243 albertel 15448:
1.191 harris41 15449: =item *
15450:
1.243 albertel 15451: symbclean($symb) : removes versions numbers from a symb, returns the
15452: cleaned symb
1.191 harris41 15453:
15454: =item *
15455:
1.243 albertel 15456: is_on_map($uri) : checks if the $uri is somewhere on the current
15457: course map, user must be in a course for it to work.
1.191 harris41 15458:
15459: =item *
15460:
1.243 albertel 15461: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15462:
15463: =item *
15464:
1.243 albertel 15465: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15466: a random seed, all arguments are optional, if they aren't sent it uses the
15467: environment to derive them. Note: if symb isn't sent and it can't get one
15468: from &symbread it will use the current time as its return value
1.191 harris41 15469:
15470: =item *
15471:
1.243 albertel 15472: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15473: unfakeable, receipt
1.191 harris41 15474:
15475: =item *
15476:
1.620 albertel 15477: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15478:
15479: =item *
15480:
1.243 albertel 15481: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15482:
15483: =item *
15484:
1.243 albertel 15485: 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 15486:
15487: =item *
15488:
1.243 albertel 15489: 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 15490:
15491: =item *
15492:
1.243 albertel 15493: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15494:
15495: =item *
15496:
1.243 albertel 15497: devalidate($symb) : devalidate temporary spreadsheet calculations,
15498: forcing spreadsheet to reevaluate the resource scores next time.
15499:
1.1172.2.13 raeburn 15500: =item *
15501:
15502: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15503: when viewing in course context.
15504:
15505: input: six args -- filename (decluttered), course number, course domain,
15506: url, symb (if registered) and group (if this is a
15507: group item -- e.g., bulletin board, group page etc.).
15508:
15509: output: array of five scalars --
15510: $cfile -- url for file editing if editable on current server
15511: $home -- homeserver of resource (i.e., for author if published,
15512: or course if uploaded.).
15513: $switchserver -- 1 if server switch will be needed.
15514: $forceedit -- 1 if icon/link should be to go to edit mode
15515: $forceview -- 1 if icon/link should be to go to view mode
15516:
15517: =item *
15518:
15519: is_course_upload($file,$cnum,$cdom)
15520:
15521: Used in course context to determine if current file was uploaded to
15522: the course (i.e., would be found in /userfiles/docs on the course's
15523: homeserver.
15524:
15525: input: 3 args -- filename (decluttered), course number and course domain.
15526: output: boolean -- 1 if file was uploaded.
15527:
1.243 albertel 15528: =back
15529:
15530: =head2 Storing/Retreiving Data
15531:
15532: =over 4
1.191 harris41 15533:
15534: =item *
15535:
1.1172.2.64 raeburn 15536: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15537: permanently for this url; hashref needs to be given and should be a \%hashname;
15538: the remaining args aren't required and if they aren't passed or are '' they will
15539: be derived from the env (with the exception of $laststore, which is an
15540: optional arg used when a user's submission is stored in grading).
15541: $laststore is $version=$timestamp, where $version is the most recent version
15542: number retrieved for the corresponding $symb in the $namespace db file, and
15543: $timestamp is the timestamp for that transaction (UNIX time).
15544: $laststore is currently only passed when cstore() is called by
15545: structuretags::finalize_storage().
1.191 harris41 15546:
15547: =item *
15548:
1.1172.2.64 raeburn 15549: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15550: but uses critical subroutine
1.191 harris41 15551:
15552: =item *
15553:
1.243 albertel 15554: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15555: all args are optional
1.191 harris41 15556:
15557: =item *
15558:
1.717 albertel 15559: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15560: dumps the complete (or key matching regexp) namespace into a hash
15561: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15562: normally &store()ed into
15563:
15564: $range should be either an integer '100' (give me the first 100
15565: matching records)
15566: or be two integers sperated by a - with no spaces
15567: '30-50' (give me the 30th through the 50th matching
15568: records)
15569:
15570:
15571: =item *
15572:
1.1172.2.59 raeburn 15573: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15574: replaces a &store() version of data with a replacement set of data
15575: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15576: reference. If $tolog is true, the transaction is logged in the courselog
15577: with an action=PUTSTORE.
1.717 albertel 15578:
15579: =item *
15580:
1.243 albertel 15581: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15582: works very similar to store/cstore, but all data is stored in a
15583: temporary location and can be reset using tmpreset, $storehash should
15584: be a hash reference, returns nothing on success
1.191 harris41 15585:
15586: =item *
15587:
1.243 albertel 15588: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15589: similar to restore, but all data is stored in a temporary location and
15590: can be reset using tmpreset. Returns a hash of values on success,
15591: error string otherwise.
1.191 harris41 15592:
15593: =item *
15594:
1.243 albertel 15595: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15596: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15597:
15598: =item *
15599:
1.243 albertel 15600: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15601: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15602:
15603: =item *
15604:
1.243 albertel 15605: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15606: namesp ($udom and $uname are optional)
1.191 harris41 15607:
15608: =item *
15609:
1.702 albertel 15610: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15611: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15612: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15613:
1.702 albertel 15614: $range should be either an integer '100' (give me the first 100
15615: matching records)
15616: or be two integers sperated by a - with no spaces
15617: '30-50' (give me the 30th through the 50th matching
15618: records)
1.449 matthew 15619: =item *
15620:
15621: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15622: $store can be a scalar, an array reference, or if the amount to be
15623: incremented is > 1, a hash reference.
15624:
15625: ($udom and $uname are optional)
1.191 harris41 15626:
15627: =item *
15628:
1.243 albertel 15629: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15630: ($udom and $uname are optional)
1.191 harris41 15631:
15632: =item *
15633:
1.243 albertel 15634: cput($namespace,$storehash,$udom,$uname) : critical put
15635: ($udom and $uname are optional)
1.191 harris41 15636:
15637: =item *
15638:
1.748 albertel 15639: newput($namespace,$storehash,$udom,$uname) :
15640:
15641: Attempts to store the items in the $storehash, but only if they don't
15642: currently exist, if this succeeds you can be certain that you have
15643: successfully created a new key value pair in the $namespace db.
15644:
15645:
15646: Args:
15647: $namespace: name of database to store values to
15648: $storehash: hashref to store to the db
15649: $udom: (optional) domain of user containing the db
15650: $uname: (optional) name of user caontaining the db
15651:
15652: Returns:
15653: 'ok' -> succeeded in storing all keys of $storehash
15654: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15655: least <key> already existed in the db (other
15656: requested keys may also already exist)
1.967 bisitz 15657: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15658: 'con_lost' -> unable to contact request server
15659: 'refused' -> action was not allowed by remote machine
15660:
15661:
15662: =item *
15663:
1.243 albertel 15664: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15665: reference filled in from namesp (encrypts the return communication)
15666: ($udom and $uname are optional)
1.191 harris41 15667:
15668: =item *
15669:
1.243 albertel 15670: log($udom,$name,$home,$message) : write to permanent log for user; use
15671: critical subroutine
15672:
1.806 raeburn 15673: =item *
15674:
1.860 raeburn 15675: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15676: array reference filled in from namespace found in domain level on either
15677: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15678:
15679: =item *
15680:
1.860 raeburn 15681: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15682: domain level either on specified domain server ($uhome) or primary domain
15683: server ($udom and $uhome are optional)
1.806 raeburn 15684:
1.943 raeburn 15685: =item *
15686:
1.1172.2.35 raeburn 15687: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15688: for: authentication, language, quotas, timezone, date locale, and portal URL in
15689: the target domain.
15690:
15691: May also include additional key => value pairs for the following groups:
15692:
15693: =over
15694:
15695: =item
15696: disk quotas (MB allocated by default to portfolios and authoring spaces).
15697:
15698: =over
15699:
15700: =item defaultquota, authorquota
15701:
15702: =back
15703:
15704: =item
15705: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15706: portfolio for users).
15707:
15708: =over
15709:
15710: =item
15711: aboutme, blog, webdav, portfolio
15712:
15713: =back
15714:
15715: =item
15716: requestcourses: ability to request courses, and how requests are processed.
15717:
15718: =over
15719:
15720: =item
1.1172.2.37 raeburn 15721: official, unofficial, community, textbook
1.1172.2.35 raeburn 15722:
15723: =back
15724:
15725: =item
15726: inststatus: types of institutional affiliation, and order in which they are displayed.
15727:
15728: =over
15729:
15730: =item
1.1172.2.44 raeburn 15731: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15732:
15733: =back
15734:
15735: =item
15736: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15737: for course's uploaded content.
15738:
15739: =over
15740:
15741: =item
1.1172.2.68 raeburn 15742: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15743: communityquota, textbookquota
1.1172.2.35 raeburn 15744:
15745: =back
15746:
15747: =item
15748: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15749: on your servers.
15750:
15751: =over
15752:
15753: =item
15754: remotesessions, hostedsessions
15755:
15756: =back
15757:
15758: =back
15759:
15760: In cases where a domain coordinator has never used the "Set Domain Configuration"
15761: utility to create a configuration.db file on a domain's primary library server
15762: only the following domain defaults: auth_def, auth_arg_def, lang_def
15763: -- corresponding values are authentication type (internal, krb4, krb5,
15764: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15765: will be available. Values are retrieved from cache (if current), unless the
15766: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15767: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15768:
15769: Typical usage:
1.943 raeburn 15770:
1.1172.2.35 raeburn 15771: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15772:
1.243 albertel 15773: =back
15774:
15775: =head2 Network Status Functions
15776:
15777: =over 4
1.191 harris41 15778:
15779: =item *
15780:
1.1137 raeburn 15781: dirlist() : return directory list based on URI (first arg).
15782:
15783: Inputs: 1 required, 5 optional.
15784:
15785: =over
15786:
15787: =item
15788: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15789:
15790: =item
15791: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15792:
15793: =item
15794: $username - username of user/course to be listed. Extracted from $uri if absent.
15795:
15796: =item
15797: $getpropath - boolean: 1 if prepend path using &propath().
15798:
15799: =item
15800: $getuserdir - boolean: 1 if prepend path for "userfiles".
15801:
15802: =item
15803: $alternateRoot - path to prepend in place of path from $uri.
15804:
15805: =back
15806:
15807: Returns: Array of up to two items.
15808:
15809: =over
15810:
15811: a reference to an array of files/subdirectories
15812:
15813: =over
15814:
15815: Each element in the array of files/subdirectories is a & separated list of
15816: item name and the result of running stat on the item. If dirlist was requested
15817: for a file instead of a directory, the item name will be ''. For a directory
15818: listing, if the item is a metadata file, the element will end &N&M
15819: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15820: default copyright set (1).
15821:
15822: =back
15823:
15824: a scalar containing error condition (if encountered).
15825:
15826: =over
15827:
15828: =item
15829: no_host (no homeserver identified for $username:$domain).
15830:
15831: =item
15832: no_such_host (server contacted for listing not identified as valid host).
15833:
15834: =item
15835: con_lost (connection to remote server failed).
15836:
15837: =item
15838: refused (invalid $username:$domain received on lond side).
15839:
15840: =item
15841: no_such_dir (directory at specified path on lond side does not exist).
15842:
15843: =item
15844: empty (directory at specified path on lond side is empty).
15845:
15846: =over
15847:
15848: This is currently not encountered because the &ls3, &ls2,
15849: &ls (_handler) routines on the lond side do not filter out
15850: . and .. from a directory listing.
15851:
15852: =back
15853:
15854: =back
15855:
15856: =back
1.191 harris41 15857:
15858: =item *
15859:
1.243 albertel 15860: spareserver() : find server with least workload from spare.tab
15861:
1.986 foxr 15862:
15863: =item *
15864:
15865: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15866: if there is no corresponding loncapa host.
15867:
1.243 albertel 15868: =back
15869:
1.986 foxr 15870:
1.243 albertel 15871: =head2 Apache Request
15872:
15873: =over 4
1.191 harris41 15874:
15875: =item *
15876:
1.243 albertel 15877: ssi($url,%hash) : server side include, does a complete request cycle on url to
15878: localhost, posts hash
15879:
15880: =back
15881:
15882: =head2 Data to String to Data
15883:
15884: =over 4
1.191 harris41 15885:
15886: =item *
15887:
1.243 albertel 15888: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15889: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15890:
15891: =item *
15892:
1.243 albertel 15893: hashref2str($hashref) : convert a hashref into a string complete with
15894: escaping and '=' and '&' separators, supports elements that are
15895: arrayrefs and hashrefs
1.191 harris41 15896:
15897: =item *
15898:
1.243 albertel 15899: arrayref2str($arrayref) : convert an arrayref into a string complete
15900: with escaping and '&' separators, supports elements that are arrayrefs
15901: and hashrefs
1.191 harris41 15902:
15903: =item *
15904:
1.243 albertel 15905: str2hash($string) : convert string to hash using unescaping and
15906: splitting on '=' and '&', supports elements that are arrayrefs and
15907: hashrefs
1.191 harris41 15908:
15909: =item *
15910:
1.243 albertel 15911: str2array($string) : convert string to hash using unescaping and
15912: splitting on '&', supports elements that are arrayrefs and hashrefs
15913:
15914: =back
15915:
15916: =head2 Logging Routines
15917:
15918:
15919: These routines allow one to make log messages in the lonnet.log and
15920: lonnet.perm logfiles.
1.191 harris41 15921:
1.1119 foxr 15922: =over 4
15923:
1.191 harris41 15924: =item *
15925:
1.243 albertel 15926: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15927:
15928: =item *
15929:
1.243 albertel 15930: logthis() : append message to the normal lonnet.log file, it gets
15931: preiodically rolled over and deleted.
1.191 harris41 15932:
15933: =item *
15934:
1.243 albertel 15935: logperm() : append a permanent message to lonnet.perm.log, this log
15936: file never gets deleted by any automated portion of the system, only
15937: messages of critical importance should go in here.
15938:
1.1119 foxr 15939:
1.243 albertel 15940: =back
15941:
15942: =head2 General File Helper Routines
15943:
15944: =over 4
1.191 harris41 15945:
15946: =item *
15947:
1.481 raeburn 15948: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15949: (a) files in /uploaded
15950: (i) If a local copy of the file exists -
15951: compares modification date of local copy with last-modified date for
15952: definitive version stored on home server for course. If local copy is
15953: stale, requests a new version from the home server and stores it.
15954: If the original has been removed from the home server, then local copy
15955: is unlinked.
15956: (ii) If local copy does not exist -
15957: requests the file from the home server and stores it.
15958:
15959: If $caller is 'uploadrep':
15960: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15961: for request for files originally uploaded via DOCS.
15962: - returns 'ok' if fresh local copy now available, -1 otherwise.
15963:
15964: Otherwise:
15965: This indicates a call from the content generation phase of the request.
15966: - returns the entire contents of the file or -1.
15967:
15968: (b) files in /res
15969: - returns the entire contents of a file or -1;
15970: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15971:
1.712 albertel 15972:
15973: =item *
15974:
15975: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15976: reference
15977:
15978: returns either a stat() list of data about the file or an empty list
15979: if the file doesn't exist or couldn't find out about it (connection
15980: problems or user unknown)
15981:
1.191 harris41 15982: =item *
15983:
1.243 albertel 15984: filelocation($dir,$file) : returns file system location of a file
15985: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15986: directory that relative $file lookups are to looked in ($dir of /a/dir
15987: and a file of ../bob will become /a/bob)
1.191 harris41 15988:
15989: =item *
15990:
15991: hreflocation($dir,$file) : returns file system location or a URL; same as
15992: filelocation except for hrefs
15993:
15994: =item *
15995:
1.1172.2.49 raeburn 15996: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15997: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15998:
1.243 albertel 15999: =back
16000:
1.608 albertel 16001: =head2 Usererfile file routines (/uploaded*)
16002:
16003: =over 4
16004:
16005: =item *
16006:
16007: userfileupload(): main rotine for putting a file in a user or course's
16008: filespace, arguments are,
16009:
1.620 albertel 16010: formname - required - this is the name of the element in $env where the
1.608 albertel 16011: filename, and the contents of the file to create/modifed exist
1.620 albertel 16012: the filename is in $env{'form.'.$formname.'.filename'} and the
16013: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16014: context - if coursedoc, store the file in the course of the active role
16015: of the current user;
16016: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16017: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16018: subdir - required - subdirectory to put the file in under ../userfiles/
16019: if undefined, it will be placed in "unknown"
16020:
16021: (This routine calls clean_filename() to remove any dangerous
16022: characters from the filename, and then calls finuserfileupload() to
16023: complete the transaction)
16024:
16025: returns either the url of the uploaded file (/uploaded/....) if successful
16026: and /adm/notfound.html if unsuccessful
16027:
16028: =item *
16029:
16030: clean_filename(): routine for cleaing a filename up for storage in
16031: userfile space, argument is:
16032:
16033: filename - proposed filename
16034:
16035: returns: the new clean filename
16036:
16037: =item *
16038:
1.1090 raeburn 16039: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16040: userspace, probably shouldn't be called directly
16041:
16042: docuname: username or courseid of destination for the file
16043: docudom: domain of user/course of destination for the file
16044: formname: same as for userfileupload()
1.1090 raeburn 16045: fname: filename (including subdirectories) for the file
16046: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16047: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16048: allfiles: reference to hash used to store objects found by parser
16049: codebase: reference to hash used for codebases of java objects found by parser
16050: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16051: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16052: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16053: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16054: context: if 'overwrite', will move the uploaded file from its temporary location to
16055: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16056: mimetype: reference to scalar to accommodate mime type determined
16057: from File::MMagic if $parser = parse.
1.608 albertel 16058:
16059: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16060: and /adm/notfound.html if unsuccessful (or an error message if context
16061: was 'overwrite').
16062:
1.608 albertel 16063:
16064: =item *
16065:
16066: renameuserfile(): renames an existing userfile to a new name
16067:
16068: Args:
16069: docuname: username or courseid of destination for the file
16070: docudom: domain of user/course of destination for the file
16071: old: current file name (including any subdirs under userfiles)
16072: new: desired file name (including any subdirs under userfiles)
16073:
16074: =item *
16075:
16076: mkdiruserfile(): creates a directory is a userfiles dir
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: dir: dir to create (including any subdirs under userfiles)
16082:
16083: =item *
16084:
16085: removeuserfile(): removes a file that exists in userfiles
16086:
16087: Args:
16088: docuname: username or courseid of destination for the file
16089: docudom: domain of user/course of destination for the file
16090: fname: filname to delete (including any subdirs under userfiles)
16091:
16092: =item *
16093:
16094: removeuploadedurl(): convience function for removeuserfile()
16095:
16096: Args:
16097: url: a full /uploaded/... url to delete
16098:
1.747 albertel 16099: =item *
16100:
16101: get_portfile_permissions():
16102: Args:
16103: domain: domain of user or course contain the portfolio files
16104: user: name of user or num of course contain the portfolio files
16105: Returns:
16106: hashref of a dump of the proper file_permissions.db
16107:
16108:
16109: =item *
16110:
16111: get_access_controls():
16112:
16113: Args:
16114: current_permissions: the hash ref returned from get_portfile_permissions()
16115: group: (optional) the group you want the files associated with
16116: file: (optional) the file you want access info on
16117:
16118: Returns:
1.749 raeburn 16119: a hash (keys are file names) of hashes containing
16120: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16121: values are XML containing access control settings (see below)
1.747 albertel 16122:
16123: Internal notes:
16124:
1.749 raeburn 16125: access controls are stored in file_permissions.db as key=value pairs.
16126: key -> path to file/file_name\0uniqueID:scope_end_start
16127: where scope -> public,guest,course,group,domains or users.
16128: end -> UNIX time for end of access (0 -> no end date)
16129: start -> UNIX time for start of access
16130:
16131: value -> XML description of access control
16132: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16133: <start></start>
16134: <end></end>
16135:
16136: <password></password> for scope type = guest
16137:
16138: <domain></domain> for scope type = course or group
16139: <number></number>
16140: <roles id="">
16141: <role></role>
16142: <access></access>
16143: <section></section>
16144: <group></group>
16145: </roles>
16146:
16147: <dom></dom> for scope type = domains
16148:
16149: <users> for scope type = users
16150: <user>
16151: <uname></uname>
16152: <udom></udom>
16153: </user>
16154: </users>
16155: </scope>
16156:
16157: Access data is also aggregated for each file in an additional key=value pair:
16158: key -> path to file/file_name\0accesscontrol
16159: value -> reference to hash
16160: hash contains key = value pairs
16161: where key = uniqueID:scope_end_start
16162: value = UNIX time record was last updated
16163:
16164: Used to improve speed of look-ups of access controls for each file.
16165:
16166: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16167:
1.1172.2.13 raeburn 16168: =item *
16169:
1.749 raeburn 16170: modify_access_controls():
16171:
16172: Modifies access controls for a portfolio file
16173: Args
16174: 1. file name
16175: 2. reference to hash of required changes,
16176: 3. domain
16177: 4. username
16178: where domain,username are the domain of the portfolio owner
16179: (either a user or a course)
16180:
16181: Returns:
16182: 1. result of additions or updates ('ok' or 'error', with error message).
16183: 2. result of deletions ('ok' or 'error', with error message).
16184: 3. reference to hash of any new or updated access controls.
16185: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16186: key = integer (inbound ID)
1.1172.2.13 raeburn 16187: value = uniqueID
16188:
16189: =item *
16190:
16191: get_timebased_id():
16192:
16193: Attempts to get a unique timestamp-based suffix for use with items added to a
16194: course via the Course Editor (e.g., folders, composite pages,
16195: group bulletin boards).
16196:
16197: Args: (first three required; six others optional)
16198:
16199: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16200: docssequence, or name of group
16201:
16202: 2. keyid (alphanumeric): name of temporary locking key in hash,
16203: e.g., num, boardids
16204:
16205: 3. namespace: name of gdbm file used to store suffixes already assigned;
16206: file will be named nohist_namespace.db
16207:
16208: 4. cdom: domain of course; default is current course domain from %env
16209:
16210: 5. cnum: course number; default is current course number from %env
16211:
16212: 6. idtype: set to concat if an additional digit is to be appended to the
16213: unix timestamp to form the suffix, if the plain timestamp is already
16214: in use. Default is to not do this, but simply increment the unix
16215: timestamp by 1 until a unique key is obtained.
16216:
16217: 7. who: holder of locking key; defaults to user:domain for user.
16218:
16219: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16220: retrying); default is 3.
16221:
16222: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16223:
16224: Returns:
16225:
16226: 1. suffix obtained (numeric)
16227:
16228: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16229:
16230: 3. error: contains (localized) error message if an error occurred.
16231:
1.747 albertel 16232:
1.608 albertel 16233: =back
16234:
1.243 albertel 16235: =head2 HTTP Helper Routines
16236:
16237: =over 4
16238:
1.191 harris41 16239: =item *
16240:
16241: escape() : unpack non-word characters into CGI-compatible hex codes
16242:
16243: =item *
16244:
16245: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16246:
1.243 albertel 16247: =back
16248:
16249: =head1 PRIVATE SUBROUTINES
16250:
16251: =head2 Underlying communication routines (Shouldn't call)
16252:
16253: =over 4
16254:
16255: =item *
16256:
16257: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16258:
16259: =item *
16260:
16261: reply() : uses subreply to send a message to remote machine, logs all failures
16262:
16263: =item *
16264:
16265: critical() : passes a critical message to another server; if cannot
16266: get through then place message in connection buffer directory and
16267: returns con_delayed, if incapable of saving message, returns
16268: con_failed
16269:
16270: =item *
16271:
16272: reconlonc() : tries to reconnect lonc client processes.
16273:
16274: =back
16275:
16276: =head2 Resource Access Logging
16277:
16278: =over 4
16279:
16280: =item *
16281:
16282: flushcourselogs() : flush (save) buffer logs and access logs
16283:
16284: =item *
16285:
16286: courselog($what) : save message for course in hash
16287:
16288: =item *
16289:
16290: courseacclog($what) : save message for course using &courselog(). Perform
16291: special processing for specific resource types (problems, exams, quizzes, etc).
16292:
1.191 harris41 16293: =item *
16294:
16295: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16296: as a PerlChildExitHandler
1.243 albertel 16297:
16298: =back
16299:
16300: =head2 Other
16301:
16302: =over 4
16303:
16304: =item *
16305:
16306: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16307:
16308: =back
16309:
16310: =cut
1.877 foxr 16311:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>