Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.150
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.150! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.149 2024/07/02 21:40:21 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.1172.2.142 raeburn 98: use Net::CIDR;
99: use Sys::Hostname::FQDN();
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 103: use LONCAPA::Lond;
1.1172.2.110 raeburn 104: use LONCAPA::transliterate;
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1172.2.79 raeburn 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.1172.2.9 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1172.2.9 raeburn 119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1172.2.13 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134 raeburn 130: my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
1.1172.2.134 raeburn 136: 'exe_ip' => $ip,
1.1172.2.9 raeburn 137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 150: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.1172.2.96 raeburn 162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.1172.2.96 raeburn 175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.890 albertel 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.993 raeburn 233: sub get_server_loncaparev {
1.1073 raeburn 234: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 235: if (defined($lonhost)) {
236: if (!defined(&hostname($lonhost))) {
237: undef($lonhost);
238: }
239: }
240: if (!defined($lonhost)) {
241: if (defined(&domain($dom,'primary'))) {
242: $lonhost=&domain($dom,'primary');
243: if ($lonhost eq 'no_host') {
244: undef($lonhost);
245: }
246: }
247: }
248: if (defined($lonhost)) {
1.1073 raeburn 249: my $cachetime = 12*3600;
250: if (!$ignore_cache) {
251: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
252: if (defined($cached)) {
253: return $loncaparev;
254: }
255: }
256: my ($answer,$loncaparev);
257: my @ids=¤t_machine_ids();
258: if (grep(/^\Q$lonhost\E$/,@ids)) {
259: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 260: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 261: $loncaparev = $1;
262: }
263: } else {
264: $answer = &reply('serverloncaparev',$lonhost);
265: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
266: if ($caller eq 'loncron') {
267: my $ua=new LWP::UserAgent;
1.1082 raeburn 268: $ua->timeout(4);
1.1172.2.120 raeburn 269: my $hostname = &hostname($lonhost);
1.1073 raeburn 270: my $protocol = $protocol{$lonhost};
271: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 272: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 273: my $request=new HTTP::Request('GET',$url);
274: my $response=$ua->request($request);
275: unless ($response->is_error()) {
276: my $content = $response->content;
1.1081 raeburn 277: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 278: $loncaparev = $1;
279: }
280: }
281: } else {
282: $loncaparev = $loncaparevs{$lonhost};
283: }
1.1081 raeburn 284: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 285: $loncaparev = $1;
286: }
1.993 raeburn 287: }
1.1073 raeburn 288: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 289: }
290: }
291:
1.1074 raeburn 292: sub get_server_homeID {
293: my ($hostname,$ignore_cache,$caller) = @_;
294: unless ($ignore_cache) {
295: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
296: if (defined($cached)) {
297: return $serverhomeID;
298: }
299: }
300: my $cachetime = 12*3600;
301: my $serverhomeID;
302: if ($caller eq 'loncron') {
303: my @machine_ids = &machine_ids($hostname);
304: foreach my $id (@machine_ids) {
305: my $response = &reply('serverhomeID',$id);
306: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
307: $serverhomeID = $response;
308: last;
309: }
310: }
311: if ($serverhomeID eq '') {
312: $serverhomeID = $machine_ids[-1];
313: }
314: } else {
315: $serverhomeID = $serverhomeIDs{$hostname};
316: }
317: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
318: }
319:
1.1121 raeburn 320: sub get_remote_globals {
321: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 322: my ($result,%returnhash,%whatneeded);
323: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 324: foreach my $what (sort(keys(%{$whathash}))) {
325: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 326: my ($response,$cached);
1.1121 raeburn 327: unless ($ignore_cache) {
1.1125 raeburn 328: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 329: }
330: if (defined($cached)) {
1.1125 raeburn 331: $returnhash{$what} = $response;
1.1121 raeburn 332: } else {
1.1125 raeburn 333: $whatneeded{$what} = 1;
1.1121 raeburn 334: }
335: }
1.1125 raeburn 336: if (keys(%whatneeded) == 0) {
337: $result = 'ok';
338: } else {
1.1121 raeburn 339: my $requested = &freeze_escape(\%whatneeded);
340: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 341: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
342: ($rep eq 'unknown_cmd')) {
343: $result = $rep;
344: } else {
345: $result = 'ok';
1.1121 raeburn 346: my @pairs=split(/\&/,$rep);
1.1125 raeburn 347: foreach my $item (@pairs) {
348: my ($key,$value)=split(/=/,$item,2);
349: my $what = &unescape($key);
350: my $hashid = $lonhost.'-'.$what;
351: $returnhash{$what}=&thaw_unescape($value);
352: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 353: }
354: }
355: }
356: }
1.1125 raeburn 357: return ($result,\%returnhash);
1.1121 raeburn 358: }
359:
1.1124 raeburn 360: sub remote_devalidate_cache {
1.1172.2.35 raeburn 361: my ($lonhost,$cachekeys) = @_;
362: my $items;
363: return unless (ref($cachekeys) eq 'ARRAY');
364: my $cachestr = join('&',@{$cachekeys});
365: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 366: }
367:
1.1 albertel 368: # -------------------------------------------------- Non-critical communication
369: sub subreply {
370: my ($cmd,$server)=@_;
1.838 albertel 371: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 372: #
373: # With loncnew process trimming, there's a timing hole between lonc server
374: # process exit and the master server picking up the listen on the AF_UNIX
375: # socket. In that time interval, a lock file will exist:
376:
377: my $lockfile=$peerfile.".lock";
378: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 379: sleep(0.1);
1.549 foxr 380: }
381: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 382: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 383: #
1.550 foxr 384: # We'll give the connection a few tries before abandoning it. If
385: # connection is not possible, we'll con_lost back to the client.
386: #
387: my $client;
388: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
389: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
390: Type => SOCK_STREAM,
391: Timeout => 10);
1.869 albertel 392: if ($client) {
1.550 foxr 393: last; # Connected!
1.850 albertel 394: } else {
1.853 albertel 395: &create_connection(&hostname($server),$server);
1.550 foxr 396: }
1.1172.2.79 raeburn 397: sleep(0.1); # Try again later if failed connection.
1.550 foxr 398: }
399: my $answer;
400: if ($client) {
1.704 albertel 401: print $client "sethost:$server:$cmd\n";
1.550 foxr 402: $answer=<$client>;
403: if (!$answer) { $answer="con_lost"; }
404: chomp($answer);
405: } else {
406: $answer = 'con_lost'; # Failed connection.
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: sub reply {
412: my ($cmd,$server)=@_;
1.838 albertel 413: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 414: my $answer=subreply($cmd,$server);
1.65 www 415: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 416: my $logged = $cmd;
417: if ($cmd =~ /^encrypt:([^:]+):/) {
418: my $subcmd = $1;
419: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
420: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
421: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
422: (undef,undef,my @rest) = split(/:/,$cmd);
423: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
424: splice(@rest,2,1,'Hidden');
425: } elsif ($subcmd eq 'passwd') {
426: splice(@rest,2,2,('Hidden','Hidden'));
427: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
428: ($subcmd eq 'autoexportgrades')) {
429: splice(@rest,3,1,'Hidden');
430: }
431: $logged = join(':',('encrypt:'.$subcmd,@rest));
432: }
433: }
434: &logthis("<font color=\"blue\">WARNING:".
435: " $logged to $server returned $answer</font>");
1.12 www 436: }
1.1 albertel 437: return $answer;
438: }
439:
440: # ----------------------------------------------------------- Send USR1 to lonc
441:
442: sub reconlonc {
1.891 albertel 443: my ($lonid) = @_;
444: if ($lonid) {
1.1172.2.72 raeburn 445: my $hostname = &hostname($lonid);
1.891 albertel 446: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
447: if ($hostname && -e $peerfile) {
448: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
449: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
450: Type => SOCK_STREAM,
451: Timeout => 10);
452: if ($client) {
453: print $client ("reset_retries\n");
454: my $answer=<$client>;
455: #reset just this one.
456: }
457: }
458: return;
459: }
460:
1.836 www 461: &logthis("Trying to reconnect lonc");
1.1 albertel 462: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 463: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 464: my $loncpid=<$fh>;
465: chomp($loncpid);
466: if (kill 0 => $loncpid) {
467: &logthis("lonc at pid $loncpid responding, sending USR1");
468: kill USR1 => $loncpid;
469: sleep 1;
1.836 www 470: } else {
1.12 www 471: &logthis(
1.672 albertel 472: "<font color=\"blue\">WARNING:".
1.12 www 473: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 474: }
475: } else {
1.836 www 476: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 477: }
478: }
479:
480: # ------------------------------------------------------ Critical communication
1.12 www 481:
1.1 albertel 482: sub critical {
483: my ($cmd,$server)=@_;
1.838 albertel 484: unless (&hostname($server)) {
1.672 albertel 485: &logthis("<font color=\"blue\">WARNING:".
1.89 www 486: " Critical message to unknown server ($server)</font>");
487: return 'no_such_host';
488: }
1.1 albertel 489: my $answer=reply($cmd,$server);
490: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 491: &reconlonc($server);
1.589 albertel 492: my $answer=reply($cmd,$server);
1.1 albertel 493: if ($answer eq 'con_lost') {
494: my $now=time;
495: my $middlename=$cmd;
1.5 www 496: $middlename=substr($middlename,0,16);
1.1 albertel 497: $middlename=~s/\W//g;
498: my $dfilename=
1.305 www 499: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
500: $dumpcount++;
1.1 albertel 501: {
1.448 albertel 502: my $dfh;
1.1172.2.96 raeburn 503: if (open($dfh,">",$dfilename)) {
1.448 albertel 504: print $dfh "$cmd\n";
505: close($dfh);
506: }
1.1 albertel 507: }
1.1172.2.79 raeburn 508: sleep 1;
1.1 albertel 509: my $wcmd='';
510: {
1.448 albertel 511: my $dfh;
1.1172.2.96 raeburn 512: if (open($dfh,"<",$dfilename)) {
1.448 albertel 513: $wcmd=<$dfh>;
514: close($dfh);
515: }
1.1 albertel 516: }
517: chomp($wcmd);
1.7 www 518: if ($wcmd eq $cmd) {
1.672 albertel 519: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 520: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 521: &logperm("D:$server:$cmd");
522: return 'con_delayed';
523: } else {
1.672 albertel 524: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 525: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 526: &logperm("F:$server:$cmd");
527: return 'con_failed';
528: }
529: }
530: }
531: return $answer;
1.405 albertel 532: }
533:
1.755 albertel 534: # ------------------------------------------- check if return value is an error
535:
536: sub error {
537: my ($result) = @_;
1.756 albertel 538: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 539: if ($2 == 2) { return undef; }
540: return $1;
541: }
542: return undef;
543: }
544:
1.783 albertel 545: sub convert_and_load_session_env {
546: my ($lonidsdir,$handle)=@_;
547: my @profile;
548: {
1.917 albertel 549: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
550: if (!$opened) {
1.915 albertel 551: return 0;
552: }
1.783 albertel 553: flock($idf,LOCK_SH);
554: @profile=<$idf>;
555: close($idf);
556: }
557: my %temp_env;
558: foreach my $line (@profile) {
1.786 albertel 559: if ($line !~ m/=/) {
560: return 0;
561: }
1.783 albertel 562: chomp($line);
563: my ($envname,$envvalue)=split(/=/,$line,2);
564: $temp_env{&unescape($envname)} = &unescape($envvalue);
565: }
566: unlink("$lonidsdir/$handle.id");
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
568: 0640)) {
569: %disk_env = %temp_env;
570: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
571: untie(%disk_env);
572: }
1.786 albertel 573: return 1;
1.783 albertel 574: }
575:
1.374 www 576: # ------------------------------------------- Transfer profile into environment
1.780 albertel 577: my $env_loaded;
578: sub transfer_profile_to_env {
1.788 albertel 579: my ($lonidsdir,$handle,$force_transfer) = @_;
580: if (!$force_transfer && $env_loaded) { return; }
1.374 www 581:
1.720 albertel 582: if (!defined($lonidsdir)) {
583: $lonidsdir = $perlvar{'lonIDsDir'};
584: }
585: if (!defined($handle)) {
586: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
587: }
588:
1.786 albertel 589: my $convert;
590: {
1.917 albertel 591: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
592: if (!$opened) {
1.915 albertel 593: return;
594: }
1.786 albertel 595: flock($idf,LOCK_SH);
596: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
597: &GDBM_READER(),0640)) {
598: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
599: untie(%disk_env);
600: } else {
601: $convert = 1;
602: }
603: }
604: if ($convert) {
605: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
606: &logthis("Failed to load session, or convert session.");
607: }
1.374 www 608: }
1.783 albertel 609:
1.786 albertel 610: my %remove;
1.783 albertel 611: while ( my $envname = each(%env) ) {
1.433 matthew 612: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
613: if ($time < time-300) {
1.783 albertel 614: $remove{$key}++;
1.433 matthew 615: }
616: }
617: }
1.783 albertel 618:
1.619 albertel 619: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 620: $env_loaded=1;
1.783 albertel 621: foreach my $expired_key (keys(%remove)) {
1.433 matthew 622: &delenv($expired_key);
1.374 www 623: }
1.1 albertel 624: }
625:
1.916 albertel 626: # ---------------------------------------------------- Check for valid session
627: sub check_for_valid_session {
1.1172.2.96 raeburn 628: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 629: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 630: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 631: if ($name eq 'lonDAV') {
632: $lonidsdir=$r->dir_config('lonDAVsessDir');
633: } else {
634: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 635: if ($name eq '') {
636: $name = 'lonID';
637: }
638: }
639: if ($name eq 'lonID') {
640: $secure = 'lonSID';
641: $linkname = 'lonLinkID';
642: $pubname = 'lonPubID';
643: if (exists($cookies{$secure})) {
644: $lonid=$cookies{$secure};
645: } elsif (exists($cookies{$name})) {
646: $lonid=$cookies{$name};
647: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
648: $lonid=$cookies{$linkname};
649: } elsif (exists($cookies{$pubname})) {
650: $lonid=$cookies{$pubname};
651: }
652: } else {
653: $lonid=$cookies{$name};
654: }
655: return undef if (!$lonid);
656:
657: my $handle=&LONCAPA::clean_handle($lonid->value);
658: if (-l "$lonidsdir/$handle.id") {
659: my $link = readlink("$lonidsdir/$handle.id");
660: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
661: $handle = $1;
662: }
1.1155 raeburn 663: }
1.1172.2.96 raeburn 664: if (!-e "$lonidsdir/$handle.id") {
665: if ((ref($domref)) && ($name eq 'lonID') &&
666: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
667: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
668: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
669: $$domref = $possudom;
670: }
671: }
672: return undef;
673: }
1.916 albertel 674:
1.917 albertel 675: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
676: return undef if (!$opened);
1.916 albertel 677:
678: flock($idf,LOCK_SH);
679: my %disk_env;
680: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
681: &GDBM_READER(),0640)) {
682: return undef;
683: }
684:
685: if (!defined($disk_env{'user.name'})
686: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 687: untie(%disk_env);
1.916 albertel 688: return undef;
689: }
1.1172.2.18 raeburn 690:
1.1172.2.36 raeburn 691: if (ref($userhashref) eq 'HASH') {
692: $userhashref->{'name'} = $disk_env{'user.name'};
693: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142 raeburn 694: if ($disk_env{'request.role'}) {
695: $userhashref->{'role'} = $disk_env{'request.role'};
696: }
1.1172.2.18 raeburn 697: }
1.1172.2.107 raeburn 698: untie(%disk_env);
1.1172.2.18 raeburn 699:
1.916 albertel 700: return $handle;
701: }
702:
1.830 albertel 703: sub timed_flock {
704: my ($file,$lock_type) = @_;
705: my $failed=0;
706: eval {
707: local $SIG{__DIE__}='DEFAULT';
708: local $SIG{ALRM}=sub {
709: $failed=1;
710: die("failed lock");
711: };
712: alarm(13);
713: flock($file,$lock_type);
714: alarm(0);
715: };
716: if ($failed) {
717: return undef;
718: } else {
719: return 1;
720: }
721: }
722:
1.1172.2.107 raeburn 723: sub get_sessionfile_vars {
724: my ($handle,$lonidsdir,$storearr) = @_;
725: my %returnhash;
726: unless (ref($storearr) eq 'ARRAY') {
727: return %returnhash;
728: }
729: if (-l "$lonidsdir/$handle.id") {
730: my $link = readlink("$lonidsdir/$handle.id");
731: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
732: $handle = $1;
733: }
734: }
735: if ((-e "$lonidsdir/$handle.id") &&
736: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
737: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
738: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
739: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
740: flock($idf,LOCK_SH);
741: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
742: &GDBM_READER(),0640)) {
743: foreach my $item (@{$storearr}) {
744: $returnhash{$item} = $disk_env{$item};
745: }
746: untie(%disk_env);
747: }
748: }
749: }
750: }
751: return %returnhash;
752: }
753:
1.5 www 754: # ---------------------------------------------------------- Append Environment
755:
756: sub appenv {
1.949 raeburn 757: my ($newenv,$roles) = @_;
758: if (ref($newenv) eq 'HASH') {
759: foreach my $key (keys(%{$newenv})) {
760: my $refused = 0;
761: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
762: $refused = 1;
763: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 764: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 765: if (grep(/^\Q$role\E$/,@{$roles})) {
766: $refused = 0;
767: }
768: }
769: }
770: if ($refused) {
771: &logthis("<font color=\"blue\">WARNING: ".
772: "Attempt to modify environment ".$key." to ".$newenv->{$key}
773: .'</font>');
774: delete($newenv->{$key});
775: } else {
776: $env{$key}=$newenv->{$key};
777: }
778: }
1.1172.2.96 raeburn 779: my $lonids = $perlvar{'lonIDsDir'};
780: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
781: my $opened = open(my $env_file,'+<',$env{'user.environment'});
782: if ($opened
783: && &timed_flock($env_file,LOCK_EX)
784: &&
785: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
786: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
787: while (my ($key,$value) = each(%{$newenv})) {
788: $disk_env{$key} = $value;
789: }
790: untie(%disk_env);
791: }
1.35 www 792: }
1.191 harris41 793: }
1.56 www 794: return 'ok';
795: }
796: # ----------------------------------------------------- Delete from Environment
797:
798: sub delenv {
1.1104 raeburn 799: my ($delthis,$regexp,$roles) = @_;
800: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
801: my $refused = 1;
802: if (ref($roles) eq 'ARRAY') {
803: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
804: if (grep(/^\Q$role\E$/,@{$roles})) {
805: $refused = 0;
806: }
807: }
808: if ($refused) {
809: &logthis("<font color=\"blue\">WARNING: ".
810: "Attempt to delete from environment ".$delthis);
811: return 'error';
812: }
1.56 www 813: }
1.917 albertel 814: my $opened = open(my $env_file,'+<',$env{'user.environment'});
815: if ($opened
1.915 albertel 816: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 817: &&
818: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
819: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 820: foreach my $key (keys(%disk_env)) {
1.987 raeburn 821: if ($regexp) {
822: if ($key=~/^$delthis/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: } else {
827: if ($key=~/^\Q$delthis\E/) {
828: delete($env{$key});
829: delete($disk_env{$key});
830: }
831: }
1.448 albertel 832: }
1.783 albertel 833: untie(%disk_env);
1.5 www 834: }
835: return 'ok';
1.369 albertel 836: }
837:
1.790 albertel 838: sub get_env_multiple {
839: my ($name) = @_;
840: my @values;
841: if (defined($env{$name})) {
842: # exists is it an array
843: if (ref($env{$name})) {
844: @values=@{ $env{$name} };
845: } else {
846: $values[0]=$env{$name};
847: }
848: }
849: return(@values);
850: }
851:
1.958 www 852: # ------------------------------------------------------------------- Locking
853:
854: sub set_lock {
855: my ($text)=@_;
856: $locknum++;
857: my $id=$$.'-'.$locknum;
858: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
859: 'session.lock.'.$id => $text});
860: return $id;
861: }
862:
863: sub get_locks {
864: my $num=0;
865: my %texts=();
866: foreach my $lock (split(/\,/,$env{'session.locks'})) {
867: if ($lock=~/\w/) {
868: $num++;
869: $texts{$lock}=$env{'session.lock.'.$lock};
870: }
871: }
872: return ($num,%texts);
873: }
874:
875: sub remove_lock {
876: my ($id)=@_;
877: my $newlocks='';
878: foreach my $lock (split(/\,/,$env{'session.locks'})) {
879: if (($lock=~/\w/) && ($lock ne $id)) {
880: $newlocks.=','.$lock;
881: }
882: }
883: &appenv({'session.locks' => $newlocks});
884: &delenv('session.lock.'.$id);
885: }
886:
887: sub remove_all_locks {
888: my $activelocks=$env{'session.locks'};
889: foreach my $lock (split(/\,/,$env{'session.locks'})) {
890: if ($lock=~/\w/) {
891: &remove_lock($lock);
892: }
893: }
894: }
895:
896:
1.369 albertel 897: # ------------------------------------------ Find out current server userload
898: sub userload {
899: my $numusers=0;
900: {
901: opendir(LONIDS,$perlvar{'lonIDsDir'});
902: my $filename;
903: my $curtime=time;
904: while ($filename=readdir(LONIDS)) {
1.925 albertel 905: next if ($filename eq '.' || $filename eq '..');
906: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 907: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 908: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 909: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 910: }
911: closedir(LONIDS);
912: }
913: my $userloadpercent=0;
914: my $maxuserload=$perlvar{'lonUserLoadLim'};
915: if ($maxuserload) {
1.371 albertel 916: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 917: }
1.372 albertel 918: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 919: return $userloadpercent;
1.283 www 920: }
921:
1.1 albertel 922: # ------------------------------ Find server with least workload from spare.tab
1.11 www 923:
1.1 albertel 924: sub spareserver {
1.1172.2.142 raeburn 925: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 926: my $spare_server;
1.370 albertel 927: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 928: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
929: : $userloadpercent;
1.1083 raeburn 930: my ($uint_dom,$remotesessions);
931: if (($udom ne '') && (&domain($udom) ne '')) {
932: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
933: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
934: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
935: $remotesessions = $udomdefaults{'remotesessions'};
936: }
1.1123 raeburn 937: my $spareshash = &this_host_spares($udom);
938: if (ref($spareshash) eq 'HASH') {
939: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
940: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 941: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
942: $try_server));
1.1123 raeburn 943: ($spare_server, $lowest_load) =
944: &compare_server_load($try_server, $spare_server, $lowest_load);
945: }
1.1083 raeburn 946: }
1.784 albertel 947:
1.1123 raeburn 948: my $found_server = ($spare_server ne '' && $lowest_load < 100);
949:
950: if (!$found_server) {
951: if (ref($spareshash->{'default'}) eq 'ARRAY') {
952: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 953: next unless (&spare_can_host($udom,$uint_dom,
954: $remotesessions,$try_server));
1.1123 raeburn 955: ($spare_server, $lowest_load) =
956: &compare_server_load($try_server, $spare_server, $lowest_load);
957: }
958: }
959: }
1.784 albertel 960: }
961:
962: if (!$want_server_name) {
1.1001 raeburn 963: if (defined($spare_server)) {
964: my $hostname = &hostname($spare_server);
1.1083 raeburn 965: if (defined($hostname)) {
1.1172.2.120 raeburn 966: my $protocol = 'http';
967: if ($protocol{$spare_server} eq 'https') {
968: $protocol = $protocol{$spare_server};
969: }
1.1172.2.142 raeburn 970: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
971: $hostname = $alias if ($alias ne '');
1.1001 raeburn 972: $spare_server = $protocol.'://'.$hostname;
973: }
974: }
1.784 albertel 975: }
976: return $spare_server;
977: }
978:
979: sub compare_server_load {
1.1172.2.41 raeburn 980: my ($try_server, $spare_server, $lowest_load, $required) = @_;
981:
982: if ($required) {
983: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
984: my $remoterev = &get_server_loncaparev(undef,$try_server);
985: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
986: if (($major eq '' && $minor eq '') ||
987: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
988: return ($spare_server,$lowest_load);
989: }
990: }
1.784 albertel 991:
992: my $loadans = &reply('load', $try_server);
993: my $userloadans = &reply('userload',$try_server);
994:
995: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 996: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 997: }
998:
999: my $load;
1000: if ($loadans =~ /\d/) {
1001: if ($userloadans =~ /\d/) {
1002: #both are numbers, pick the bigger one
1003: $load = ($loadans > $userloadans) ? $loadans
1004: : $userloadans;
1.411 albertel 1005: } else {
1.784 albertel 1006: $load = $loadans;
1.411 albertel 1007: }
1.784 albertel 1008: } else {
1009: $load = $userloadans;
1010: }
1011:
1012: if (($load =~ /\d/) && ($load < $lowest_load)) {
1013: $spare_server = $try_server;
1014: $lowest_load = $load;
1.370 albertel 1015: }
1.784 albertel 1016: return ($spare_server,$lowest_load);
1.202 matthew 1017: }
1.914 albertel 1018:
1019: # --------------------------- ask offload servers if user already has a session
1020: sub find_existing_session {
1021: my ($udom,$uname) = @_;
1.1123 raeburn 1022: my $spareshash = &this_host_spares($udom);
1023: if (ref($spareshash) eq 'HASH') {
1024: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1025: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1026: return $try_server if (&has_user_session($try_server, $udom, $uname));
1027: }
1028: }
1029: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1030: foreach my $try_server (@{ $spareshash->{'default'} }) {
1031: return $try_server if (&has_user_session($try_server, $udom, $uname));
1032: }
1033: }
1.914 albertel 1034: }
1035: return;
1036: }
1037:
1.1172.2.107 raeburn 1038: # check if user's browser sent load balancer cookie and server still has session
1039: # and is not overloaded.
1040: sub check_for_balancer_cookie {
1041: my ($r,$update_mtime) = @_;
1042: my ($otherserver,$cookie);
1043: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1044: if (exists($cookies{'balanceID'})) {
1045: my $balid = $cookies{'balanceID'};
1046: $cookie=&LONCAPA::clean_handle($balid->value);
1047: my $balancedir=$r->dir_config('lonBalanceDir');
1048: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1049: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1050: my ($possudom,$possuname) = ($1,$2);
1051: my $has_session = 0;
1052: if ((&domain($possudom) ne '') &&
1053: (&homeserver($possuname,$possudom) ne 'no_host')) {
1054: my $try_server;
1055: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1056: if ($opened) {
1057: flock($idf,LOCK_SH);
1058: while (my $line = <$idf>) {
1059: chomp($line);
1060: if (&hostname($line) ne '') {
1061: $try_server = $line;
1062: last;
1063: }
1064: }
1065: close($idf);
1066: if (($try_server) &&
1067: (&has_user_session($try_server,$possudom,$possuname))) {
1068: my $lowest_load = 30000;
1069: ($otherserver,$lowest_load) =
1070: &compare_server_load($try_server,undef,$lowest_load);
1071: if ($otherserver ne '' && $lowest_load < 100) {
1072: $has_session = 1;
1073: } else {
1074: undef($otherserver);
1075: }
1076: }
1077: }
1078: }
1079: if ($has_session) {
1080: if ($update_mtime) {
1081: my $atime = my $mtime = time;
1082: utime($atime,$mtime,"$balancedir/$cookie.id");
1083: }
1084: } else {
1085: unlink("$balancedir/$cookie.id");
1086: }
1087: }
1088: }
1089: }
1090: return ($otherserver,$cookie);
1091: }
1092:
1.1172.2.130 raeburn 1093: sub updatebalcookie {
1094: my ($cookie,$balancer,$lastentry)=@_;
1095: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1096: my ($udom,$uname) = ($1,$2);
1097: my $uprimary_id = &domain($udom,'primary');
1098: my $uintdom = &internet_dom($uprimary_id);
1099: my $intdom = &internet_dom($balancer);
1100: my $serverhomedom = &host_domain($balancer);
1101: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1102: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1103: }
1104: }
1105: return;
1106: }
1107:
1.1172.2.107 raeburn 1108: sub delbalcookie {
1109: my ($cookie,$balancer) =@_;
1110: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1111: my ($udom,$uname) = ($1,$2);
1112: my $uprimary_id = &domain($udom,'primary');
1113: my $uintdom = &internet_dom($uprimary_id);
1114: my $intdom = &internet_dom($balancer);
1115: my $serverhomedom = &host_domain($balancer);
1116: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1117: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1118: }
1119: }
1120: }
1121:
1.914 albertel 1122: # -------------------------------- ask if server already has a session for user
1123: sub has_user_session {
1124: my ($lonid,$udom,$uname) = @_;
1125: my $result = &reply(join(':','userhassession',
1126: map {&escape($_)} ($udom,$uname)),$lonid);
1127: return 1 if ($result eq 'ok');
1128:
1129: return 0;
1130: }
1131:
1.1076 raeburn 1132: # --------- determine least loaded server in a user's domain which allows login
1133:
1134: sub choose_server {
1.1172.2.47 raeburn 1135: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1136: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1137: my %servers = &get_servers($udom);
1.1076 raeburn 1138: my $lowest_load = 30000;
1.1172.2.47 raeburn 1139: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1140: if ($skiploadbal) {
1141: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1142: unless (defined($cached)) {
1143: my $cachetime = 60*60*24;
1144: my %domconfig =
1145: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1146: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1147: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1148: $cachetime);
1149: }
1150: }
1151: }
1.1076 raeburn 1152: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1153: my $loginvia;
1.1172.2.47 raeburn 1154: if ($skiploadbal) {
1155: if (ref($balancers) eq 'HASH') {
1156: next if (exists($balancers->{$lonhost}));
1157: }
1158: }
1.1115 raeburn 1159: if ($checkloginvia) {
1160: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1161: if ($loginvia) {
1162: my ($server,$path) = split(/:/,$loginvia);
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $server) {
1166: $portal_path = $path;
1.1151 raeburn 1167: $isredirect = 1;
1.1116 raeburn 1168: }
1169: } else {
1170: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1171: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1172: if ($login_host eq $lonhost) {
1173: $portal_path = '';
1.1151 raeburn 1174: $isredirect = '';
1.1116 raeburn 1175: }
1176: }
1177: } else {
1.1076 raeburn 1178: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1179: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1180: }
1181: }
1182: if ($login_host ne '') {
1.1116 raeburn 1183: $hostname = &hostname($login_host);
1.1076 raeburn 1184: }
1.1172.2.88 raeburn 1185: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1186: }
1187:
1.1172.2.123 raeburn 1188: sub get_course_sessions {
1189: my ($cnum,$cdom,$lastactivity) = @_;
1190: my %servers = &internet_dom_servers($cdom);
1191: my %returnhash;
1192: foreach my $server (sort(keys(%servers))) {
1193: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1194: my @pairs=split(/\&/,$rep);
1195: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1196: foreach my $item (@pairs) {
1197: my ($key,$value)=split(/=/,$item,2);
1198: $key = &unescape($key);
1199: next if ($key =~ /^error: 2 /);
1200: if (exists($returnhash{$key})) {
1201: next if ($value < $returnhash{$key});
1202: }
1203: $returnhash{$key}=$value;
1204: }
1205: }
1206: }
1207: return %returnhash;
1208: }
1209:
1.202 matthew 1210: # --------------------------------------------- Try to change a user's password
1211:
1212: sub changepass {
1.799 raeburn 1213: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1214: $currentpass = &escape($currentpass);
1215: $newpass = &escape($newpass);
1.1030 raeburn 1216: my $lonhost = $perlvar{'lonHostID'};
1217: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1218: $server);
1219: if (! $answer) {
1220: &logthis("No reply on password change request to $server ".
1221: "by $uname in domain $udom.");
1222: } elsif ($answer =~ "^ok") {
1223: &logthis("$uname in $udom successfully changed their password ".
1224: "on $server.");
1225: } elsif ($answer =~ "^pwchange_failure") {
1226: &logthis("$uname in $udom was unable to change their password ".
1227: "on $server. The action was blocked by either lcpasswd ".
1228: "or pwchange");
1229: } elsif ($answer =~ "^non_authorized") {
1230: &logthis("$uname in $udom did not get their password correct when ".
1231: "attempting to change it on $server.");
1232: } elsif ($answer =~ "^auth_mode_error") {
1233: &logthis("$uname in $udom attempted to change their password despite ".
1234: "not being locally or internally authenticated on $server.");
1235: } elsif ($answer =~ "^unknown_user") {
1236: &logthis("$uname in $udom attempted to change their password ".
1237: "on $server but were unable to because $server is not ".
1238: "their home server.");
1239: } elsif ($answer =~ "^refused") {
1240: &logthis("$server refused to change $uname in $udom password because ".
1241: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1242: } elsif ($answer =~ "invalid_client") {
1243: &logthis("$server refused to change $uname in $udom password because ".
1244: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1245: } elsif ($answer =~ "^prioruse") {
1246: &logthis("$server refused to change $uname in $udom password because ".
1247: "the password had been used before");
1.202 matthew 1248: }
1249: return $answer;
1.1 albertel 1250: }
1251:
1.169 harris41 1252: # ----------------------- Try to determine user's current authentication scheme
1253:
1254: sub queryauthenticate {
1255: my ($uname,$udom)=@_;
1.456 albertel 1256: my $uhome=&homeserver($uname,$udom);
1.1172.2.147 raeburn 1257: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1258: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1259: return 'no_host';
1260: }
1261: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1262: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1263: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1264: }
1.456 albertel 1265: return $answer;
1.169 harris41 1266: }
1267:
1.1 albertel 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1269:
1.1 albertel 1270: sub authenticate {
1.1073 raeburn 1271: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1272: $upass=&escape($upass);
1273: $uname= &LONCAPA::clean_username($uname);
1.836 www 1274: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1275: my $newhome;
1.836 www 1276: if ((!$uhome) || ($uhome eq 'no_host')) {
1277: # Maybe the machine was offline and only re-appeared again recently?
1278: &reconlonc();
1279: # One more
1.952 raeburn 1280: $uhome=&homeserver($uname,$udom,1);
1281: if (($uhome eq 'no_host') && $checkdefauth) {
1282: if (defined(&domain($udom,'primary'))) {
1283: $newhome=&domain($udom,'primary');
1284: }
1285: if ($newhome ne '') {
1286: $uhome = $newhome;
1287: }
1288: }
1.836 www 1289: if ((!$uhome) || ($uhome eq 'no_host')) {
1290: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1291: return 'no_host';
1292: }
1.1 albertel 1293: }
1.1073 raeburn 1294: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1295: if ($answer eq 'authorized') {
1.952 raeburn 1296: if ($newhome) {
1297: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1298: return 'no_account_on_host';
1299: } else {
1300: &logthis("User $uname at $udom authorized by $uhome");
1301: return $uhome;
1302: }
1.471 albertel 1303: }
1304: if ($answer eq 'non_authorized') {
1305: &logthis("User $uname at $udom rejected by $uhome");
1.1172.2.147 raeburn 1306: return 'no_host';
1.9 www 1307: }
1.471 albertel 1308: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1309: return 'no_host';
1310: }
1311:
1.1172.2.149 raeburn 1312: sub can_switchserver {
1313: my ($udom,$home) = @_;
1314: my ($canswitch,@intdoms);
1315: my $internet_names = &get_internet_names($home);
1316: if (ref($internet_names) eq 'ARRAY') {
1317: @intdoms = @{$internet_names};
1318: }
1319: my $uint_dom = &internet_dom(&domain($udom,'primary'));
1320: if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1321: $canswitch = 1;
1322: } else {
1323: my $serverhomeID = &get_server_homeID(&hostname($home));
1324: my $serverhomedom = &host_domain($serverhomeID);
1325: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1326: my %udomdefaults = &get_domain_defaults($udom);
1327: my $remoterev = &get_server_loncaparev('',$home);
1328: $canswitch = &can_host_session($udom,$home,$remoterev,
1329: $udomdefaults{'remotesessions'},
1330: $defdomdefaults{'hostedsessions'});
1331: }
1332: return $canswitch;
1333: }
1334:
1.1073 raeburn 1335: sub can_host_session {
1.1074 raeburn 1336: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1337: my $canhost = 1;
1.1074 raeburn 1338: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1339: if (ref($remotesessions) eq 'HASH') {
1340: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1341: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1342: $canhost = 0;
1343: } else {
1344: $canhost = 1;
1345: }
1346: }
1347: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1348: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1349: $canhost = 1;
1350: } else {
1351: $canhost = 0;
1352: }
1353: }
1354: if ($canhost) {
1355: if ($remotesessions->{'version'} ne '') {
1356: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1357: if ($reqmajor ne '' && $reqminor ne '') {
1358: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1359: my $major = $1;
1360: my $minor = $2;
1361: if (($major < $reqmajor ) ||
1362: (($major == $reqmajor) && ($minor < $reqminor))) {
1363: $canhost = 0;
1364: }
1365: } else {
1366: $canhost = 0;
1367: }
1368: }
1369: }
1370: }
1371: }
1372: if ($canhost) {
1373: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1374: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1375: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1376: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1377: if (($uint_dom ne '') &&
1378: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1379: $canhost = 0;
1380: } else {
1381: $canhost = 1;
1382: }
1383: }
1384: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1385: if (($uint_dom ne '') &&
1386: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1387: $canhost = 1;
1388: } else {
1389: $canhost = 0;
1390: }
1391: }
1392: }
1393: }
1394: return $canhost;
1395: }
1396:
1.1083 raeburn 1397: sub spare_can_host {
1398: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1399: my $canhost=1;
1.1172.2.62 raeburn 1400: my $try_server_hostname = &hostname($try_server);
1401: my $serverhomeID = &get_server_homeID($try_server_hostname);
1402: my $serverhomedom = &host_domain($serverhomeID);
1403: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1404: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1405: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1406: $canhost = 0;
1407: }
1408: }
1.1172.2.136 raeburn 1409: if ($canhost) {
1410: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1411: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1412: unless (&shared_institution($udom,$try_server)) {
1413: $canhost = 0;
1414: }
1415: }
1416: }
1417: }
1.1172.2.62 raeburn 1418: if (($canhost) && ($uint_dom)) {
1419: my @intdoms;
1420: my $internet_names = &get_internet_names($try_server);
1421: if (ref($internet_names) eq 'ARRAY') {
1422: @intdoms = @{$internet_names};
1423: }
1424: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1425: my $remoterev = &get_server_loncaparev(undef,$try_server);
1426: $canhost = &can_host_session($udom,$try_server,$remoterev,
1427: $remotesessions,
1428: $defdomdefaults{'hostedsessions'});
1429: }
1.1083 raeburn 1430: }
1431: return $canhost;
1432: }
1433:
1.1123 raeburn 1434: sub this_host_spares {
1435: my ($dom) = @_;
1.1126 raeburn 1436: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1437: my @hosts = ¤t_machine_ids();
1438: foreach my $lonhost (@hosts) {
1439: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1440: $dom_in_use = $dom;
1441: $lonhost_in_use = $lonhost;
1.1123 raeburn 1442: last;
1443: }
1444: }
1.1126 raeburn 1445: if ($dom_in_use ne '') {
1446: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1447: }
1448: if (ref($result) ne 'HASH') {
1449: $lonhost_in_use = $perlvar{'lonHostID'};
1450: $dom_in_use = &host_domain($lonhost_in_use);
1451: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1452: if (ref($result) ne 'HASH') {
1453: $result = \%spareid;
1454: }
1455: }
1456: return $result;
1457: }
1458:
1459: sub spares_for_offload {
1460: my ($dom_in_use,$lonhost_in_use) = @_;
1461: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1462: if (defined($cached)) {
1463: return $result;
1464: } else {
1.1126 raeburn 1465: my $cachetime = 60*60*24;
1466: my %domconfig =
1467: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1468: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1469: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1470: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1471: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1472: }
1473: }
1474: }
1475: }
1.1126 raeburn 1476: return;
1.1123 raeburn 1477: }
1478:
1.1129 raeburn 1479: sub get_lonbalancer_config {
1480: my ($servers) = @_;
1481: my ($currbalancer,$currtargets);
1482: if (ref($servers) eq 'HASH') {
1483: foreach my $server (keys(%{$servers})) {
1484: my %what = (
1485: spareid => 1,
1486: perlvar => 1,
1487: );
1488: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1489: if ($result eq 'ok') {
1490: if (ref($returnhash) eq 'HASH') {
1491: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1492: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1493: $currbalancer = $server;
1494: $currtargets = {};
1495: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1496: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1497: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1498: }
1499: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1500: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1501: }
1502: }
1503: last;
1504: }
1505: }
1506: }
1507: }
1508: }
1509: }
1510: return ($currbalancer,$currtargets);
1511: }
1512:
1513: sub check_loadbalancing {
1.1172.2.88 raeburn 1514: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1515: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1516: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1517: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1518: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1519: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1520: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1521: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1522: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1523: my $domneedscache;
1.1129 raeburn 1524: my $cachetime = 60*60*24;
1525:
1526: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1527: $dom_in_use = $udom;
1528: $homeintdom = 1;
1529: } else {
1530: $dom_in_use = $serverhomedom;
1531: }
1532: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1533: unless (defined($cached)) {
1534: my %domconfig =
1535: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1536: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1537: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1538: } else {
1539: $domneedscache = $dom_in_use;
1.1129 raeburn 1540: }
1541: }
1542: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1543: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1544: &check_balancer_result($result,@hosts);
1.1129 raeburn 1545: if ($is_balancer) {
1546: if (ref($currrules) eq 'HASH') {
1547: if ($homeintdom) {
1548: if ($uname ne '') {
1549: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1550: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1551: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1552: $rule_in_effect = $currrules->{'_LC_author'};
1553: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1554: $rule_in_effect = $currrules->{'_LC_adv'}
1555: }
1556: }
1557: if ($rule_in_effect eq '') {
1558: my %userenv = &userenvironment($udom,$uname,'inststatus');
1559: if ($userenv{'inststatus'} ne '') {
1560: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1561: my ($othertitle,$usertypes,$types) =
1562: &Apache::loncommon::sorted_inst_types($udom);
1563: if (ref($types) eq 'ARRAY') {
1564: foreach my $type (@{$types}) {
1565: if (grep(/^\Q$type\E$/,@statuses)) {
1566: if (exists($currrules->{$type})) {
1567: $rule_in_effect = $currrules->{$type};
1568: }
1569: }
1570: }
1571: }
1572: } else {
1573: if (exists($currrules->{'default'})) {
1574: $rule_in_effect = $currrules->{'default'};
1575: }
1576: }
1577: }
1578: } else {
1579: if (exists($currrules->{'default'})) {
1580: $rule_in_effect = $currrules->{'default'};
1581: }
1582: }
1583: } else {
1584: if ($currrules->{'_LC_external'} ne '') {
1585: $rule_in_effect = $currrules->{'_LC_external'};
1586: }
1587: }
1588: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1589: $uname,$udom);
1590: }
1591: }
1592: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1593: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1594: unless (defined($cached)) {
1595: my %domconfig =
1596: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1597: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1598: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1599: } else {
1600: $domneedscache = $serverhomedom;
1.1129 raeburn 1601: }
1602: }
1603: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1604: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1605: &check_balancer_result($result,@hosts);
1606: if ($is_balancer) {
1.1129 raeburn 1607: if (ref($currrules) eq 'HASH') {
1608: if ($currrules->{'_LC_internetdom'} ne '') {
1609: $rule_in_effect = $currrules->{'_LC_internetdom'};
1610: }
1611: }
1612: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1613: $uname,$udom);
1614: }
1615: } else {
1616: if ($perlvar{'lonBalancer'} eq 'yes') {
1617: $is_balancer = 1;
1618: $offloadto = &this_host_spares($dom_in_use);
1619: }
1.1172.2.75 raeburn 1620: unless (defined($cached)) {
1621: $domneedscache = $serverhomedom;
1622: }
1.1129 raeburn 1623: }
1624: } else {
1625: if ($perlvar{'lonBalancer'} eq 'yes') {
1626: $is_balancer = 1;
1627: $offloadto = &this_host_spares($dom_in_use);
1628: }
1.1172.2.75 raeburn 1629: unless (defined($cached)) {
1630: $domneedscache = $serverhomedom;
1631: }
1632: }
1633: if ($domneedscache) {
1634: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1635: }
1.1172.2.130 raeburn 1636: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1637: my $lowest_load = 30000;
1638: if (ref($offloadto) eq 'HASH') {
1639: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1640: foreach my $try_server (@{$offloadto->{'primary'}}) {
1641: ($otherserver,$lowest_load) =
1642: &compare_server_load($try_server,$otherserver,$lowest_load);
1643: }
1.1129 raeburn 1644: }
1.1172.2.5 raeburn 1645: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1646:
1.1172.2.5 raeburn 1647: if (!$found_server) {
1648: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1649: foreach my $try_server (@{$offloadto->{'default'}}) {
1650: ($otherserver,$lowest_load) =
1651: &compare_server_load($try_server,$otherserver,$lowest_load);
1652: }
1653: }
1654: }
1655: } elsif (ref($offloadto) eq 'ARRAY') {
1656: if (@{$offloadto} == 1) {
1657: $otherserver = $offloadto->[0];
1658: } elsif (@{$offloadto} > 1) {
1659: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1660: ($otherserver,$lowest_load) =
1661: &compare_server_load($try_server,$otherserver,$lowest_load);
1662: }
1663: }
1664: }
1.1172.2.88 raeburn 1665: unless ($caller eq 'login') {
1666: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1667: $is_balancer = 0;
1668: if ($uname ne '' && $udom ne '') {
1669: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1670: &appenv({'user.loadbalexempt' => $lonhost,
1671: 'user.loadbalcheck.time' => time});
1672: }
1.1172.2.5 raeburn 1673: }
1.1129 raeburn 1674: }
1675: }
1.1172.2.130 raeburn 1676: }
1677: if (($is_balancer) && (!$homeintdom)) {
1678: undef($setcookie);
1.1129 raeburn 1679: }
1.1172.2.107 raeburn 1680: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1681: }
1682:
1.1172.2.12 raeburn 1683: sub check_balancer_result {
1684: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1685: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1686: if (ref($result) eq 'HASH') {
1687: if ($result->{'lonhost'} ne '') {
1688: my $currbalancer = $result->{'lonhost'};
1689: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1690: $is_balancer = 1;
1691: $currtargets = $result->{'targets'};
1692: $currrules = $result->{'rules'};
1693: }
1694: } else {
1695: foreach my $key (keys(%{$result})) {
1696: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1697: (ref($result->{$key}) eq 'HASH')) {
1698: $is_balancer = 1;
1699: $currrules = $result->{$key}{'rules'};
1700: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1701: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1702: last;
1703: }
1704: }
1705: }
1706: }
1.1172.2.107 raeburn 1707: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1708: }
1709:
1.1129 raeburn 1710: sub get_loadbalancer_targets {
1711: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1712: my $offloadto;
1.1172.2.4 raeburn 1713: if ($rule_in_effect eq 'none') {
1714: return [$perlvar{'lonHostID'}];
1715: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1716: $offloadto = $currtargets;
1717: } else {
1718: if ($rule_in_effect eq 'homeserver') {
1719: my $homeserver = &homeserver($uname,$udom);
1720: if ($homeserver ne 'no_host') {
1721: $offloadto = [$homeserver];
1722: }
1723: } elsif ($rule_in_effect eq 'externalbalancer') {
1724: my %domconfig =
1725: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1726: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1727: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1728: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1729: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1730: }
1731: }
1732: } else {
1.1172.2.7 raeburn 1733: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1734: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1735: if (&hostname($remotebalancer) ne '') {
1736: $offloadto = [$remotebalancer];
1737: }
1738: }
1739: } elsif (&hostname($rule_in_effect) ne '') {
1740: $offloadto = [$rule_in_effect];
1741: }
1742: }
1743: return $offloadto;
1744: }
1745:
1.1127 raeburn 1746: sub internet_dom_servers {
1747: my ($dom) = @_;
1748: my (%uniqservers,%servers);
1749: my $primaryserver = &hostname(&domain($dom,'primary'));
1750: my @machinedoms = &machine_domains($primaryserver);
1751: foreach my $mdom (@machinedoms) {
1752: my %currservers = %servers;
1753: my %server = &get_servers($mdom);
1754: %servers = (%currservers,%server);
1755: }
1756: my %by_hostname;
1757: foreach my $id (keys(%servers)) {
1758: push(@{$by_hostname{$servers{$id}}},$id);
1759: }
1760: foreach my $hostname (sort(keys(%by_hostname))) {
1761: if (@{$by_hostname{$hostname}} > 1) {
1762: my $match = 0;
1763: foreach my $id (@{$by_hostname{$hostname}}) {
1764: if (&host_domain($id) eq $dom) {
1765: $uniqservers{$id} = $hostname;
1766: $match = 1;
1767: }
1768: }
1769: unless ($match) {
1770: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1771: }
1772: } else {
1773: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1774: }
1775: }
1776: return %uniqservers;
1777: }
1778:
1.1 albertel 1779: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1780:
1.599 albertel 1781: my %homecache;
1.1 albertel 1782: sub homeserver {
1.230 stredwic 1783: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1784: my $index="$uname:$udom";
1.426 albertel 1785:
1.599 albertel 1786: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1787:
1788: my %servers = &get_servers($udom,'library');
1789: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1790: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1791: exists($badServerCache{$tryserver}));
1.841 albertel 1792:
1793: my $answer=reply("home:$udom:$uname",$tryserver);
1794: if ($answer eq 'found') {
1795: delete($badServerCache{$tryserver});
1796: return $homecache{$index}=$tryserver;
1797: } elsif ($answer eq 'no_host') {
1798: $badServerCache{$tryserver}=1;
1799: }
1.1 albertel 1800: }
1801: return 'no_host';
1.70 www 1802: }
1803:
1804: # ------------------------------------- Find the usernames behind a list of IDs
1805:
1806: sub idget {
1807: my ($udom,@ids)=@_;
1808: my %returnhash=();
1809:
1.841 albertel 1810: my %servers = &get_servers($udom,'library');
1811: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1812: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1813: $idlist=~tr/A-Z/a-z/;
1814: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1815: my @answer=();
1816: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1817: @answer=split(/\&/,$reply);
1818: } ;
1819: my $i;
1820: for ($i=0;$i<=$#ids;$i++) {
1821: if ($answer[$i]) {
1.1172.2.73 raeburn 1822: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1823: }
1824: }
1825: }
1.70 www 1826: return %returnhash;
1827: }
1828:
1829: # ------------------------------------- Find the IDs behind a list of usernames
1830:
1831: sub idrget {
1832: my ($udom,@unames)=@_;
1833: my %returnhash=();
1.800 albertel 1834: foreach my $uname (@unames) {
1835: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1836: }
1.70 www 1837: return %returnhash;
1838: }
1839:
1840: # ------------------------------- Store away a list of names and associated IDs
1841:
1842: sub idput {
1843: my ($udom,%ids)=@_;
1844: my %servers=();
1.800 albertel 1845: foreach my $uname (keys(%ids)) {
1846: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1847: my $uhom=&homeserver($uname,$udom);
1.70 www 1848: if ($uhom ne 'no_host') {
1.800 albertel 1849: my $id=&escape($ids{$uname});
1.70 www 1850: $id=~tr/A-Z/a-z/;
1.800 albertel 1851: my $esc_unam=&escape($uname);
1.70 www 1852: if ($servers{$uhom}) {
1.800 albertel 1853: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1854: } else {
1.800 albertel 1855: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1856: }
1857: }
1.191 harris41 1858: }
1.800 albertel 1859: foreach my $server (keys(%servers)) {
1860: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1861: }
1.344 www 1862: }
1863:
1.1172.2.30 raeburn 1864: # ---------------------------------------- Delete unwanted IDs from ids.db file
1865:
1866: sub iddel {
1867: my ($udom,$idshashref,$uhome)=@_;
1868: my %result=();
1869: unless (ref($idshashref) eq 'HASH') {
1870: return %result;
1871: }
1872: my %servers=();
1873: while (my ($id,$uname) = each(%{$idshashref})) {
1874: my $uhom;
1875: if ($uhome) {
1876: $uhom = $uhome;
1877: } else {
1878: $uhom=&homeserver($uname,$udom);
1879: }
1880: if ($uhom ne 'no_host') {
1881: if ($servers{$uhom}) {
1882: $servers{$uhom}.='&'.&escape($id);
1883: } else {
1884: $servers{$uhom}=&escape($id);
1885: }
1886: }
1887: }
1888: foreach my $server (keys(%servers)) {
1889: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1890: }
1891: return %result;
1892: }
1893:
1.1023 raeburn 1894: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1895: sub dump_dom {
1.1165 droeschl 1896: my ($namespace, $udom, $regexp) = @_;
1897:
1898: $udom ||= $env{'user.domain'};
1899:
1900: return () unless $udom;
1901:
1902: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1903: }
1904:
1.1023 raeburn 1905: # ------------------------------------------ get items from domain db files
1.806 raeburn 1906:
1907: sub get_dom {
1.860 raeburn 1908: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1909: return if ($udom eq 'public');
1.806 raeburn 1910: my $items='';
1911: foreach my $item (@$storearr) {
1912: $items.=&escape($item).'&';
1913: }
1914: $items=~s/\&$//;
1.860 raeburn 1915: if (!$udom) {
1916: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1917: return if ($udom eq 'public');
1.860 raeburn 1918: if (defined(&domain($udom,'primary'))) {
1919: $uhome=&domain($udom,'primary');
1920: } else {
1.874 albertel 1921: undef($uhome);
1.860 raeburn 1922: }
1923: } else {
1924: if (!$uhome) {
1925: if (defined(&domain($udom,'primary'))) {
1926: $uhome=&domain($udom,'primary');
1927: }
1928: }
1929: }
1930: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139 raeburn 1931: my $rep;
1932: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1933: # domain information is hosted on this machine
1934: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1935: } else {
1936: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1937: }
1.866 raeburn 1938: my %returnhash;
1.875 albertel 1939: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1940: return %returnhash;
1941: }
1.806 raeburn 1942: my @pairs=split(/\&/,$rep);
1943: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1944: return @pairs;
1945: }
1946: my $i=0;
1947: foreach my $item (@$storearr) {
1948: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1949: $i++;
1950: }
1951: return %returnhash;
1952: } else {
1.880 banghart 1953: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1954: }
1955: }
1956:
1957: # -------------------------------------------- put items in domain db files
1958:
1959: sub put_dom {
1.860 raeburn 1960: my ($namespace,$storehash,$udom,$uhome)=@_;
1961: if (!$udom) {
1962: $udom=$env{'user.domain'};
1963: if (defined(&domain($udom,'primary'))) {
1964: $uhome=&domain($udom,'primary');
1965: } else {
1.874 albertel 1966: undef($uhome);
1.860 raeburn 1967: }
1968: } else {
1969: if (!$uhome) {
1970: if (defined(&domain($udom,'primary'))) {
1971: $uhome=&domain($udom,'primary');
1972: }
1973: }
1974: }
1975: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1976: my $items='';
1977: foreach my $item (keys(%$storehash)) {
1978: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1979: }
1980: $items=~s/\&$//;
1981: return &reply("putdom:$udom:$namespace:$items",$uhome);
1982: } else {
1.860 raeburn 1983: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1984: }
1985: }
1986:
1.1023 raeburn 1987: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1988: sub newput_dom {
1.1023 raeburn 1989: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1990: my $result;
1991: if (!$udom) {
1992: $udom=$env{'user.domain'};
1993: }
1.1023 raeburn 1994: if ($udom) {
1995: my $uname = &get_domainconfiguser($udom);
1996: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1997: }
1998: return $result;
1999: }
2000:
1.1023 raeburn 2001: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2002: sub del_dom {
1.1023 raeburn 2003: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2004: if (ref($storearr) eq 'ARRAY') {
2005: if (!$udom) {
2006: $udom=$env{'user.domain'};
2007: }
1.1023 raeburn 2008: if ($udom) {
2009: my $uname = &get_domainconfiguser($udom);
2010: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2011: }
2012: }
2013: }
2014:
1.1023 raeburn 2015: # ----------------------------------construct domainconfig user for a domain
2016: sub get_domainconfiguser {
2017: my ($udom) = @_;
2018: return $udom.'-domainconfig';
2019: }
2020:
1.837 raeburn 2021: sub retrieve_inst_usertypes {
2022: my ($udom) = @_;
2023: my (%returnhash,@order);
1.989 raeburn 2024: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2025: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2026: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 2027: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2028: } else {
2029: if (defined(&domain($udom,'primary'))) {
2030: my $uhome=&domain($udom,'primary');
2031: my $rep=&reply("inst_usertypes:$udom",$uhome);
2032: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2033: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2034: return (\%returnhash,\@order);
2035: }
2036: my ($hashitems,$orderitems) = split(/:/,$rep);
2037: my @pairs=split(/\&/,$hashitems);
2038: foreach my $item (@pairs) {
2039: my ($key,$value)=split(/=/,$item,2);
2040: $key = &unescape($key);
2041: next if ($key =~ /^error: 2 /);
2042: $returnhash{$key}=&thaw_unescape($value);
2043: }
2044: my @esc_order = split(/\&/,$orderitems);
2045: foreach my $item (@esc_order) {
2046: push(@order,&unescape($item));
2047: }
2048: } else {
1.1172.2.44 raeburn 2049: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2050: }
1.1172.2.44 raeburn 2051: return (\%returnhash,\@order);
1.837 raeburn 2052: }
2053: }
2054:
1.868 raeburn 2055: sub is_domainimage {
2056: my ($url) = @_;
1.1172.2.142 raeburn 2057: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2058: if (&domain($1) ne '') {
2059: return '1';
2060: }
2061: }
2062: return;
2063: }
2064:
1.899 raeburn 2065: sub inst_directory_query {
2066: my ($srch) = @_;
2067: my $udom = $srch->{'srchdomain'};
2068: my %results;
2069: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2070: my $outcome;
1.899 raeburn 2071: if ($homeserver ne '') {
1.1172.2.116 raeburn 2072: unless ($homeserver eq $perlvar{'lonHostID'}) {
2073: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2074: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2075: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2076: if (($major eq '' && $minor eq '') || ($major < 2) ||
2077: (($major == 2) && ($minor < 11)) ||
2078: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2079: return;
2080: }
2081: }
2082: }
1.904 albertel 2083: my $queryid=&reply("querysend:instdirsearch:".
2084: &escape($srch->{'srchby'}).':'.
2085: &escape($srch->{'srchterm'}).':'.
2086: &escape($srch->{'srchtype'}),$homeserver);
2087: my $host=&hostname($homeserver);
2088: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2089: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2090: return;
2091: }
2092: my $response = &get_query_reply($queryid);
2093: my $maxtries = 5;
2094: my $tries = 1;
2095: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2096: $response = &get_query_reply($queryid);
2097: $tries ++;
2098: }
2099:
2100: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2101: if ($response eq 'unavailable') {
2102: $outcome = $response;
2103: } else {
2104: $outcome = 'ok';
2105: my @matches = split(/\n/,$response);
2106: foreach my $match (@matches) {
2107: my ($key,$value) = split(/=/,$match);
2108: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2109: }
1.899 raeburn 2110: }
2111: }
2112: }
1.909 raeburn 2113: return ($outcome,%results);
1.899 raeburn 2114: }
2115:
2116: sub usersearch {
2117: my ($srch) = @_;
2118: my $dom = $srch->{'srchdomain'};
2119: my %results;
2120: my %libserv = &all_library();
2121: my $query = 'usersearch';
2122: foreach my $tryserver (keys(%libserv)) {
2123: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2124: unless ($tryserver eq $perlvar{'lonHostID'}) {
2125: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2126: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2127: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2128: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2129: (($major == 2) && ($minor < 11)) ||
2130: (($major == 2) && ($minor == 11) && ($subver < 3)));
2131: }
2132: }
1.899 raeburn 2133: my $host=&hostname($tryserver);
2134: my $queryid=
1.911 raeburn 2135: &reply("querysend:".&escape($query).':'.
2136: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2137: &escape($srch->{'srchtype'}).':'.
2138: &escape($srch->{'srchterm'}),$tryserver);
2139: if ($queryid !~/^\Q$host\E\_/) {
2140: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2141: next;
1.899 raeburn 2142: }
2143: my $reply = &get_query_reply($queryid);
2144: my $maxtries = 1;
2145: my $tries = 1;
2146: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2147: $reply = &get_query_reply($queryid);
2148: $tries ++;
2149: }
2150: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2151: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2152: } else {
1.911 raeburn 2153: my @matches;
2154: if ($reply =~ /\n/) {
2155: @matches = split(/\n/,$reply);
2156: } else {
2157: @matches = split(/\&/,$reply);
2158: }
1.899 raeburn 2159: foreach my $match (@matches) {
2160: my ($uname,$udom,%userhash);
1.911 raeburn 2161: foreach my $entry (split(/:/,$match)) {
2162: my ($key,$value) =
2163: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2164: $userhash{$key} = $value;
2165: if ($key eq 'username') {
2166: $uname = $value;
2167: } elsif ($key eq 'domain') {
2168: $udom = $value;
1.911 raeburn 2169: }
1.899 raeburn 2170: }
2171: $results{$uname.':'.$udom} = \%userhash;
2172: }
2173: }
2174: }
2175: }
2176: return %results;
2177: }
2178:
1.912 raeburn 2179: sub get_instuser {
2180: my ($udom,$uname,$id) = @_;
2181: my $homeserver = &domain($udom,'primary');
2182: my ($outcome,%results);
2183: if ($homeserver ne '') {
2184: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2185: &escape($id).':'.&escape($udom),$homeserver);
2186: my $host=&hostname($homeserver);
2187: if ($queryid !~/^\Q$host\E\_/) {
2188: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2189: return;
2190: }
2191: my $response = &get_query_reply($queryid);
2192: my $maxtries = 5;
2193: my $tries = 1;
2194: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2195: $response = &get_query_reply($queryid);
2196: $tries ++;
2197: }
2198: if (!&error($response) && $response ne 'refused') {
2199: if ($response eq 'unavailable') {
2200: $outcome = $response;
2201: } else {
2202: $outcome = 'ok';
2203: my @matches = split(/\n/,$response);
2204: foreach my $match (@matches) {
2205: my ($key,$value) = split(/=/,$match);
2206: $results{&unescape($key)} = &thaw_unescape($value);
2207: }
2208: }
2209: }
2210: }
2211: my %userinfo;
2212: if (ref($results{$uname}) eq 'HASH') {
2213: %userinfo = %{$results{$uname}};
2214: }
2215: return ($outcome,%userinfo);
2216: }
2217:
1.1172.2.69 raeburn 2218: sub get_multiple_instusers {
2219: my ($udom,$users,$caller) = @_;
2220: my ($outcome,$results);
2221: if (ref($users) eq 'HASH') {
2222: my $count = keys(%{$users});
2223: my $requested = &freeze_escape($users);
2224: my $homeserver = &domain($udom,'primary');
2225: if ($homeserver ne '') {
2226: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2227: my $host=&hostname($homeserver);
2228: if ($queryid !~/^\Q$host\E\_/) {
2229: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2230: ' for host: '.$homeserver.'in domain '.$udom);
2231: return ($outcome,$results);
2232: }
2233: my $response = &get_query_reply($queryid);
2234: my $maxtries = 5;
2235: if ($count > 100) {
2236: $maxtries = 1+int($count/20);
2237: }
2238: my $tries = 1;
2239: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2240: $response = &get_query_reply($queryid);
2241: $tries ++;
2242: }
2243: if ($response eq '') {
2244: $results = {};
2245: foreach my $key (keys(%{$users})) {
2246: my ($uname,$id);
2247: if ($caller eq 'id') {
2248: $id = $key;
2249: } else {
2250: $uname = $key;
2251: }
2252: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2253: $outcome = $resp;
2254: if ($resp eq 'ok') {
2255: %{$results} = (%{$results}, %info);
2256: } else {
2257: last;
2258: }
2259: }
2260: } elsif(!&error($response) && ($response ne 'refused')) {
2261: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2262: $outcome = $response;
2263: } else {
2264: ($outcome,my $userdata) = split(/=/,$response,2);
2265: if ($outcome eq 'ok') {
2266: $results = &thaw_unescape($userdata);
2267: }
2268: }
2269: }
2270: }
2271: }
2272: return ($outcome,$results);
2273: }
2274:
1.912 raeburn 2275: sub inst_rulecheck {
1.923 raeburn 2276: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2277: my %returnhash;
2278: if ($udom ne '') {
2279: if (ref($rules) eq 'ARRAY') {
2280: @{$rules} = map {&escape($_);} (@{$rules});
2281: my $rulestr = join(':',@{$rules});
2282: my $homeserver=&domain($udom,'primary');
2283: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2284: my $response;
2285: if ($item eq 'username') {
2286: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2287: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2288: $homeserver));
1.923 raeburn 2289: } elsif ($item eq 'id') {
2290: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2291: ':'.&escape($id).':'.$rulestr,
2292: $homeserver));
1.945 raeburn 2293: } elsif ($item eq 'selfcreate') {
2294: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2295: &escape($udom).':'.&escape($uname).
2296: ':'.$rulestr,$homeserver));
1.1172.2.147 raeburn 2297: } elsif ($item eq 'unamemap') {
2298: $response=&unescape(&reply('instunamemapcheck:'.
2299: &escape($udom).':'.&escape($uname).
2300: ':'.$rulestr,$homeserver));
1.923 raeburn 2301: }
1.912 raeburn 2302: if ($response ne 'refused') {
2303: my @pairs=split(/\&/,$response);
2304: foreach my $item (@pairs) {
2305: my ($key,$value)=split(/=/,$item,2);
2306: $key = &unescape($key);
2307: next if ($key =~ /^error: 2 /);
2308: $returnhash{$key}=&thaw_unescape($value);
2309: }
2310: }
2311: }
2312: }
2313: }
2314: return %returnhash;
2315: }
2316:
2317: sub inst_userrules {
1.923 raeburn 2318: my ($udom,$check) = @_;
1.912 raeburn 2319: my (%ruleshash,@ruleorder);
2320: if ($udom ne '') {
2321: my $homeserver=&domain($udom,'primary');
2322: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2323: my $response;
2324: if ($check eq 'id') {
2325: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2326: $homeserver);
1.943 raeburn 2327: } elsif ($check eq 'email') {
2328: $response=&reply('instemailrules:'.&escape($udom),
2329: $homeserver);
1.1172.2.147 raeburn 2330: } elsif ($check eq 'unamemap') {
2331: $response=&reply('unamemaprules:'.&escape($udom),
2332: $homeserver);
1.923 raeburn 2333: } else {
2334: $response=&reply('instuserrules:'.&escape($udom),
2335: $homeserver);
2336: }
1.912 raeburn 2337: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2338: ($response ne 'unknown_cmd') &&
1.912 raeburn 2339: ($response ne 'no_such_host')) {
2340: my ($hashitems,$orderitems) = split(/:/,$response);
2341: my @pairs=split(/\&/,$hashitems);
2342: foreach my $item (@pairs) {
2343: my ($key,$value)=split(/=/,$item,2);
2344: $key = &unescape($key);
2345: next if ($key =~ /^error: 2 /);
2346: $ruleshash{$key}=&thaw_unescape($value);
2347: }
2348: my @esc_order = split(/\&/,$orderitems);
2349: foreach my $item (@esc_order) {
2350: push(@ruleorder,&unescape($item));
2351: }
2352: }
2353: }
2354: }
2355: return (\%ruleshash,\@ruleorder);
2356: }
2357:
1.976 raeburn 2358: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2359:
2360: sub get_domain_defaults {
1.1172.2.35 raeburn 2361: my ($domain,$ignore_cache) = @_;
2362: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2363: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2364: unless ($ignore_cache) {
2365: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2366: if (defined($cached)) {
2367: if (ref($result) eq 'HASH') {
2368: return %{$result};
2369: }
1.943 raeburn 2370: }
2371: }
2372: my %domdefaults;
2373: my %domconfig =
1.989 raeburn 2374: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2375: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2376: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2377: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2378: 'coursecategories','autoenroll',
1.1172.2.146 raeburn 2379: 'helpsettings','wafproxy'],$domain);
1.1172.2.41 raeburn 2380: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2381: if (ref($domconfig{'defaults'}) eq 'HASH') {
2382: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2383: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2384: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2385: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2386: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2387: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2388: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2389: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2390: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.147 raeburn 2391: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2392: } else {
2393: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2394: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2395: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2396: }
1.976 raeburn 2397: if (ref($domconfig{'quotas'}) eq 'HASH') {
2398: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2399: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2400: } else {
2401: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2402: }
1.1172.2.6 raeburn 2403: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2404: foreach my $item (@usertools) {
2405: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2406: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2407: }
2408: }
1.1172.2.29 raeburn 2409: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2410: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2411: }
1.976 raeburn 2412: }
1.985 raeburn 2413: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2414: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2415: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2416: }
2417: }
1.1172.2.9 raeburn 2418: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2419: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2420: }
1.989 raeburn 2421: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2422: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2423: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2424: }
2425: }
1.1047 raeburn 2426: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2427: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144 raeburn 2428: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60 raeburn 2429: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2430: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2431: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2432: }
1.1172.2.41 raeburn 2433: foreach my $type (@coursetypes) {
2434: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2435: unless ($type eq 'community') {
2436: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2437: }
2438: }
2439: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2440: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2441: }
1.1172.2.60 raeburn 2442: if ($domdefaults{'postsubmit'} eq 'on') {
2443: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2444: $domdefaults{$type.'postsubtimeout'} =
2445: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2446: }
2447: }
1.1172.2.30 raeburn 2448: }
1.1172.2.67 raeburn 2449: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2450: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2451: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2452: if (@clonecodes) {
2453: $domdefaults{'canclone'} = join('+',@clonecodes);
2454: }
2455: }
2456: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2457: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2458: }
1.1172.2.103 raeburn 2459: if ($domconfig{'coursedefaults'}{'texengine'}) {
2460: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2461: }
1.1047 raeburn 2462: }
1.1073 raeburn 2463: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2464: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2465: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2466: }
2467: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2468: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2469: }
1.1172.2.62 raeburn 2470: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2471: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2472: }
1.1172.2.137 raeburn 2473: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2474: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2475: }
1.1073 raeburn 2476: }
1.1172.2.41 raeburn 2477: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2478: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2479: my @settings = ('types','registered','enroll_dates','access_dates','section',
2480: 'approval','limit');
2481: foreach my $type (@coursetypes) {
2482: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2483: my @mgrdc = ();
2484: foreach my $item (@settings) {
2485: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2486: push(@mgrdc,$item);
2487: }
2488: }
2489: if (@mgrdc) {
2490: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2491: }
2492: }
2493: }
2494: }
2495: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2496: foreach my $type (@coursetypes) {
2497: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2498: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2499: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2500: }
2501: }
2502: }
2503: }
2504: }
1.1172.2.46 raeburn 2505: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2506: $domdefaults{'catauth'} = 'std';
2507: $domdefaults{'catunauth'} = 'std';
2508: if ($domconfig{'coursecategories'}{'auth'}) {
2509: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2510: }
2511: if ($domconfig{'coursecategories'}{'unauth'}) {
2512: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2513: }
2514: }
1.1172.2.76 raeburn 2515: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2516: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146 raeburn 2517: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76 raeburn 2518: }
1.1172.2.89 raeburn 2519: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2520: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2521: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2522: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2523: }
2524: }
1.1172.2.142 raeburn 2525: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2526: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2527: if ($domconfig{'wafproxy'}{$item}) {
2528: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2529: }
2530: }
2531: }
1.1172.2.23 raeburn 2532: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2533: return %domdefaults;
2534: }
2535:
1.1172.2.106 raeburn 2536: sub get_dom_cats {
2537: my ($dom) = @_;
2538: return unless (&domain($dom));
2539: my ($cats,$cached)=&is_cached_new('cats',$dom);
2540: unless (defined($cached)) {
2541: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2542: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2543: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2544: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2545: } else {
2546: $cats = {};
2547: }
2548: } else {
2549: $cats = {};
2550: }
2551: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2552: }
2553: return $cats;
2554: }
2555:
2556: sub get_dom_instcats {
2557: my ($dom) = @_;
2558: return unless (&domain($dom));
2559: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2560: unless (defined($cached)) {
2561: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2562: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2563: if ($totcodes > 0) {
2564: my $caller = 'global';
2565: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2566: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2567: $instcats = {
2568: codes => \%codes,
2569: codetitles => \@codetitles,
2570: cat_titles => \%cat_titles,
2571: cat_order => \%cat_order,
2572: };
2573: &do_cache_new('instcats',$dom,$instcats,3600);
2574: }
2575: }
2576: }
2577: return $instcats;
2578: }
2579:
2580: sub retrieve_instcodes {
2581: my ($coursecodes,$dom) = @_;
2582: my $totcodes;
2583: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2584: foreach my $course (keys(%courses)) {
2585: if (ref($courses{$course}) eq 'HASH') {
2586: if ($courses{$course}{'inst_code'} ne '') {
2587: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2588: $totcodes ++;
2589: }
2590: }
2591: }
2592: return $totcodes;
2593: }
2594:
1.1172.2.113 raeburn 2595: # --------------------------------------------- Get domain config for passwords
2596:
2597: sub get_passwdconf {
2598: my ($dom) = @_;
2599: my (%passwdconf,$gotconf,$lookup);
2600: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2601: if (defined($cached)) {
2602: if (ref($result) eq 'HASH') {
2603: %passwdconf = %{$result};
2604: $gotconf = 1;
2605: }
2606: }
2607: unless ($gotconf) {
2608: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2609: if (ref($domconfig{'passwords'}) eq 'HASH') {
2610: %passwdconf = %{$domconfig{'passwords'}};
2611: }
2612: my $cachetime = 24*60*60;
2613: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2614: }
2615: return %passwdconf;
2616: }
2617:
1.344 www 2618: # --------------------------------------------------- Assign a key to a student
2619:
2620: sub assign_access_key {
1.364 www 2621: #
2622: # a valid key looks like uname:udom#comments
2623: # comments are being appended
2624: #
1.498 www 2625: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2626: $kdom=
1.620 albertel 2627: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2628: $knum=
1.620 albertel 2629: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2630: $cdom=
1.620 albertel 2631: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2632: $cnum=
1.620 albertel 2633: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2634: $udom=$env{'user.name'} unless (defined($udom));
2635: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2636: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2637: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2638: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2639: # assigned to this person
2640: # - this should not happen,
1.345 www 2641: # unless something went wrong
2642: # the first time around
2643: # ready to assign
1.364 www 2644: $logentry=$1.'; '.$logentry;
1.496 www 2645: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2646: $kdom,$knum) eq 'ok') {
1.345 www 2647: # key now belongs to user
1.346 www 2648: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2649: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2650: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2651: return 'ok';
2652: } else {
2653: return
2654: 'error: Count not permanently assign key, will need to be re-entered later.';
2655: }
2656: } else {
2657: return 'error: Could not assign key, try again later.';
2658: }
1.364 www 2659: } elsif (!$existing{$ckey}) {
1.345 www 2660: # the key does not exist
2661: return 'error: The key does not exist';
2662: } else {
2663: # the key is somebody else's
2664: return 'error: The key is already in use';
2665: }
1.344 www 2666: }
2667:
1.364 www 2668: # ------------------------------------------ put an additional comment on a key
2669:
2670: sub comment_access_key {
2671: #
2672: # a valid key looks like uname:udom#comments
2673: # comments are being appended
2674: #
2675: my ($ckey,$cdom,$cnum,$logentry)=@_;
2676: $cdom=
1.620 albertel 2677: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2678: $cnum=
1.620 albertel 2679: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2680: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2681: if ($existing{$ckey}) {
2682: $existing{$ckey}.='; '.$logentry;
2683: # ready to assign
1.367 www 2684: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2685: $cdom,$cnum) eq 'ok') {
2686: return 'ok';
2687: } else {
2688: return 'error: Count not store comment.';
2689: }
2690: } else {
2691: # the key does not exist
2692: return 'error: The key does not exist';
2693: }
2694: }
2695:
1.344 www 2696: # ------------------------------------------------------ Generate a set of keys
2697:
2698: sub generate_access_keys {
1.364 www 2699: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2700: $cdom=
1.620 albertel 2701: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2702: $cnum=
1.620 albertel 2703: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2704: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2705: unless (($cdom) && ($cnum)) { return 0; }
2706: if ($number>10000) { return 0; }
2707: sleep(2); # make sure don't get same seed twice
2708: srand(time()^($$+($$<<15))); # from "Programming Perl"
2709: my $total=0;
2710: for (my $i=1;$i<=$number;$i++) {
2711: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2712: sprintf("%lx",int(100000*rand)).'-'.
2713: sprintf("%lx",int(100000*rand));
2714: $newkey=~s/1/g/g; # folks mix up 1 and l
2715: $newkey=~s/0/h/g; # and also 0 and O
2716: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2717: if ($existing{$newkey}) {
2718: $i--;
2719: } else {
1.364 www 2720: if (&put('accesskeys',
2721: { $newkey => '# generated '.localtime().
1.620 albertel 2722: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2723: '; '.$logentry },
2724: $cdom,$cnum) eq 'ok') {
1.344 www 2725: $total++;
2726: }
2727: }
2728: }
1.620 albertel 2729: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2730: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2731: return $total;
2732: }
2733:
2734: # ------------------------------------------------------- Validate an accesskey
2735:
2736: sub validate_access_key {
2737: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2738: $cdom=
1.620 albertel 2739: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2740: $cnum=
1.620 albertel 2741: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2742: $udom=$env{'user.domain'} unless (defined($udom));
2743: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2744: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2745: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2746: }
2747:
2748: # ------------------------------------- Find the section of student in a course
1.652 albertel 2749: sub devalidate_getsection_cache {
2750: my ($udom,$unam,$courseid)=@_;
2751: my $hashid="$udom:$unam:$courseid";
2752: &devalidate_cache_new('getsection',$hashid);
2753: }
1.298 matthew 2754:
1.815 albertel 2755: sub courseid_to_courseurl {
2756: my ($courseid) = @_;
2757: #already url style courseid
2758: return $courseid if ($courseid =~ m{^/});
2759:
2760: if (exists($env{'course.'.$courseid.'.num'})) {
2761: my $cnum = $env{'course.'.$courseid.'.num'};
2762: my $cdom = $env{'course.'.$courseid.'.domain'};
2763: return "/$cdom/$cnum";
2764: }
2765:
2766: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2767: if (exists($courseinfo{'num'})) {
2768: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2769: }
2770:
2771: return undef;
2772: }
2773:
1.298 matthew 2774: sub getsection {
2775: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2776: my $cachetime=1800;
1.551 albertel 2777:
2778: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2779: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2780: if (defined($cached)) { return $result; }
2781:
1.298 matthew 2782: my %Pending;
2783: my %Expired;
2784: #
2785: # Each role can either have not started yet (pending), be active,
2786: # or have expired.
2787: #
2788: # If there is an active role, we are done.
2789: #
2790: # If there is more than one role which has not started yet,
2791: # choose the one which will start sooner
2792: # If there is one role which has not started yet, return it.
2793: #
2794: # If there is more than one expired role, choose the one which ended last.
2795: # If there is a role which has expired, return it.
2796: #
1.815 albertel 2797: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2798: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2799: foreach my $key (keys(%roleshash)) {
1.479 albertel 2800: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2801: my $section=$1;
2802: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2803: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2804: my $now=time;
1.548 albertel 2805: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2806: $Expired{$end}=$section;
2807: next;
2808: }
1.548 albertel 2809: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2810: $Pending{$start}=$section;
2811: next;
2812: }
1.599 albertel 2813: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2814: }
2815: #
2816: # Presumedly there will be few matching roles from the above
2817: # loop and the sorting time will be negligible.
2818: if (scalar(keys(%Pending))) {
2819: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2820: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2821: }
2822: if (scalar(keys(%Expired))) {
2823: my @sorted = sort {$a <=> $b} keys(%Expired);
2824: my $time = pop(@sorted);
1.599 albertel 2825: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2826: }
1.599 albertel 2827: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2828: }
1.70 www 2829:
1.599 albertel 2830: sub save_cache {
2831: &purge_remembered();
1.722 albertel 2832: #&Apache::loncommon::validate_page();
1.620 albertel 2833: undef(%env);
1.780 albertel 2834: undef($env_loaded);
1.599 albertel 2835: }
1.452 albertel 2836:
1.599 albertel 2837: my $to_remember=-1;
2838: my %remembered;
2839: my %accessed;
2840: my $kicks=0;
2841: my $hits=0;
1.849 albertel 2842: sub make_key {
2843: my ($name,$id) = @_;
1.872 albertel 2844: if (length($id) > 65
2845: && length(&escape($id)) > 200) {
2846: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2847: }
1.849 albertel 2848: return &escape($name.':'.$id);
2849: }
2850:
1.599 albertel 2851: sub devalidate_cache_new {
2852: my ($name,$id,$debug) = @_;
2853: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2854: my $remembered_id=$name.':'.$id;
1.849 albertel 2855: $id=&make_key($name,$id);
1.599 albertel 2856: $memcache->delete($id);
1.1172.2.81 raeburn 2857: delete($remembered{$remembered_id});
2858: delete($accessed{$remembered_id});
1.599 albertel 2859: }
2860:
2861: sub is_cached_new {
2862: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2863: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2864: # keys in %remembered hash, which persists for
2865: # duration of request (no restriction on key length).
2866: if (exists($remembered{$remembered_id})) {
2867: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2868: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2869: $hits++;
1.1172.2.81 raeburn 2870: return ($remembered{$remembered_id},1);
1.599 albertel 2871: }
1.1172.2.81 raeburn 2872: $id=&make_key($name,$id);
1.599 albertel 2873: my $value = $memcache->get($id);
2874: if (!(defined($value))) {
2875: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2876: return (undef,undef);
1.416 albertel 2877: }
1.599 albertel 2878: if ($value eq '__undef__') {
2879: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2880: $value=undef;
2881: }
1.1172.2.81 raeburn 2882: &make_room($remembered_id,$value,$debug);
1.599 albertel 2883: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2884: return ($value,1);
2885: }
2886:
2887: sub do_cache_new {
2888: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2889: my $remembered_id=$name.':'.$id;
1.849 albertel 2890: $id=&make_key($name,$id);
1.599 albertel 2891: my $setvalue=$value;
2892: if (!defined($setvalue)) {
2893: $setvalue='__undef__';
2894: }
1.623 albertel 2895: if (!defined($time) ) {
2896: $time=600;
2897: }
1.599 albertel 2898: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2899: my $result = $memcache->set($id,$setvalue,$time);
2900: if (! $result) {
1.872 albertel 2901: &logthis("caching of id -> $id failed");
1.910 albertel 2902: $memcache->disconnect_all();
1.872 albertel 2903: }
1.600 albertel 2904: # need to make a copy of $value
1.1172.2.81 raeburn 2905: &make_room($remembered_id,$value,$debug);
1.599 albertel 2906: return $value;
2907: }
2908:
2909: sub make_room {
1.1172.2.81 raeburn 2910: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2911:
1.1172.2.81 raeburn 2912: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2913: : $value;
1.599 albertel 2914: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2915: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2916: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2917: my $to_kick;
2918: my $max_time=0;
2919: foreach my $other (keys(%accessed)) {
2920: if (&tv_interval($accessed{$other}) > $max_time) {
2921: $to_kick=$other;
2922: $max_time=&tv_interval($accessed{$other});
2923: }
2924: }
2925: delete($remembered{$to_kick});
2926: delete($accessed{$to_kick});
2927: $kicks++;
2928: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2929: return;
2930: }
2931:
1.599 albertel 2932: sub purge_remembered {
1.604 albertel 2933: #&logthis("Tossing ".scalar(keys(%remembered)));
2934: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2935: undef(%remembered);
2936: undef(%accessed);
1.428 albertel 2937: }
1.70 www 2938: # ------------------------------------- Read an entry from a user's environment
2939:
2940: sub userenvironment {
2941: my ($udom,$unam,@what)=@_;
1.976 raeburn 2942: my $items;
2943: foreach my $item (@what) {
2944: $items.=&escape($item).'&';
2945: }
2946: $items=~s/\&$//;
1.70 www 2947: my %returnhash=();
1.1009 raeburn 2948: my $uhome = &homeserver($unam,$udom);
2949: unless ($uhome eq 'no_host') {
2950: my @answer=split(/\&/,
2951: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2952: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2953: return %returnhash;
2954: }
1.1009 raeburn 2955: my $i;
2956: for ($i=0;$i<=$#what;$i++) {
2957: $returnhash{$what[$i]}=&unescape($answer[$i]);
2958: }
1.70 www 2959: }
2960: return %returnhash;
1.1 albertel 2961: }
2962:
1.617 albertel 2963: # ---------------------------------------------------------- Get a studentphoto
2964: sub studentphoto {
2965: my ($udom,$unam,$ext) = @_;
2966: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2967: if (defined($env{'request.course.id'})) {
1.708 raeburn 2968: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2969: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2970: return(&retrievestudentphoto($udom,$unam,$ext));
2971: } else {
2972: my ($result,$perm_reqd)=
1.707 albertel 2973: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2974: if ($result eq 'ok') {
2975: if (!($perm_reqd eq 'yes')) {
2976: return(&retrievestudentphoto($udom,$unam,$ext));
2977: }
2978: }
2979: }
2980: }
2981: } else {
2982: my ($result,$perm_reqd) =
1.707 albertel 2983: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2984: if ($result eq 'ok') {
2985: if (!($perm_reqd eq 'yes')) {
2986: return(&retrievestudentphoto($udom,$unam,$ext));
2987: }
2988: }
2989: }
2990: return '/adm/lonKaputt/lonlogo_broken.gif';
2991: }
2992:
2993: sub retrievestudentphoto {
2994: my ($udom,$unam,$ext,$type) = @_;
2995: my $home=&Apache::lonnet::homeserver($unam,$udom);
2996: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2997: if ($ret eq 'ok') {
2998: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2999: if ($type eq 'thumbnail') {
3000: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3001: }
3002: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3003: return $tokenurl;
3004: } else {
3005: if ($type eq 'thumbnail') {
3006: return '/adm/lonKaputt/genericstudent_tn.gif';
3007: } else {
3008: return '/adm/lonKaputt/lonlogo_broken.gif';
3009: }
1.617 albertel 3010: }
3011: }
3012:
1.263 www 3013: # -------------------------------------------------------------------- New chat
3014:
3015: sub chatsend {
1.724 raeburn 3016: my ($newentry,$anon,$group)=@_;
1.620 albertel 3017: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3018: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3019: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3020: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3021: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3022: &escape($newentry)).':'.$group,$chome);
1.292 www 3023: }
3024:
3025: # ------------------------------------------ Find current version of a resource
3026:
3027: sub getversion {
3028: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3029: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3030: return ¤tversion(&filelocation('',$fname));
3031: }
3032:
3033: sub currentversion {
3034: my $fname=shift;
3035: my $author=$fname;
3036: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3037: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3038: my $home=&homeserver($uname,$udom);
1.292 www 3039: if ($home eq 'no_host') {
3040: return -1;
3041: }
1.1112 www 3042: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3043: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3044: return -1;
3045: }
1.1112 www 3046: return $answer;
1.263 www 3047: }
3048:
1.1111 www 3049: #
3050: # Return special version number of resource if set by override, empty otherwise
3051: #
3052: sub usedversion {
3053: my $fname=shift;
3054: unless ($fname) { $fname=$env{'request.uri'}; }
3055: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3056: if ($urlversion) { return $urlversion; }
3057: return '';
3058: }
3059:
1.1 albertel 3060: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3061:
1.1 albertel 3062: sub subscribe {
3063: my $fname=shift;
1.761 raeburn 3064: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3065: $fname=~s/[\n\r]//g;
1.1 albertel 3066: my $author=$fname;
3067: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3068: my ($udom,$uname)=split(/\//,$author);
3069: my $home=homeserver($uname,$udom);
1.335 albertel 3070: if ($home eq 'no_host') {
3071: return 'not_found';
1.1 albertel 3072: }
3073: my $answer=reply("sub:$fname",$home);
1.64 www 3074: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3075: $answer.=' by '.$home;
3076: }
1.1 albertel 3077: return $answer;
3078: }
3079:
1.8 www 3080: # -------------------------------------------------------------- Replicate file
3081:
3082: sub repcopy {
3083: my $filename=shift;
1.23 www 3084: $filename=~s/\/+/\//g;
1.1142 raeburn 3085: my $londocroot = $perlvar{'lonDocRoot'};
3086: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3087: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3088: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3089: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3090: return &repcopy_userfile($filename);
3091: }
1.532 albertel 3092: $filename=~s/[\n\r]//g;
1.8 www 3093: my $transname="$filename.in.transfer";
1.828 www 3094: # FIXME: this should flock
1.607 raeburn 3095: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3096: my $remoteurl=subscribe($filename);
1.64 www 3097: if ($remoteurl =~ /^con_lost by/) {
3098: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3099: return 'unavailable';
1.8 www 3100: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3101: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3102: return 'not_found';
1.64 www 3103: } elsif ($remoteurl =~ /^rejected by/) {
3104: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3105: return 'forbidden';
1.20 www 3106: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3107: return 'ok';
1.8 www 3108: } else {
1.290 www 3109: my $author=$filename;
3110: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3111: my ($udom,$uname)=split(/\//,$author);
3112: my $home=homeserver($uname,$udom);
3113: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3114: my @parts=split(/\//,$filename);
3115: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3116: if ($path ne "$londocroot/res") {
1.8 www 3117: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3118: return 'bad_request';
1.8 www 3119: }
3120: my $count;
3121: for ($count=5;$count<$#parts;$count++) {
3122: $path.="/$parts[$count]";
3123: if ((-e $path)!=1) {
3124: mkdir($path,0777);
3125: }
3126: }
3127: my $ua=new LWP::UserAgent;
3128: my $request=new HTTP::Request('GET',"$remoteurl");
3129: my $response=$ua->request($request,$transname);
3130: if ($response->is_error()) {
3131: unlink($transname);
3132: my $message=$response->status_line;
1.672 albertel 3133: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3134: ." LWP get: $message: $filename</font>");
1.607 raeburn 3135: return 'unavailable';
1.8 www 3136: } else {
1.16 www 3137: if ($remoteurl!~/\.meta$/) {
3138: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3139: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3140: if ($mresponse->is_error()) {
3141: unlink($filename.'.meta');
3142: &logthis(
1.672 albertel 3143: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3144: }
3145: }
1.8 www 3146: rename($transname,$filename);
1.607 raeburn 3147: return 'ok';
1.8 www 3148: }
1.290 www 3149: }
1.8 www 3150: }
1.330 www 3151: }
3152:
1.1172.2.124 raeburn 3153: # ------------------------------------------------- Unsubscribe from a resource
3154:
3155: sub unsubscribe {
3156: my ($fname) = @_;
3157: my $answer;
3158: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3159: $fname=~s/[\n\r]//g;
3160: my $author=$fname;
3161: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3162: my ($udom,$uname)=split(/\//,$author);
3163: my $home=homeserver($uname,$udom);
3164: if ($home eq 'no_host') {
3165: $answer = 'no_host';
3166: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3167: $answer = 'home';
3168: } else {
1.1172.2.125 raeburn 3169: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3170: }
3171: return $answer;
3172: }
3173:
1.330 www 3174: # ------------------------------------------------ Get server side include body
3175: sub ssi_body {
1.381 albertel 3176: my ($filelink,%form)=@_;
1.606 matthew 3177: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3178: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3179: }
1.953 www 3180: my $output='';
3181: my $response;
1.980 raeburn 3182: if ($filelink=~/^https?\:/) {
1.954 raeburn 3183: ($output,$response)=&externalssi($filelink);
1.953 www 3184: } else {
1.1004 droeschl 3185: $filelink .= $filelink=~/\?/ ? '&' : '?';
3186: $filelink .= 'inhibitmenu=yes';
1.953 www 3187: ($output,$response)=&ssi($filelink,%form);
3188: }
1.778 albertel 3189: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3190: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3191: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3192: if (wantarray) {
3193: return ($output, $response);
3194: } else {
3195: return $output;
3196: }
1.8 www 3197: }
3198:
1.15 www 3199: # --------------------------------------------------------- Server Side Include
3200:
1.782 albertel 3201: sub absolute_url {
1.1172.2.145 raeburn 3202: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3203: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3204: if ($host_name eq '') {
3205: $host_name = $ENV{'SERVER_NAME'};
3206: }
1.1172.2.145 raeburn 3207: if ($unalias) {
3208: my $alias = &get_proxy_alias();
3209: if ($alias eq $host_name) {
3210: my $lonhost = $perlvar{'lonHostID'};
3211: my $hostname = &hostname($lonhost);
3212: my $lcproto;
3213: if (($keep_proto) || ($hostname eq '')) {
3214: $lcproto = $protocol;
3215: } else {
3216: $lcproto = $protocol{$lonhost};
3217: $lcproto = 'http' if ($lcproto ne 'https');
3218: $lcproto .= '://';
3219: }
3220: unless ($hostname eq '') {
3221: return $lcproto.$hostname;
3222: }
3223: }
3224: }
1.782 albertel 3225: return $protocol.$host_name;
3226: }
3227:
1.942 foxr 3228: #
3229: # Server side include.
3230: # Parameters:
3231: # fn Possibly encrypted resource name/id.
3232: # form Hash that describes how the rendering should be done
3233: # and other things.
1.944 foxr 3234: # Returns:
1.950 raeburn 3235: # Scalar context: The content of the response.
3236: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3237: #
1.15 www 3238: sub ssi {
3239:
1.944 foxr 3240: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3241: my ($host,$request,$response);
3242: $host = &absolute_url('',1);
1.711 albertel 3243:
3244: $form{'no_update_last_known'}=1;
1.895 albertel 3245: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3246: if (%form) {
1.1172.2.145 raeburn 3247: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3248: $request->content(join('&',map {
3249: my $name = escape($_);
3250: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3251: ? join("&$name=", map {escape($_) } @{$form{$_}})
3252: : &escape($form{$_}) );
3253: } keys(%form)));
1.23 www 3254: } else {
1.1172.2.145 raeburn 3255: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3256: }
3257:
1.15 www 3258: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3259:
1.1172.2.101 raeburn 3260: if (($env{'request.course.id'}) &&
3261: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3262: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3263: ($form{'grade_symb'} ne '') &&
3264: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3265: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3266: if (LWP::UserAgent->VERSION >= 5.834) {
3267: my $ua=new LWP::UserAgent;
3268: $ua->local_address('127.0.0.1');
3269: $response = $ua->request($request);
3270: } else {
3271: {
3272: require LWP::Protocol::http;
3273: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3274: my $ua=new LWP::UserAgent;
3275: $response = $ua->request($request);
3276: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3277: }
3278: }
3279: } else {
3280: my $ua=new LWP::UserAgent;
3281: $response = $ua->request($request);
3282: }
1.944 foxr 3283: if (wantarray) {
1.1172.2.3 raeburn 3284: return ($response->content, $response);
1.944 foxr 3285: } else {
1.1172.2.3 raeburn 3286: return $response->content;
1.942 foxr 3287: }
1.324 www 3288: }
3289:
3290: sub externalssi {
3291: my ($url)=@_;
3292: my $ua=new LWP::UserAgent;
3293: my $request=new HTTP::Request('GET',$url);
3294: my $response=$ua->request($request);
1.954 raeburn 3295: if (wantarray) {
3296: return ($response->content, $response);
3297: } else {
3298: return $response->content;
3299: }
1.15 www 3300: }
1.254 www 3301:
1.1172.2.98 raeburn 3302: # If the local copy of a replicated resource is outdated, trigger a
3303: # connection from the homeserver to flush the delayed queue. If no update
3304: # happens, remove local copies of outdated resource (and corresponding
3305: # metadata file).
3306:
3307: sub remove_stale_resfile {
3308: my ($url) = @_;
3309: my $removed;
3310: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3311: my $audom = $1;
3312: my $auname = $2;
3313: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3314: my $homeserver = &homeserver($auname,$audom);
3315: unless (($homeserver eq 'no_host') ||
3316: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3317: my $fname = &filelocation('',$url);
3318: if (-e $fname) {
3319: my $hostname = &hostname($homeserver);
3320: if ($hostname) {
1.1172.2.120 raeburn 3321: my $protocol = $protocol{$homeserver};
3322: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3323: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3324: my $ua=new LWP::UserAgent;
3325: $ua->timeout(5);
1.1172.2.98 raeburn 3326: my $request=new HTTP::Request('HEAD',$uri);
3327: my $response=$ua->request($request);
3328: if ($response->is_success()) {
3329: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3330: my $locmodtime = (stat($fname))[9];
3331: if ($locmodtime < $remmodtime) {
3332: my $stale;
3333: my $answer = &reply('pong',$homeserver);
3334: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3335: sleep(0.2);
3336: $locmodtime = (stat($fname))[9];
3337: if ($locmodtime < $remmodtime) {
3338: my $posstransfer = $fname.'.in.transfer';
3339: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3340: $removed = 1;
3341: } else {
3342: $stale = 1;
3343: }
3344: } else {
3345: $removed = 1;
3346: }
3347: } else {
3348: $stale = 1;
3349: }
3350: if ($stale) {
1.1172.2.124 raeburn 3351: if (unlink($fname)) {
3352: if ($uri!~/\.meta$/) {
3353: if (-e $fname.'.meta') {
3354: unlink($fname.'.meta');
3355: }
3356: }
3357: my $unsubresult = &unsubscribe($fname);
3358: unless ($unsubresult eq 'ok') {
3359: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3360: }
3361: $removed = 1;
1.1172.2.98 raeburn 3362: }
3363: }
3364: }
3365: }
3366: }
3367: }
3368: }
3369: }
3370: }
3371: return $removed;
3372: }
3373:
1.492 albertel 3374: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3375:
3376: sub allowuploaded {
3377: my ($srcurl,$url)=@_;
3378: $url=&clutter(&declutter($url));
3379: my $dir=$url;
3380: $dir=~s/\/[^\/]+$//;
3381: my %httpref=();
3382: my $httpurl=&hreflocation('',$url);
3383: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3384: &Apache::lonnet::appenv(\%httpref);
1.254 www 3385: }
1.477 raeburn 3386:
1.1172.2.13 raeburn 3387: #
3388: # Determine if the current user should be able to edit a particular resource,
3389: # when viewing in course context.
3390: # (a) When viewing resource used to determine if "Edit" item is included in
3391: # Functions.
3392: # (b) When displaying folder contents in course editor, used to determine if
3393: # "Edit" link will be displayed alongside resource.
3394: #
3395: # input: six args -- filename (decluttered), course number, course domain,
3396: # url, symb (if registered) and group (if this is a group
3397: # item -- e.g., bulletin board, group page etc.).
3398: # output: array of five scalars --
3399: # $cfile -- url for file editing if editable on current server
3400: # $home -- homeserver of resource (i.e., for author if published,
3401: # or course if uploaded.).
3402: # $switchserver -- 1 if server switch will be needed.
3403: # $forceedit -- 1 if icon/link should be to go to edit mode
3404: # $forceview -- 1 if icon/link should be to go to view mode
3405: #
3406:
3407: sub can_edit_resource {
3408: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3409: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3410: #
3411: # For aboutme pages user can only edit his/her own.
3412: #
3413: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3414: my ($sdom,$sname) = ($1,$2);
3415: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3416: $home = $env{'user.home'};
3417: $cfile = $resurl;
3418: if ($env{'form.forceedit'}) {
3419: $forceview = 1;
3420: } else {
3421: $forceedit = 1;
3422: }
3423: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3424: } else {
3425: return;
3426: }
3427: }
3428:
3429: if ($env{'request.course.id'}) {
3430: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3431: if ($group ne '') {
3432: # if this is a group homepage or group bulletin board, check group privs
3433: my $allowed = 0;
3434: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3435: if ((&allowed('mdg',$env{'request.course.id'}.
3436: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3437: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3438: $allowed = 1;
3439: }
3440: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3441: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3442: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3443: $allowed = 1;
3444: }
3445: }
3446: if ($allowed) {
3447: $home=&homeserver($cnum,$cdom);
3448: if ($env{'form.forceedit'}) {
3449: $forceview = 1;
3450: } else {
3451: $forceedit = 1;
3452: }
3453: $cfile = $resurl;
3454: } else {
3455: return;
3456: }
3457: } else {
1.1172.2.15 raeburn 3458: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3459: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3460: return;
3461: }
3462: } elsif (!$crsedit) {
1.1172.2.148 raeburn 3463: if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1172.2.13 raeburn 3464: #
3465: # No edit allowed where CC has switched to student role.
3466: #
1.1172.2.148 raeburn 3467: return;
3468: } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
3469: ($resurl =~ m{^/res/lib/templates/})) {
3470: return;
3471: }
1.1172.2.13 raeburn 3472: }
3473: }
3474: }
3475:
3476: if ($file ne '') {
3477: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3478: if (&is_course_upload($file,$cnum,$cdom)) {
3479: $uploaded = 1;
3480: $incourse = 1;
3481: if ($file =~/\.(htm|html|css|js|txt)$/) {
3482: $cfile = &hreflocation('',$file);
3483: if ($env{'form.forceedit'}) {
3484: $forceview = 1;
3485: } else {
3486: $forceedit = 1;
3487: }
3488: }
3489: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3490: $incourse = 1;
3491: if ($env{'form.forceedit'}) {
3492: $forceview = 1;
3493: } else {
3494: $forceedit = 1;
3495: }
3496: $cfile = $resurl;
3497: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3498: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3499: $incourse = 1;
3500: if ($env{'form.forceedit'}) {
3501: $forceview = 1;
3502: } else {
3503: $forceedit = 1;
3504: }
3505: $cfile = $resurl;
3506: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3507: $incourse = 1;
3508: $cfile = $resurl.'/smpedit';
3509: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3510: $incourse = 1;
3511: if ($env{'form.forceedit'}) {
3512: $forceview = 1;
3513: } else {
3514: $forceedit = 1;
3515: }
3516: $cfile = $resurl;
1.1172.2.122 raeburn 3517: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3518: my ($map,$id,$res) = &decode_symb($symb);
3519: if ($map =~ /\.page$/) {
3520: $incourse = 1;
3521: if ($env{'form.forceedit'}) {
3522: $forceview = 1;
3523: $cfile = $map;
3524: } else {
3525: $forceedit = 1;
3526: $cfile = '/adm/wrapper'.$resurl;
3527: }
3528: }
1.1172.2.15 raeburn 3529: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3530: $incourse = 1;
3531: if ($env{'form.forceedit'}) {
3532: $forceview = 1;
3533: } else {
3534: $forceedit = 1;
3535: }
3536: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3537: }
3538: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3539: my $template = '/res/lib/templates/simpleproblem.problem';
3540: if (&is_on_map($template)) {
3541: $incourse = 1;
3542: $forceview = 1;
3543: $cfile = $template;
3544: }
3545: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3546: $incourse = 1;
3547: if ($env{'form.forceedit'}) {
3548: $forceview = 1;
3549: } else {
3550: $forceedit = 1;
3551: }
3552: $cfile = $resurl;
1.1172.2.13 raeburn 3553: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3554: $incourse = 1;
3555: $forceview = 1;
3556: if ($symb) {
3557: my ($map,$id,$res)=&decode_symb($symb);
3558: $env{'request.symb'} = $symb;
3559: $cfile = &clutter($res);
3560: } else {
3561: $cfile = $env{'form.suppurl'};
3562: $cfile =~ s{^http://}{};
3563: $cfile = '/adm/wrapper/ext/'.$cfile;
3564: }
1.1172.2.31 raeburn 3565: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3566: if ($env{'form.forceedit'}) {
3567: $forceview = 1;
3568: } else {
3569: $forceedit = 1;
3570: }
3571: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3572: }
3573: }
3574: if ($uploaded || $incourse) {
3575: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3576: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3577: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3578: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3579: # Check that the user has permission to edit this resource
3580: my $setpriv = 1;
3581: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3582: if (defined($cfudom)) {
3583: $home=&homeserver($cfuname,$cfudom);
3584: $cfile=$file;
3585: }
3586: }
3587: if (($cfile ne '') && (!$incourse || $uploaded) &&
3588: (($home ne '') && ($home ne 'no_host'))) {
3589: my @ids=¤t_machine_ids();
3590: unless (grep(/^\Q$home\E$/,@ids)) {
3591: $switchserver=1;
3592: }
3593: }
3594: }
3595: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3596: }
3597:
3598: sub is_course_upload {
3599: my ($file,$cnum,$cdom) = @_;
3600: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3601: $uploadpath =~ s{^\/}{};
3602: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3603: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3604: return 1;
3605: }
3606: return;
3607: }
3608:
3609: sub in_course {
3610: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3611: if ($hideprivileged) {
3612: my $skipuser;
1.1172.2.23 raeburn 3613: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3614: my @possdoms = ($cdom);
3615: if ($coursehash{'checkforpriv'}) {
3616: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3617: }
3618: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3619: $skipuser = 1;
3620: if ($coursehash{'nothideprivileged'}) {
3621: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3622: my $user;
3623: if ($item =~ /:/) {
3624: $user = $item;
3625: } else {
3626: $user = join(':',split(/[\@]/,$item));
3627: }
3628: if ($user eq $uname.':'.$udom) {
3629: undef($skipuser);
3630: last;
3631: }
3632: }
3633: }
3634: if ($skipuser) {
3635: return 0;
3636: }
3637: }
3638: }
3639: $type ||= 'any';
3640: if (!defined($cdom) || !defined($cnum)) {
3641: my $cid = $env{'request.course.id'};
3642: $cdom = $env{'course.'.$cid.'.domain'};
3643: $cnum = $env{'course.'.$cid.'.num'};
3644: }
3645: my $typesref;
3646: if (($type eq 'any') || ($type eq 'all')) {
3647: $typesref = ['active','previous','future'];
3648: } elsif ($type eq 'previous' || $type eq 'future') {
3649: $typesref = [$type];
3650: }
3651: my %roles = &get_my_roles($uname,$udom,'userroles',
3652: $typesref,undef,[$cdom]);
3653: my ($tmp) = keys(%roles);
3654: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3655: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3656: if (@course_roles > 0) {
3657: return 1;
3658: }
3659: return 0;
3660: }
3661:
1.478 albertel 3662: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3663: # input: action, courseID, current domain, intended
1.637 raeburn 3664: # path to file, source of file, instruction to parse file for objects,
3665: # ref to hash for embedded objects,
3666: # ref to hash for codebase of java objects.
1.1095 raeburn 3667: # reference to scalar to accommodate mime type determined
3668: # from File::MMagic if $parser = parse.
1.637 raeburn 3669: #
1.485 raeburn 3670: # output: url to file (if action was uploaddoc),
3671: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3672: #
1.478 albertel 3673: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3674: # course.
1.477 raeburn 3675: #
1.478 albertel 3676: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3677: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3678: # course's home server.
1.477 raeburn 3679: #
1.478 albertel 3680: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3681: # be copied from $source (current location) to
3682: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3683: # and will then be copied to
3684: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3685: # course's home server.
1.485 raeburn 3686: #
1.481 raeburn 3687: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3688: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3689: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3690: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3691: # in course's home server.
1.637 raeburn 3692: #
1.477 raeburn 3693:
3694: sub process_coursefile {
1.1095 raeburn 3695: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3696: $mimetype)=@_;
1.477 raeburn 3697: my $fetchresult;
1.638 albertel 3698: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3699: if ($action eq 'propagate') {
1.638 albertel 3700: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3701: $home);
1.481 raeburn 3702: } else {
1.477 raeburn 3703: my $fpath = '';
3704: my $fname = $file;
1.478 albertel 3705: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3706: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3707: my $filepath = &build_filepath($fpath);
1.481 raeburn 3708: if ($action eq 'copy') {
3709: if ($source eq '') {
3710: $fetchresult = 'no source file';
3711: return $fetchresult;
3712: } else {
3713: my $destination = $filepath.'/'.$fname;
3714: rename($source,$destination);
3715: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3716: $home);
1.481 raeburn 3717: }
3718: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3719: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3720: print $fh $env{'form.'.$source};
1.481 raeburn 3721: close($fh);
1.637 raeburn 3722: if ($parser eq 'parse') {
1.1024 raeburn 3723: my $mm = new File::MMagic;
1.1095 raeburn 3724: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3725: if ($type eq 'text/html') {
1.1024 raeburn 3726: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3727: unless ($parse_result eq 'ok') {
3728: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3729: }
1.637 raeburn 3730: }
1.1095 raeburn 3731: if (ref($mimetype)) {
3732: $$mimetype = $type;
3733: }
1.637 raeburn 3734: }
1.477 raeburn 3735: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3736: $home);
1.481 raeburn 3737: if ($fetchresult eq 'ok') {
3738: return '/uploaded/'.$fpath.'/'.$fname;
3739: } else {
3740: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3741: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3742: return '/adm/notfound.html';
3743: }
1.477 raeburn 3744: }
3745: }
1.485 raeburn 3746: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3747: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3748: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3749: }
3750: return $fetchresult;
3751: }
3752:
1.637 raeburn 3753: sub build_filepath {
3754: my ($fpath) = @_;
3755: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3756: unless ($fpath eq '') {
3757: my @parts=split('/',$fpath);
3758: foreach my $part (@parts) {
3759: $filepath.= '/'.$part;
3760: if ((-e $filepath)!=1) {
3761: mkdir($filepath,0777);
3762: }
3763: }
3764: }
3765: return $filepath;
3766: }
3767:
3768: sub store_edited_file {
1.638 albertel 3769: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3770: my $file = $primary_url;
3771: $file =~ s#^/uploaded/$docudom/$docuname/##;
3772: my $fpath = '';
3773: my $fname = $file;
3774: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3775: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3776: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3777: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3778: print $fh $content;
3779: close($fh);
1.638 albertel 3780: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3781: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3782: $home);
1.637 raeburn 3783: if ($$fetchresult eq 'ok') {
3784: return '/uploaded/'.$fpath.'/'.$fname;
3785: } else {
1.638 albertel 3786: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3787: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3788: return '/adm/notfound.html';
3789: }
3790: }
3791:
1.531 albertel 3792: sub clean_filename {
1.831 albertel 3793: my ($fname,$args)=@_;
1.315 www 3794: # Replace Windows backslashes by forward slashes
1.257 www 3795: $fname=~s/\\/\//g;
1.831 albertel 3796: if (!$args->{'keep_path'}) {
3797: # Get rid of everything but the actual filename
3798: $fname=~s/^.*\/([^\/]+)$/$1/;
3799: }
1.315 www 3800: # Replace spaces by underscores
3801: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3802: # Transliterate non-ascii text to ascii
3803: my $lang = &Apache::lonlocal::current_language();
3804: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3805: # Replace all other weird characters by nothing
1.831 albertel 3806: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3807: # Replace all .\d. sequences with _\d. so they no longer look like version
3808: # numbers
3809: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3810: # Replace three or more adjacent underscores with one for consistency
3811: # with loncfile::filename_check() so complete url can be extracted by
3812: # lonnet::decode_symb()
3813: $fname=~s/_{3,}/_/g;
1.531 albertel 3814: return $fname;
3815: }
1.1172.2.110 raeburn 3816:
1.1051 raeburn 3817: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3818: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3819: # image with the same aspect ratio as the original, but with dimensions which do
3820: # not exceed $resizewidth and $resizeheight.
3821:
1.984 neumanie 3822: sub resizeImage {
1.1051 raeburn 3823: my ($img_path,$resizewidth,$resizeheight) = @_;
3824: my $ima = Image::Magick->new;
3825: my $resized;
3826: if (-e $img_path) {
3827: $ima->Read($img_path);
3828: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3829: my $width = $ima->Get('width');
3830: my $height = $ima->Get('height');
3831: if ($width > $resizewidth) {
3832: my $factor = $width/$resizewidth;
3833: my $newheight = $height/$factor;
3834: $ima->Scale(width=>$resizewidth,height=>$newheight);
3835: $resized = 1;
3836: }
3837: }
3838: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3839: my $width = $ima->Get('width');
3840: my $height = $ima->Get('height');
3841: if ($height > $resizeheight) {
3842: my $factor = $height/$resizeheight;
3843: my $newwidth = $width/$factor;
3844: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3845: $resized = 1;
3846: }
3847: }
3848: if ($resized) {
3849: $ima->Write($img_path);
3850: }
3851: }
3852: return;
1.977 amueller 3853: }
3854:
1.608 albertel 3855: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3856: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3857: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3858: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3859: # canceloverwrite, scantron or ''.
1.1090 raeburn 3860: # if 'coursedoc': upload to the current course
3861: # if 'existingfile': write file to tmp/overwrites directory
3862: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3863: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3864: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3865: # $parser - instruction to parse file for objects ($parser = parse) or
3866: # if context is 'scantron', $parser is hashref of csv column mapping
3867: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3868: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3869: # $allfiles - reference to hash for embedded objects
3870: # $codebase - reference to hash for codebase of java objects
3871: # $desuname - username for permanent storage of uploaded file
3872: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3873: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3874: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3875: # $resizewidth - width (pixels) to which to resize uploaded image
3876: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3877: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3878: # from File::MMagic.
1.858 raeburn 3879: #
1.686 albertel 3880: # output: url of file in userspace, or error: <message>
3881: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3882:
1.531 albertel 3883: sub userfileupload {
1.1090 raeburn 3884: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3885: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3886: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3887: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3888: $fname=&clean_filename($fname);
1.1090 raeburn 3889: # See if there is anything left
1.257 www 3890: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3891: # If filename now begins with a . prepend unix timestamp _ milliseconds
3892: if ($fname =~ /^\./) {
3893: my ($s,$usec) = &gettimeofday();
3894: while (length($usec) < 6) {
3895: $usec = '0'.$usec;
3896: }
3897: $fname = $s.'_'.substr($usec,0,3).$fname;
3898: }
1.1090 raeburn 3899: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3900: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3901: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3902: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3903: my $now = time;
1.1090 raeburn 3904: my $filepath;
1.1095 raeburn 3905: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3906: $filepath = 'tmp/helprequests/'.$now;
3907: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3908: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3909: '_'.$env{'user.domain'}.'/pending';
3910: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3911: my ($docuname,$docudom);
1.1172.2.96 raeburn 3912: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3913: $docudom = $destudom;
3914: } else {
3915: $docudom = $env{'user.domain'};
3916: }
1.1172.2.96 raeburn 3917: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3918: $docuname = $destuname;
3919: } else {
3920: $docuname = $env{'user.name'};
3921: }
3922: if (exists($env{'form.group'})) {
3923: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3924: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3925: }
3926: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3927: if ($context eq 'canceloverwrite') {
3928: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3929: if (-e $tempfile) {
3930: my @info = stat($tempfile);
3931: if ($info[9] eq $env{'form.timestamp'}) {
3932: unlink($tempfile);
3933: }
3934: }
3935: return;
1.523 raeburn 3936: }
3937: }
1.1090 raeburn 3938: # Create the directory if not present
1.741 raeburn 3939: my @parts=split(/\//,$filepath);
3940: my $fullpath = $perlvar{'lonDaemons'};
3941: for (my $i=0;$i<@parts;$i++) {
3942: $fullpath .= '/'.$parts[$i];
3943: if ((-e $fullpath)!=1) {
3944: mkdir($fullpath,0777);
3945: }
3946: }
1.1172.2.96 raeburn 3947: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3948: print $fh $env{'form.'.$formname};
3949: close($fh);
1.1090 raeburn 3950: if ($context eq 'existingfile') {
3951: my @info = stat($fullpath.'/'.$fname);
3952: return ($fullpath.'/'.$fname,$info[9]);
3953: } else {
3954: return $fullpath.'/'.$fname;
3955: }
1.523 raeburn 3956: }
1.995 raeburn 3957: if ($subdir eq 'scantron') {
3958: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3959: } else {
1.995 raeburn 3960: $fname="$subdir/$fname";
3961: }
1.1090 raeburn 3962: if ($context eq 'coursedoc') {
1.638 albertel 3963: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3964: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3965: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3966: return &finishuserfileupload($docuname,$docudom,
3967: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3968: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3969: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3970: } else {
1.1172.2.21 raeburn 3971: if ($env{'form.folder'}) {
3972: $fname=$env{'form.folder'}.'/'.$fname;
3973: }
1.638 albertel 3974: return &process_coursefile('uploaddoc',$docuname,$docudom,
3975: $fname,$formname,$parser,
1.1095 raeburn 3976: $allfiles,$codebase,$mimetype);
1.481 raeburn 3977: }
1.719 banghart 3978: } elsif (defined($destuname)) {
3979: my $docuname=$destuname;
3980: my $docudom=$destudom;
1.860 raeburn 3981: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3982: $parser,$allfiles,$codebase,
1.1051 raeburn 3983: $thumbwidth,$thumbheight,
1.1095 raeburn 3984: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3985: } else {
1.638 albertel 3986: my $docuname=$env{'user.name'};
3987: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3988: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3989: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3990: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3991: }
1.860 raeburn 3992: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3993: $parser,$allfiles,$codebase,
1.1051 raeburn 3994: $thumbwidth,$thumbheight,
1.1095 raeburn 3995: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3996: }
1.271 www 3997: }
3998:
3999: sub finishuserfileupload {
1.860 raeburn 4000: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4001: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4002: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4003: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4004:
1.860 raeburn 4005: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4006: $file=$fname;
4007: if ($fname=~m|/|) {
4008: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4009: $path.=$fnamepath.'/';
4010: }
1.259 www 4011: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4012: my $count;
4013: for ($count=4;$count<=$#parts;$count++) {
4014: $filepath.="/$parts[$count]";
4015: if ((-e $filepath)!=1) {
4016: mkdir($filepath,0777);
4017: }
4018: }
1.984 neumanie 4019:
1.258 www 4020: # Save the file
4021: {
1.1172.2.96 raeburn 4022: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4023: &logthis('Failed to create '.$filepath.'/'.$file);
4024: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4025: return '/adm/notfound.html';
4026: }
1.1090 raeburn 4027: if ($context eq 'overwrite') {
1.1117 foxr 4028: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4029: my $target = $filepath.'/'.$file;
4030: if (-e $source) {
4031: my @info = stat($source);
4032: if ($info[9] eq $env{'form.timestamp'}) {
4033: unless (&File::Copy::move($source,$target)) {
4034: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4035: return "Moving from $source failed";
4036: }
4037: } else {
4038: return "Temporary file: $source had unexpected date/time for last modification";
4039: }
4040: } else {
4041: return "Temporary file: $source missing";
4042: }
4043: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4044: &logthis('Failed to write to '.$filepath.'/'.$file);
4045: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4046: return '/adm/notfound.html';
4047: }
1.570 albertel 4048: close(FH);
1.1051 raeburn 4049: if ($resizewidth && $resizeheight) {
4050: my $mm = new File::MMagic;
4051: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4052: if ($mime_type =~ m{^image/}) {
4053: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4054: }
1.977 amueller 4055: }
1.258 www 4056: }
1.1152 raeburn 4057: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4058: if (ref($mimetype)) {
4059: if ($$mimetype eq '') {
4060: my $mm = new File::MMagic;
4061: my $type = $mm->checktype_filename($filepath.'/'.$file);
4062: $$mimetype = $type;
4063: }
4064: }
4065: }
1.1172.2.109 raeburn 4066: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4067: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4068: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4069: $allfiles,$codebase);
4070: unless ($parse_result eq 'ok') {
4071: &logthis('Failed to parse '.$filepath.$file.
4072: ' for embedded media: '.$parse_result);
4073: }
1.637 raeburn 4074: }
1.1172.2.109 raeburn 4075: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4076: my $format = $env{'form.scantron_format'};
4077: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4078: }
1.860 raeburn 4079: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4080: my $input = $filepath.'/'.$file;
4081: my $output = $filepath.'/'.'tn-'.$file;
4082: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4083: my @args = ('convert','-sample',$thumbsize,$input,$output);
4084: system({$args[0]} @args);
1.860 raeburn 4085: if (-e $filepath.'/'.'tn-'.$file) {
4086: $fetchthumb = 1;
4087: }
4088: }
1.858 raeburn 4089:
1.259 www 4090: # Notify homeserver to grep it
4091: #
1.984 neumanie 4092: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4093: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4094: if ($fetchresult eq 'ok') {
1.860 raeburn 4095: if ($fetchthumb) {
4096: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4097: if ($thumbresult ne 'ok') {
4098: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4099: $docuhome.': '.$thumbresult);
4100: }
4101: }
1.259 www 4102: #
1.258 www 4103: # Return the URL to it
1.494 albertel 4104: return '/uploaded/'.$path.$file;
1.263 www 4105: } else {
1.494 albertel 4106: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4107: ': '.$fetchresult);
1.263 www 4108: return '/adm/notfound.html';
1.858 raeburn 4109: }
1.493 albertel 4110: }
4111:
1.637 raeburn 4112: sub extract_embedded_items {
1.961 raeburn 4113: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4114: my @state = ();
1.1164 raeburn 4115: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4116: my %javafiles = (
4117: codebase => '',
4118: code => '',
4119: archive => ''
4120: );
4121: my %mediafiles = (
4122: src => '',
4123: movie => '',
4124: );
1.648 raeburn 4125: my $p;
4126: if ($content) {
4127: $p = HTML::LCParser->new($content);
4128: } else {
1.961 raeburn 4129: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4130: }
1.641 albertel 4131: while (my $t=$p->get_token()) {
1.640 albertel 4132: if ($t->[0] eq 'S') {
4133: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4134: push(@state, $tagname);
1.648 raeburn 4135: if (lc($tagname) eq 'allow') {
4136: &add_filetype($allfiles,$attr->{'src'},'src');
4137: }
1.640 albertel 4138: if (lc($tagname) eq 'img') {
4139: &add_filetype($allfiles,$attr->{'src'},'src');
4140: }
1.886 albertel 4141: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4142: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4143: &add_filetype($allfiles,$attr->{'href'},'href');
4144: }
1.886 albertel 4145: }
1.645 raeburn 4146: if (lc($tagname) eq 'script') {
1.1164 raeburn 4147: my $src;
1.645 raeburn 4148: if ($attr->{'archive'} =~ /\.jar$/i) {
4149: &add_filetype($allfiles,$attr->{'archive'},'archive');
4150: } else {
1.1164 raeburn 4151: if ($attr->{'src'} ne '') {
4152: $src = $attr->{'src'};
4153: &add_filetype($allfiles,$src,'src');
4154: }
4155: }
4156: my $text = $p->get_trimmed_text();
4157: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4158: my @swfargs = split(/,/,$1);
4159: foreach my $item (@swfargs) {
4160: $item =~ s/["']//g;
4161: $item =~ s/^\s+//;
4162: $item =~ s/\s+$//;
4163: }
4164: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4165: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4166: push(@{$related{$swfargs[0]}},$swfargs[2]);
4167: } else {
4168: $related{$swfargs[0]} = [$swfargs[2]];
4169: }
4170: }
1.645 raeburn 4171: }
4172: }
4173: if (lc($tagname) eq 'link') {
4174: if (lc($attr->{'rel'}) eq 'stylesheet') {
4175: &add_filetype($allfiles,$attr->{'href'},'href');
4176: }
4177: }
1.640 albertel 4178: if (lc($tagname) eq 'object' ||
4179: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4180: foreach my $item (keys(%javafiles)) {
4181: $javafiles{$item} = '';
4182: }
1.1164 raeburn 4183: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4184: $lastids{lc($tagname)} = $attr->{'id'};
4185: }
1.640 albertel 4186: }
4187: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4188: my $name = lc($attr->{'name'});
4189: foreach my $item (keys(%javafiles)) {
4190: if ($name eq $item) {
4191: $javafiles{$item} = $attr->{'value'};
4192: last;
4193: }
4194: }
1.1164 raeburn 4195: my $pathfrom;
1.640 albertel 4196: foreach my $item (keys(%mediafiles)) {
4197: if ($name eq $item) {
1.1164 raeburn 4198: $pathfrom = $attr->{'value'};
4199: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4200: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4201: last;
4202: }
4203: }
1.1164 raeburn 4204: if ($name eq 'flashvars') {
4205: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4206: }
4207: if ($pathfrom ne '') {
4208: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4209: $pathfrom);
4210: }
1.640 albertel 4211: }
4212: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4213: foreach my $item (keys(%javafiles)) {
4214: if ($attr->{$item}) {
4215: $javafiles{$item} = $attr->{$item};
4216: last;
4217: }
4218: }
4219: foreach my $item (keys(%mediafiles)) {
4220: if ($attr->{$item}) {
4221: &add_filetype($allfiles,$attr->{$item},$item);
4222: last;
4223: }
4224: }
1.1164 raeburn 4225: if (lc($tagname) eq 'embed') {
4226: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4227: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4228: $attr->{'src'});
4229: }
4230: }
1.640 albertel 4231: }
1.1172.2.35 raeburn 4232: if (lc($tagname) eq 'iframe') {
4233: my $src = $attr->{'src'} ;
4234: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4235: &add_filetype($allfiles,$src,'src');
4236: } elsif ($src =~ m{^/}) {
4237: if ($env{'request.course.id'}) {
4238: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4239: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4240: my $url = &hreflocation('',$fullpath);
4241: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4242: my $relpath = $1;
4243: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4244: &add_filetype($allfiles,$1,'src');
4245: }
4246: }
4247: }
4248: }
4249: }
1.1164 raeburn 4250: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4251: pop(@state);
1.1164 raeburn 4252: }
1.640 albertel 4253: } elsif ($t->[0] eq 'E') {
4254: my ($tagname) = ($t->[1]);
4255: if ($javafiles{'codebase'} ne '') {
4256: $javafiles{'codebase'} .= '/';
4257: }
4258: if (lc($tagname) eq 'applet' ||
4259: lc($tagname) eq 'object' ||
4260: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4261: ) {
4262: foreach my $item (keys(%javafiles)) {
4263: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4264: my $file=$javafiles{'codebase'}.$javafiles{$item};
4265: &add_filetype($allfiles,$file,$item);
4266: }
4267: }
4268: }
4269: pop @state;
4270: }
4271: }
1.1164 raeburn 4272: foreach my $id (sort(keys(%flashvars))) {
4273: if ($shockwave{$id} ne '') {
4274: my @pairs = split(/\&/,$flashvars{$id});
4275: foreach my $pair (@pairs) {
4276: my ($key,$value) = split(/\=/,$pair);
4277: if ($key eq 'thumb') {
4278: &add_filetype($allfiles,$value,$key);
4279: } elsif ($key eq 'content') {
4280: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4281: my ($ext) = ($value =~ /\.([^.]+)$/);
4282: if ($ext ne '') {
4283: &add_filetype($allfiles,$path.$value,$ext);
4284: }
4285: }
4286: }
4287: }
4288: }
1.637 raeburn 4289: return 'ok';
4290: }
4291:
1.639 albertel 4292: sub add_filetype {
4293: my ($allfiles,$file,$type)=@_;
4294: if (exists($allfiles->{$file})) {
4295: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4296: push(@{$allfiles->{$file}}, &escape($type));
4297: }
4298: } else {
4299: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4300: }
4301: }
4302:
1.1164 raeburn 4303: sub embedded_dependency {
4304: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4305: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4306: if (($identifier ne '') &&
4307: (ref($related->{$identifier}) eq 'ARRAY') &&
4308: ($pathfrom ne '')) {
4309: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4310: foreach my $dep (@{$related->{$identifier}}) {
4311: &add_filetype($allfiles,$path.$dep,'object');
4312: }
4313: }
4314: }
4315: return;
4316: }
4317:
1.1172.2.109 raeburn 4318: sub bubblesheet_converter {
4319: my ($cdom,$fullpath,$config,$format) = @_;
4320: if ((&domain($cdom) ne '') &&
4321: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4322: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4323: my (%csvcols,%csvoptions);
4324: if (ref($config->{'fields'}) eq 'HASH') {
4325: %csvcols = %{$config->{'fields'}};
4326: }
4327: if (ref($config->{'options'}) eq 'HASH') {
4328: %csvoptions = %{$config->{'options'}};
4329: }
4330: my %csvbynum = reverse(%csvcols);
4331: my %scantronconf = &get_scantron_config($format,$cdom);
4332: if (keys(%scantronconf)) {
4333: my %bynum = (
4334: $scantronconf{CODEstart} => 'CODEstart',
4335: $scantronconf{IDstart} => 'IDstart',
4336: $scantronconf{PaperID} => 'PaperID',
4337: $scantronconf{FirstName} => 'FirstName',
4338: $scantronconf{LastName} => 'LastName',
4339: $scantronconf{Qstart} => 'Qstart',
4340: );
4341: my @ordered;
4342: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4343: push(@ordered,$bynum{$item});
4344: }
4345: my %mapstart = (
4346: CODEstart => 'CODE',
4347: IDstart => 'ID',
4348: PaperID => 'PaperID',
4349: FirstName => 'FirstName',
4350: LastName => 'LastName',
4351: Qstart => 'FirstQuestion',
4352: );
4353: my %maplength = (
4354: CODEstart => 'CODElength',
4355: IDstart => 'IDlength',
4356: PaperID => 'PaperIDlength',
4357: FirstName => 'FirstNamelength',
4358: LastName => 'LastNamelength',
4359: );
4360: if (open(my $fh,'<',$fullpath)) {
4361: my $output;
4362: my %lettdig = &letter_to_digits();
4363: my %diglett = reverse(%lettdig);
4364: my $numletts = scalar(keys(%lettdig));
4365: my $num = 0;
4366: while (my $line=<$fh>) {
4367: $num ++;
4368: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4369: $line =~ s{[\r\n]+$}{};
4370: my %found;
1.1172.2.143 raeburn 4371: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4372: my ($qstart,$record);
4373: for (my $i=0; $i<@values; $i++) {
4374: if ((($qstart ne '') && ($i > $qstart)) ||
4375: ($csvbynum{$i} eq 'FirstQuestion')) {
4376: if ($values[$i] eq '') {
4377: $values[$i] = $scantronconf{'Qoff'};
4378: } elsif ($scantronconf{'Qon'} eq 'number') {
4379: if ($values[$i] =~ /^[A-Ja-j]$/) {
4380: $values[$i] = $lettdig{uc($values[$i])};
4381: }
4382: } elsif ($scantronconf{'Qon'} eq 'letter') {
4383: if ($values[$i] =~ /^[0-9]$/) {
4384: $values[$i] = $diglett{$values[$i]};
4385: }
4386: } else {
4387: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4388: my $digit;
4389: if ($values[$i] =~ /^[A-Ja-j]$/) {
4390: $digit = $lettdig{uc($values[$i])}-1;
4391: if ($values[$i] eq 'J') {
4392: $digit += $numletts;
4393: }
4394: } elsif ($values[$i] =~ /^[0-9]$/) {
4395: $digit = $values[$i]-1;
4396: if ($values[$i] eq '0') {
4397: $digit += $numletts;
4398: }
4399: }
4400: my $qval='';
4401: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4402: if ($j == $digit) {
4403: $qval .= $scantronconf{'Qon'};
4404: } else {
4405: $qval .= $scantronconf{'Qoff'};
4406: }
4407: }
4408: $values[$i] = $qval;
4409: }
4410: }
4411: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4412: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4413: }
4414: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4415: if ($numblank > 0) {
4416: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4417: }
4418: if ($csvbynum{$i} eq 'FirstQuestion') {
4419: $qstart = $i;
4420: $found{$csvbynum{$i}} = $values[$i];
4421: } else {
4422: $found{'FirstQuestion'} .= $values[$i];
4423: }
4424: } elsif (exists($csvbynum{$i})) {
4425: if ($csvoptions{'rem'}) {
4426: $values[$i] =~ s/^\s+//;
4427: }
4428: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4429: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4430: $values[$i] = '0'.$values[$i];
4431: }
4432: }
4433: $found{$csvbynum{$i}} = $values[$i];
4434: }
4435: }
4436: foreach my $item (@ordered) {
4437: my $currlength = 1+length($record);
4438: my $numspaces = $scantronconf{$item} - $currlength;
4439: if ($numspaces > 0) {
4440: $record .= (' ' x $numspaces);
4441: }
4442: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4443: unless ($item eq 'Qstart') {
4444: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4445: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4446: }
4447: }
4448: $record .= $found{$mapstart{$item}};
4449: }
4450: }
4451: $output .= "$record\n";
4452: }
4453: close($fh);
4454: if ($output) {
4455: if (open(my $fh,'>',$fullpath)) {
4456: print $fh $output;
4457: close($fh);
4458: }
4459: }
4460: }
4461: }
4462: return;
4463: }
4464: }
4465:
4466: sub letter_to_digits {
4467: my %lettdig = (
4468: A => 1,
4469: B => 2,
4470: C => 3,
4471: D => 4,
4472: E => 5,
4473: F => 6,
4474: G => 7,
4475: H => 8,
4476: I => 9,
4477: J => 0,
4478: );
4479: return %lettdig;
4480: }
4481:
4482: sub get_scantron_config {
4483: my ($which,$cdom) = @_;
4484: my @lines = &get_scantronformat_file($cdom);
4485: my %config;
4486: #FIXME probably should move to XML it has already gotten a bit much now
4487: foreach my $line (@lines) {
4488: my ($name,$descrip)=split(/:/,$line);
4489: if ($name ne $which ) { next; }
4490: chomp($line);
4491: my @config=split(/:/,$line);
4492: $config{'name'}=$config[0];
4493: $config{'description'}=$config[1];
4494: $config{'CODElocation'}=$config[2];
4495: $config{'CODEstart'}=$config[3];
4496: $config{'CODElength'}=$config[4];
4497: $config{'IDstart'}=$config[5];
4498: $config{'IDlength'}=$config[6];
4499: $config{'Qstart'}=$config[7];
4500: $config{'Qlength'}=$config[8];
4501: $config{'Qoff'}=$config[9];
4502: $config{'Qon'}=$config[10];
4503: $config{'PaperID'}=$config[11];
4504: $config{'PaperIDlength'}=$config[12];
4505: $config{'FirstName'}=$config[13];
4506: $config{'FirstNamelength'}=$config[14];
4507: $config{'LastName'}=$config[15];
4508: $config{'LastNamelength'}=$config[16];
4509: $config{'BubblesPerRow'}=$config[17];
4510: last;
4511: }
4512: return %config;
4513: }
4514:
4515: sub get_scantronformat_file {
4516: my ($cdom) = @_;
4517: if ($cdom eq '') {
4518: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4519: }
4520: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4521: my $gottab = 0;
4522: my @lines;
4523: if (ref($domconfig{'scantron'}) eq 'HASH') {
4524: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4525: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4526: if ($formatfile ne '-1') {
4527: @lines = split("\n",$formatfile,-1);
4528: $gottab = 1;
4529: }
4530: }
4531: }
4532: if (!$gottab) {
4533: my $confname = $cdom.'-domainconfig';
4534: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4535: my $formatfile = &getfile($default);
4536: if ($formatfile ne '-1') {
4537: @lines = split("\n",$formatfile,-1);
4538: $gottab = 1;
4539: }
4540: }
4541: if (!$gottab) {
4542: my @domains = ¤t_machine_domains();
4543: if (grep(/^\Q$cdom\E$/,@domains)) {
4544: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4545: @lines = <$fh>;
4546: close($fh);
4547: }
4548: } else {
4549: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4550: @lines = <$fh>;
4551: close($fh);
4552: }
4553: }
1.1172.2.150! raeburn 4554: chomp(@lines);
1.1172.2.109 raeburn 4555: }
4556: return @lines;
4557: }
4558:
1.493 albertel 4559: sub removeuploadedurl {
1.984 neumanie 4560: my ($url)=@_;
4561: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4562: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4563: }
4564:
4565: sub removeuserfile {
4566: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4567: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4568: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4569: if ($result eq 'ok') {
1.798 raeburn 4570: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4571: my $metafile = $fname.'.meta';
4572: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4573: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4574: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4575: my $sqlresult =
1.823 albertel 4576: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4577: 'portfolio_metadata',$group,
4578: 'delete');
1.798 raeburn 4579: }
4580: }
4581: return $result;
1.257 www 4582: }
1.15 www 4583:
1.530 albertel 4584: sub mkdiruserfile {
4585: my ($docuname,$docudom,$dir)=@_;
4586: my $home=&homeserver($docuname,$docudom);
4587: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4588: }
4589:
1.531 albertel 4590: sub renameuserfile {
4591: my ($docuname,$docudom,$old,$new)=@_;
4592: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4593: my $result = &reply("renameuserfile:$docudom:$docuname:".
4594: &escape("$old").':'.&escape("$new"),$home);
4595: if ($result eq 'ok') {
4596: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4597: my $oldmeta = $old.'.meta';
4598: my $newmeta = $new.'.meta';
4599: my $metaresult =
4600: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4601: my $url = "/uploaded/$docudom/$docuname/$old";
4602: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4603: my $sqlresult =
1.823 albertel 4604: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4605: 'portfolio_metadata',$group,
4606: 'delete');
1.798 raeburn 4607: }
4608: }
4609: return $result;
1.531 albertel 4610: }
4611:
1.14 www 4612: # ------------------------------------------------------------------------- Log
4613:
4614: sub log {
4615: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4616: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4617: }
4618:
4619: # ------------------------------------------------------------------ Course Log
1.352 www 4620: #
4621: # This routine flushes several buffers of non-mission-critical nature
4622: #
1.157 www 4623:
4624: sub flushcourselogs {
1.352 www 4625: &logthis('Flushing log buffers');
4626: #
4627: # course logs
4628: # This is a log of all transactions in a course, which can be used
4629: # for data mining purposes
4630: #
4631: # It also collects the courseid database, which lists last transaction
4632: # times and course titles for all courseids
4633: #
4634: my %courseidbuffer=();
1.921 raeburn 4635: foreach my $crsid (keys(%courselogs)) {
1.352 www 4636: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4637: &escape($courselogs{$crsid}),
4638: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4639: delete $courselogs{$crsid};
4640: } else {
4641: &logthis('Failed to flush log buffer for '.$crsid);
4642: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4643: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4644: " exceeded maximum size, deleting.</font>");
4645: delete $courselogs{$crsid};
4646: }
1.352 www 4647: }
1.920 raeburn 4648: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4649: 'description' => $coursedescrbuf{$crsid},
4650: 'inst_code' => $courseinstcodebuf{$crsid},
4651: 'type' => $coursetypebuf{$crsid},
4652: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4653: };
1.191 harris41 4654: }
1.352 www 4655: #
4656: # Write course id database (reverse lookup) to homeserver of courses
4657: # Is used in pickcourse
4658: #
1.840 albertel 4659: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4660: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4661: $courseidbuffer{$crs_home},
4662: $crs_home,'timeonly');
1.352 www 4663: }
4664: #
4665: # File accesses
4666: # Writes to the dynamic metadata of resources to get hit counts, etc.
4667: #
1.449 matthew 4668: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4669: if ($entry =~ /___count$/) {
4670: my ($dom,$name);
1.807 albertel 4671: ($dom,$name,undef)=
1.811 albertel 4672: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4673: if (! defined($dom) || $dom eq '' ||
4674: ! defined($name) || $name eq '') {
1.620 albertel 4675: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4676: #
4677: # FIXME 11/29/2021
4678: # Typo in rev. 1.458 (2003/12/09)??
4679: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4680: #
4681: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4682: # $dom and $name will always be null, so the &inc() call will default to storing this data
4683: # in a nohist_accesscount.db file for the user rather than the course.
4684: #
4685: # That said there is a lot of noise in the data being stored.
4686: # So counts for prtspool/ and adm/ etc. are recorded.
4687: #
4688: # A review of which items ending '___count' are written to %accesshash should likely be
4689: # made before deciding whether to set these to 'course.' instead of 'request.'
4690: #
4691: # Under the current scheme each user receives a nohist_accesscount.db file listing
4692: # accesses for things which are not published resources, regardless of course, and
4693: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4694: # anyone in the course for things which are not published resources.
4695: #
4696: # For an author, nohist_accesscount.db ends up having records for other items
4697: # mixed up with the legitimate access counts for the author's published resources.
4698: #
1.620 albertel 4699: $dom = $env{'request.'.$cid.'.domain'};
4700: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4701: }
1.450 matthew 4702: my $value = $accesshash{$entry};
4703: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4704: my %temphash=($url => $value);
1.449 matthew 4705: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4706: if ($result eq 'ok') {
4707: delete $accesshash{$entry};
4708: }
4709: } else {
1.811 albertel 4710: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4711: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4712: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4713: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4714: delete $accesshash{$entry};
4715: }
1.185 www 4716: }
1.191 harris41 4717: }
1.352 www 4718: #
4719: # Roles
4720: # Reverse lookup of user roles for course faculty/staff and co-authorship
4721: #
1.800 albertel 4722: foreach my $entry (keys(%userrolehash)) {
1.351 www 4723: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4724: split(/\:/,$entry);
4725: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4726: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4727: $rudom,$runame) eq 'ok') {
4728: delete $userrolehash{$entry};
4729: }
4730: }
1.662 raeburn 4731: #
1.1172.2.90 raeburn 4732: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4733: #
4734: my %domrolebuffer = ();
1.1000 raeburn 4735: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4736: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4737: if ($domrolebuffer{$rudom}) {
4738: $domrolebuffer{$rudom}.='&'.&escape($entry).
4739: '='.&escape($domainrolehash{$entry});
4740: } else {
4741: $domrolebuffer{$rudom}.=&escape($entry).
4742: '='.&escape($domainrolehash{$entry});
4743: }
4744: delete $domainrolehash{$entry};
4745: }
4746: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4747: my %servers;
4748: if (defined(&domain($dom,'primary'))) {
4749: my $primary=&domain($dom,'primary');
4750: my $hostname=&hostname($primary);
4751: $servers{$primary} = $hostname;
4752: } else {
4753: %servers = &get_servers($dom,'library');
4754: }
1.841 albertel 4755: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4756: if (&reply('domroleput:'.$dom.':'.
4757: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4758: last;
4759: } else {
1.841 albertel 4760: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4761: }
1.662 raeburn 4762: }
4763: }
1.186 www 4764: $dumpcount++;
1.157 www 4765: }
4766:
4767: sub courselog {
4768: my $what=shift;
1.158 www 4769: $what=time.':'.$what;
1.620 albertel 4770: unless ($env{'request.course.id'}) { return ''; }
4771: $coursedombuf{$env{'request.course.id'}}=
4772: $env{'course.'.$env{'request.course.id'}.'.domain'};
4773: $coursenumbuf{$env{'request.course.id'}}=
4774: $env{'course.'.$env{'request.course.id'}.'.num'};
4775: $coursehombuf{$env{'request.course.id'}}=
4776: $env{'course.'.$env{'request.course.id'}.'.home'};
4777: $coursedescrbuf{$env{'request.course.id'}}=
4778: $env{'course.'.$env{'request.course.id'}.'.description'};
4779: $courseinstcodebuf{$env{'request.course.id'}}=
4780: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4781: $courseownerbuf{$env{'request.course.id'}}=
4782: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4783: $coursetypebuf{$env{'request.course.id'}}=
4784: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4785: if (defined $courselogs{$env{'request.course.id'}}) {
4786: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4787: } else {
1.620 albertel 4788: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4789: }
1.620 albertel 4790: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4791: &flushcourselogs();
4792: }
1.158 www 4793: }
4794:
4795: sub courseacclog {
4796: my $fnsymb=shift;
1.620 albertel 4797: unless ($env{'request.course.id'}) { return ''; }
4798: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4799: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4800: $what.=':POST';
1.583 matthew 4801: # FIXME: Probably ought to escape things....
1.800 albertel 4802: foreach my $key (keys(%env)) {
4803: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4804: my $formitem = $1;
4805: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4806: $what.=':'.$formitem.'='.$env{$key};
4807: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4808: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4809: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4810: } else {
4811: $what.=':'.$formitem.'='.$env{$key};
4812: }
1.975 raeburn 4813: }
1.158 www 4814: }
1.191 harris41 4815: }
1.583 matthew 4816: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4817: # FIXME: We should not be depending on a form parameter that someone
4818: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4819: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4820: $what.= ':POST';
4821: # FIXME: Probably ought to escape things....
4822: foreach my $element ('courseexp','crsfulltext','crsrelated',
4823: 'crsdiscuss') {
1.620 albertel 4824: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4825: }
4826: }
1.158 www 4827: }
4828: &courselog($what);
1.149 www 4829: }
4830:
1.185 www 4831: sub countacc {
4832: my $url=&declutter(shift);
1.458 matthew 4833: return if (! defined($url) || $url eq '');
1.620 albertel 4834: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4835: #
4836: # Mark that this url was used in this course
4837: #
1.620 albertel 4838: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4839: #
4840: # Increase the access count for this resource in this child process
4841: #
1.281 www 4842: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4843: $accesshash{$key}++;
1.185 www 4844: }
1.349 www 4845:
1.361 www 4846: sub linklog {
4847: my ($from,$to)=@_;
4848: $from=&declutter($from);
4849: $to=&declutter($to);
4850: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4851: $accesshash{$to.'___'.$from.'___goto'}=1;
4852: }
1.1160 www 4853:
4854: sub statslog {
4855: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4856: if ($users<2) { return; }
4857: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4858: 'course' => $env{'request.course.id'},
4859: 'sections' => '"all"',
4860: 'num_students' => $users,
4861: 'part' => $part,
4862: 'symb' => $symb,
4863: 'mean_tries' => $av_attempts,
4864: 'deg_of_diff' => $degdiff});
4865: foreach my $key (keys(%dynstore)) {
4866: $accesshash{$key}=$dynstore{$key};
4867: }
4868: }
1.361 www 4869:
1.349 www 4870: sub userrolelog {
4871: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4872: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4873: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4874: $userrolehash
4875: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4876: =$tend.':'.$tstart;
1.662 raeburn 4877: }
1.1169 droeschl 4878: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4879: $userrolehash
4880: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4881: =$tend.':'.$tstart;
4882: }
1.1172.2.90 raeburn 4883: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4884: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4885: $domainrolehash
4886: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4887: = $tend.':'.$tstart;
4888: }
1.351 www 4889: }
4890:
1.957 raeburn 4891: sub courserolelog {
4892: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4893: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4894: my $cdom = $1;
4895: my $cnum = $2;
4896: my $sec = $3;
4897: my $namespace = 'rolelog';
4898: my %storehash = (
4899: role => $trole,
4900: start => $tstart,
4901: end => $tend,
4902: selfenroll => $selfenroll,
4903: context => $context,
4904: );
4905: if ($trole eq 'gr') {
4906: $namespace = 'groupslog';
4907: $storehash{'group'} = $sec;
4908: } else {
4909: $storehash{'section'} = $sec;
4910: }
4911: &write_log('course',$namespace,\%storehash,$delflag,$username,
4912: $domain,$cnum,$cdom);
4913: if (($trole ne 'st') || ($sec ne '')) {
4914: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4915: }
4916: }
4917: return;
4918: }
4919:
1.1172.2.9 raeburn 4920: sub domainrolelog {
4921: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4922: if ($area =~ m{^/($match_domain)/$}) {
4923: my $cdom = $1;
4924: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4925: my $namespace = 'rolelog';
4926: my %storehash = (
4927: role => $trole,
4928: start => $tstart,
4929: end => $tend,
4930: context => $context,
4931: );
4932: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4933: $domain,$domconfiguser,$cdom);
4934: }
4935: return;
4936:
4937: }
4938:
4939: sub coauthorrolelog {
4940: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4941: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4942: my $audom = $1;
4943: my $auname = $2;
4944: my $namespace = 'rolelog';
4945: my %storehash = (
4946: role => $trole,
4947: start => $tstart,
4948: end => $tend,
4949: context => $context,
4950: );
4951: &write_log('author',$namespace,\%storehash,$delflag,$username,
4952: $domain,$auname,$audom);
4953: }
4954: return;
4955: }
4956:
1.351 www 4957: sub get_course_adv_roles {
1.948 raeburn 4958: my ($cid,$codes) = @_;
1.620 albertel 4959: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4960: my %coursehash=&coursedescription($cid);
1.988 raeburn 4961: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4962: my %nothide=();
1.800 albertel 4963: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4964: if ($user !~ /:/) {
4965: $nothide{join(':',split(/[\@]/,$user))}=1;
4966: } else {
4967: $nothide{$user}=1;
4968: }
1.470 www 4969: }
1.1172.2.23 raeburn 4970: my @possdoms = ($coursehash{'domain'});
4971: if ($coursehash{'checkforpriv'}) {
4972: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4973: }
1.351 www 4974: my %returnhash=();
4975: my %dumphash=
4976: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4977: my $now=time;
1.997 raeburn 4978: my %privileged;
1.1000 raeburn 4979: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4980: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4981: if (($tstart) && ($tstart<0)) { next; }
4982: if (($tend) && ($tend<$now)) { next; }
4983: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4984: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4985: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4986: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4987: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4988: if ($role eq 'cr') { next; }
1.948 raeburn 4989: if ($codes) {
4990: if ($section) { $role .= ':'.$section; }
4991: if ($returnhash{$role}) {
4992: $returnhash{$role}.=','.$username.':'.$domain;
4993: } else {
4994: $returnhash{$role}=$username.':'.$domain;
4995: }
1.351 www 4996: } else {
1.988 raeburn 4997: my $key=&plaintext($role,$crstype);
1.973 bisitz 4998: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4999: if ($returnhash{$key}) {
5000: $returnhash{$key}.=','.$username.':'.$domain;
5001: } else {
5002: $returnhash{$key}=$username.':'.$domain;
5003: }
1.351 www 5004: }
1.948 raeburn 5005: }
1.400 www 5006: return %returnhash;
5007: }
5008:
5009: sub get_my_roles {
1.937 raeburn 5010: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5011: unless (defined($uname)) { $uname=$env{'user.name'}; }
5012: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5013: my (%dumphash,%nothide);
1.1086 raeburn 5014: if ($context eq 'userroles') {
1.1166 raeburn 5015: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5016: } else {
1.1172.2.23 raeburn 5017: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5018: if ($hidepriv) {
5019: my %coursehash=&coursedescription($udom.'_'.$uname);
5020: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5021: if ($user !~ /:/) {
5022: $nothide{join(':',split(/[\@]/,$user))} = 1;
5023: } else {
5024: $nothide{$user} = 1;
5025: }
5026: }
5027: }
1.858 raeburn 5028: }
1.400 www 5029: my %returnhash=();
5030: my $now=time;
1.999 raeburn 5031: my %privileged;
1.800 albertel 5032: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5033: my ($role,$tend,$tstart);
5034: if ($context eq 'userroles') {
1.1149 raeburn 5035: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5036: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5037: } else {
5038: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5039: }
1.400 www 5040: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5041: my $status = 'active';
1.939 raeburn 5042: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5043: $status = 'previous';
5044: }
5045: if (($tstart) && ($now<$tstart)) {
5046: $status = 'future';
5047: }
5048: if (ref($types) eq 'ARRAY') {
5049: if (!grep(/^\Q$status\E$/,@{$types})) {
5050: next;
5051: }
5052: } else {
5053: if ($status ne 'active') {
5054: next;
5055: }
5056: }
1.867 raeburn 5057: my ($rolecode,$username,$domain,$section,$area);
5058: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5059: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5060: (undef,$domain,$username,$section) = split(/\//,$area);
5061: } else {
5062: ($role,$username,$domain,$section) = split(/\:/,$entry);
5063: }
1.832 raeburn 5064: if (ref($roledoms) eq 'ARRAY') {
5065: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5066: next;
5067: }
5068: }
5069: if (ref($roles) eq 'ARRAY') {
5070: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5071: if ($role =~ /^cr\//) {
5072: if (!grep(/^cr$/,@{$roles})) {
5073: next;
5074: }
1.1104 raeburn 5075: } elsif ($role =~ /^gr\//) {
5076: if (!grep(/^gr$/,@{$roles})) {
5077: next;
5078: }
1.922 raeburn 5079: } else {
5080: next;
5081: }
1.832 raeburn 5082: }
1.867 raeburn 5083: }
1.937 raeburn 5084: if ($hidepriv) {
1.1172.2.23 raeburn 5085: my @privroles = ('dc','su');
1.999 raeburn 5086: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5087: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5088: } else {
1.1172.2.23 raeburn 5089: my $possdoms = [$domain];
5090: if (ref($roledoms) eq 'ARRAY') {
5091: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5092: }
1.1172.2.23 raeburn 5093: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5094: if (!$nothide{$username.':'.$domain}) {
5095: next;
5096: }
5097: }
1.937 raeburn 5098: }
5099: }
1.933 raeburn 5100: if ($withsec) {
5101: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5102: $tstart.':'.$tend;
5103: } else {
5104: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5105: }
1.832 raeburn 5106: }
1.373 www 5107: return %returnhash;
1.399 www 5108: }
5109:
1.1172.2.89 raeburn 5110: sub get_all_adhocroles {
5111: my ($dom) = @_;
5112: my @roles_by_num = ();
5113: my %domdefaults = &get_domain_defaults($dom);
5114: my (%description,%access_in_dom,%access_info);
5115: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5116: my $count = 0;
5117: my %domcurrent = %{$domdefaults{'adhocroles'}};
5118: my %ordered;
5119: foreach my $role (sort(keys(%domcurrent))) {
5120: my ($order,$desc,$access_in_dom);
5121: if (ref($domcurrent{$role}) eq 'HASH') {
5122: $order = $domcurrent{$role}{'order'};
5123: $desc = $domcurrent{$role}{'desc'};
5124: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5125: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5126: }
5127: if ($order eq '') {
5128: $order = $count;
5129: }
5130: $ordered{$order} = $role;
5131: if ($desc ne '') {
5132: $description{$role} = $desc;
5133: } else {
5134: $description{$role}= $role;
5135: }
5136: $count++;
5137: }
5138: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5139: push(@roles_by_num,$ordered{$item});
5140: }
5141: }
5142: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5143: }
5144:
5145: sub get_my_adhocroles {
5146: my ($cid,$checkreg) = @_;
5147: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5148: if ($env{'request.course.id'} eq $cid) {
5149: $cdom = $env{'course.'.$cid.'.domain'};
5150: $cnum = $env{'course.'.$cid.'.num'};
5151: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5152: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5153: $cdom = $1;
5154: $cnum = $2;
5155: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5156: $cdom,$cnum);
5157: }
5158: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5159: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5160: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5161: if ($rosterhash{$user} ne '') {
5162: my $type = (split(/:/,$rosterhash{$user}))[5];
5163: return ([],{}) if ($type eq 'auto');
5164: }
5165: }
5166: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5167: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5168: my $then=$env{'user.login.time'};
5169: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5170: if (!$update) {
5171: $update = $then;
5172: }
5173: my @liveroles;
5174: foreach my $role ('dh','da') {
5175: if ($env{"user.role.$role./$cdom/"}) {
5176: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5177: my $limit = $update;
5178: if ($env{'request.role'} eq "$role./$cdom/") {
5179: $limit = $then;
5180: }
5181: my $activerole = 1;
5182: if ($tstart && $tstart>$limit) { $activerole = 0; }
5183: if ($tend && $tend <$limit) { $activerole = 0; }
5184: if ($activerole) {
5185: push(@liveroles,$role);
5186: }
5187: }
5188: }
5189: if (@liveroles) {
1.1172.2.89 raeburn 5190: if (&homeserver($cnum,$cdom) ne 'no_host') {
5191: my ($accessref,$accessinfo,%access_in_dom);
5192: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5193: if (ref($roles_by_num) eq 'ARRAY') {
5194: if (@{$roles_by_num}) {
5195: my %settings;
5196: if ($env{'request.course.id'} eq $cid) {
5197: foreach my $envkey (keys(%env)) {
5198: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5199: $settings{$1} = $env{$envkey};
5200: }
5201: }
5202: } else {
5203: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5204: }
5205: my %setincrs;
5206: if ($settings{'internal.adhocaccess'}) {
5207: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5208: }
5209: my @statuses;
5210: if ($env{'environment.inststatus'}) {
5211: @statuses = split(/,/,$env{'environment.inststatus'});
5212: }
5213: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5214: if (ref($accessref) eq 'HASH') {
5215: %access_in_dom = %{$accessref};
5216: }
5217: foreach my $role (@{$roles_by_num}) {
5218: my ($curraccess,@okstatus,@personnel);
5219: if ($setincrs{$role}) {
5220: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5221: if ($curraccess eq 'status') {
5222: @okstatus = split(/\&/,$rest);
5223: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5224: @personnel = split(/\&/,$rest);
5225: }
5226: } else {
5227: $curraccess = $access_in_dom{$role};
5228: if (ref($accessinfo) eq 'HASH') {
5229: if ($curraccess eq 'status') {
5230: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5231: @okstatus = @{$accessinfo->{$role}};
5232: }
5233: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5234: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5235: @personnel = @{$accessinfo->{$role}};
5236: }
5237: }
5238: }
5239: }
5240: if ($curraccess eq 'none') {
5241: next;
5242: } elsif ($curraccess eq 'all') {
5243: push(@possroles,$role);
1.1172.2.90 raeburn 5244: } elsif ($curraccess eq 'dh') {
5245: if (grep(/^dh$/,@liveroles)) {
5246: push(@possroles,$role);
5247: } else {
5248: next;
5249: }
5250: } elsif ($curraccess eq 'da') {
5251: if (grep(/^da$/,@liveroles)) {
5252: push(@possroles,$role);
5253: } else {
5254: next;
5255: }
1.1172.2.89 raeburn 5256: } elsif ($curraccess eq 'status') {
5257: if (@okstatus) {
5258: if (!@statuses) {
5259: if (grep(/^default$/,@okstatus)) {
5260: push(@possroles,$role);
5261: }
5262: } else {
5263: foreach my $status (@okstatus) {
5264: if (grep(/^\Q$status\E$/,@statuses)) {
5265: push(@possroles,$role);
5266: last;
5267: }
5268: }
5269: }
5270: }
5271: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5272: if (grep(/^\Q$user\E$/,@personnel)) {
5273: if ($curraccess eq 'exc') {
5274: push(@possroles,$role);
5275: }
5276: } elsif ($curraccess eq 'inc') {
5277: push(@possroles,$role);
5278: }
5279: }
5280: }
5281: }
5282: }
5283: }
5284: }
5285: }
5286: }
5287: unless (ref($description) eq 'HASH') {
5288: if (ref($roles_by_num) eq 'ARRAY') {
5289: my %desc;
5290: map { $desc{$_} = $_; } (@{$roles_by_num});
5291: $description = \%desc;
5292: } else {
5293: $description = {};
5294: }
5295: }
5296: return (\@possroles,$description);
5297: }
5298:
1.399 www 5299: # ----------------------------------------------------- Frontpage Announcements
5300: #
5301: #
5302:
5303: sub postannounce {
5304: my ($server,$text)=@_;
1.844 albertel 5305: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5306: unless ($text=~/\w/) { $text=''; }
5307: return &reply('setannounce:'.&escape($text),$server);
5308: }
5309:
5310: sub getannounce {
1.448 albertel 5311:
1.1172.2.96 raeburn 5312: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5313: my $announcement='';
1.800 albertel 5314: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5315: close($fh);
1.399 www 5316: if ($announcement=~/\w/) {
5317: return
5318: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5319: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5320: } else {
5321: return '';
5322: }
5323: } else {
5324: return '';
5325: }
1.351 www 5326: }
1.353 www 5327:
5328: # ---------------------------------------------------------- Course ID routines
5329: # Deal with domain's nohist_courseid.db files
5330: #
5331:
5332: sub courseidput {
1.921 raeburn 5333: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5334: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5335: my $outcome;
5336: if ($caller eq 'timeonly') {
5337: my $cids = '';
5338: foreach my $item (keys(%$storehash)) {
5339: $cids.=&escape($item).'&';
5340: }
5341: $cids=~s/\&$//;
5342: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5343: $coursehome);
5344: } else {
5345: my $items = '';
5346: foreach my $item (keys(%$storehash)) {
5347: $items.= &escape($item).'='.
5348: &freeze_escape($$storehash{$item}).'&';
5349: }
5350: $items=~s/\&$//;
5351: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5352: $coursehome);
1.918 raeburn 5353: }
5354: if ($outcome eq 'unknown_cmd') {
5355: my $what;
5356: foreach my $cid (keys(%$storehash)) {
5357: $what .= &escape($cid).'=';
1.921 raeburn 5358: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5359: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5360: }
5361: $what =~ s/\:$/&/;
5362: }
5363: $what =~ s/\&$//;
5364: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5365: } else {
5366: return $outcome;
5367: }
1.353 www 5368: }
5369:
5370: sub courseiddump {
1.921 raeburn 5371: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5372: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5373: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5374: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5375: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5376: my $as_hash = 1;
5377: my %returnhash;
5378: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5379: my %libserv = &all_library();
5380: foreach my $tryserver (keys(%libserv)) {
5381: if ( ( $hostidflag == 1
5382: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5383: || (!defined($hostidflag)) ) {
5384:
1.918 raeburn 5385: if (($domfilter eq '') ||
5386: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5387: my $rep;
5388: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5389: $rep = &LONCAPA::Lond::dump_course_id_handler(
5390: join(":", (&host_domain($tryserver), $sincefilter,
5391: &escape($descfilter), &escape($instcodefilter),
5392: &escape($ownerfilter), &escape($coursefilter),
5393: &escape($typefilter), &escape($regexp_ok),
5394: $as_hash, &escape($selfenrollonly),
5395: &escape($catfilter), $showhidden, $caller,
5396: &escape($cloner), &escape($cc_clone), $cloneonly,
5397: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5398: &escape($creationcontext),$domcloner,$hasuniquecode,
5399: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5400: } else {
5401: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5402: $sincefilter.':'.&escape($descfilter).':'.
5403: &escape($instcodefilter).':'.&escape($ownerfilter).
5404: ':'.&escape($coursefilter).':'.&escape($typefilter).
5405: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5406: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5407: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5408: &escape($cc_clone).':'.$cloneonly.':'.
5409: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5410: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5411: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5412: }
5413:
1.918 raeburn 5414: my @pairs=split(/\&/,$rep);
5415: foreach my $item (@pairs) {
5416: my ($key,$value)=split(/\=/,$item,2);
5417: $key = &unescape($key);
5418: next if ($key =~ /^error: 2 /);
5419: my $result = &thaw_unescape($value);
5420: if (ref($result) eq 'HASH') {
5421: $returnhash{$key}=$result;
5422: } else {
1.921 raeburn 5423: my @responses = split(/:/,$value);
5424: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5425: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5426: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5427: }
1.1008 raeburn 5428: }
1.353 www 5429: }
5430: }
5431: }
5432: }
5433: return %returnhash;
5434: }
5435:
1.1055 raeburn 5436: sub courselastaccess {
5437: my ($cdom,$cnum,$hostidref) = @_;
5438: my %returnhash;
5439: if ($cdom && $cnum) {
5440: my $chome = &homeserver($cnum,$cdom);
5441: if ($chome ne 'no_host') {
5442: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5443: &extract_lastaccess(\%returnhash,$rep);
5444: }
5445: } else {
5446: if (!$cdom) { $cdom=''; }
5447: my %libserv = &all_library();
5448: foreach my $tryserver (keys(%libserv)) {
5449: if (ref($hostidref) eq 'ARRAY') {
5450: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5451: }
5452: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5453: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5454: &extract_lastaccess(\%returnhash,$rep);
5455: }
5456: }
5457: }
5458: return %returnhash;
5459: }
5460:
5461: sub extract_lastaccess {
5462: my ($returnhash,$rep) = @_;
5463: if (ref($returnhash) eq 'HASH') {
5464: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5465: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5466: $rep eq '') {
5467: my @pairs=split(/\&/,$rep);
5468: foreach my $item (@pairs) {
5469: my ($key,$value)=split(/\=/,$item,2);
5470: $key = &unescape($key);
5471: next if ($key =~ /^error: 2 /);
5472: $returnhash->{$key} = &thaw_unescape($value);
5473: }
5474: }
5475: }
5476: return;
5477: }
5478:
1.658 raeburn 5479: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5480:
5481: sub dcmailput {
1.685 raeburn 5482: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5483: my $status = &Apache::lonnet::critical(
1.740 www 5484: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5485: &escape($message),$server);
1.662 raeburn 5486: return $status;
5487: }
5488:
1.658 raeburn 5489: sub dcmaildump {
5490: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5491: my %returnhash=();
1.846 albertel 5492:
5493: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5494: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5495: &escape($enddate).':';
5496: my @esc_senders=map { &escape($_)} @$senders;
5497: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5498: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5499: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5500: if (($key) && ($value)) {
5501: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5502: }
5503: }
5504: }
5505: return %returnhash;
5506: }
1.662 raeburn 5507: # ---------------------------------------------------------- Domain roles
5508:
5509: sub get_domain_roles {
5510: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5511: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5512: $startdate = '.';
5513: }
1.1018 raeburn 5514: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5515: $enddate = '.';
5516: }
1.922 raeburn 5517: my $rolelist;
5518: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5519: $rolelist = join('&',@{$roles});
1.922 raeburn 5520: }
1.662 raeburn 5521: my %personnel = ();
1.841 albertel 5522:
5523: my %servers = &get_servers($dom,'library');
5524: foreach my $tryserver (keys(%servers)) {
5525: %{$personnel{$tryserver}}=();
5526: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5527: &escape($startdate).':'.
5528: &escape($enddate).':'.
5529: &escape($rolelist), $tryserver))) {
5530: my ($key,$value) = split(/\=/,$line,2);
5531: if (($key) && ($value)) {
5532: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5533: }
5534: }
1.662 raeburn 5535: }
5536: return %personnel;
5537: }
1.658 raeburn 5538:
1.1172.2.89 raeburn 5539: sub get_active_domroles {
5540: my ($dom,$roles) = @_;
5541: return () unless (ref($roles) eq 'ARRAY');
5542: my $now = time;
5543: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5544: my %domroles;
5545: foreach my $server (keys(%dompersonnel)) {
5546: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5547: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5548: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5549: }
5550: }
5551: return %domroles;
5552: }
5553:
1.1057 www 5554: # ----------------------------------------------------------- Interval timing
1.149 www 5555:
1.1153 www 5556: {
5557: # Caches needed for speedup of navmaps
5558: # We don't want to cache this for very long at all (5 seconds at most)
5559: #
5560: # The user for whom we cache
5561: my $cachedkey='';
5562: # The cached times for this user
5563: my %cachedtimes=();
5564: # When this was last done
1.1172.2.66 raeburn 5565: my $cachedtime='';
1.1153 www 5566:
5567: sub load_all_first_access {
1.1154 raeburn 5568: my ($uname,$udom)=@_;
1.1156 www 5569: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5570: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5571: return;
5572: }
5573: $cachedtime=time;
5574: $cachedkey=$uname.':'.$udom;
5575: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5576: }
5577:
1.504 albertel 5578: sub get_first_access {
1.1162 raeburn 5579: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5580: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5581: if ($argsymb) { $symb=$argsymb; }
5582: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5583: if ($argmap) { $map = $argmap; }
1.926 albertel 5584: if ($type eq 'course') {
5585: $res='course';
5586: } elsif ($type eq 'map') {
1.588 albertel 5587: $res=&symbread($map);
5588: } else {
5589: $res=$symb;
5590: }
1.1153 www 5591: &load_all_first_access($uname,$udom);
5592: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5593: }
5594:
5595: sub set_first_access {
1.1162 raeburn 5596: my ($type,$interval)=@_;
1.790 albertel 5597: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5598: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5599: if ($type eq 'course') {
5600: $res='course';
5601: } elsif ($type eq 'map') {
1.588 albertel 5602: $res=&symbread($map);
5603: } else {
5604: $res=$symb;
5605: }
1.1153 www 5606: $cachedkey='';
1.1162 raeburn 5607: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5608: if ($firstaccess) {
5609: &logthis("First access time already set ($firstaccess) when attempting ".
5610: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5611: "in $courseid");
5612: return 'already_set';
5613: } else {
1.1162 raeburn 5614: my $start = time;
5615: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5616: $udom,$uname);
5617: if ($putres eq 'ok') {
5618: &put('timerinterval',{"$courseid\0$res"=>$interval},
5619: $udom,$uname);
5620: &appenv(
5621: {
5622: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5623: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5624: }
5625: );
1.1172.2.97 raeburn 5626: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5627: $cachedtimes{"$courseid\0$res"} = $start;
5628: }
1.1172.2.102 raeburn 5629: } elsif ($putres ne 'refused') {
5630: &logthis("Result: $putres when attempting to set first access time ".
5631: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5632: }
5633: return $putres;
1.505 albertel 5634: }
5635: return 'already_set';
1.504 albertel 5636: }
1.1153 www 5637: }
1.1172.2.32 raeburn 5638:
5639: sub checkout {
5640: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5641: my $now=time;
5642: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5643: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5644: my $infostr=&escape(
5645: 'CHECKOUTTOKEN&'.
5646: $tuname.'&'.
5647: $tudom.'&'.
5648: $tcrsid.'&'.
5649: $symb.'&'.
1.1172.2.134 raeburn 5650: $now.'&'.$ip);
1.1172.2.32 raeburn 5651: my $token=&reply('tmpput:'.$infostr,$lonhost);
5652: if ($token=~/^error\:/) {
5653: &logthis("<font color=\"blue\">WARNING: ".
5654: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5655: "</font>");
5656: return '';
5657: }
5658:
5659: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5660: $token=~tr/a-z/A-Z/;
5661:
5662: my %infohash=('resource.0.outtoken' => $token,
5663: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5664: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5665:
5666: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5667: return '';
5668: } else {
5669: &logthis("<font color=\"blue\">WARNING: ".
5670: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5671: "</font>");
5672: }
5673:
5674: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5675: &escape('Checkout '.$infostr.' - '.
5676: $token)) ne 'ok') {
5677: return '';
5678: } else {
5679: &logthis("<font color=\"blue\">WARNING: ".
5680: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5681: "</font>");
5682: }
5683: return $token;
5684: }
5685:
5686: # ------------------------------------------------------------ Check in an item
5687:
5688: sub checkin {
5689: my $token=shift;
5690: my $now=time;
5691: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5692: $lonhost=~tr/A-Z/a-z/;
5693: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5694: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5695: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5696: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5697: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5698:
5699: unless (($tuname) && ($tudom)) {
5700: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5701: return '';
5702: }
5703:
5704: unless (&allowed('mgr',$tcrsid)) {
5705: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5706: $env{'user.name'}.' - '.$env{'user.domain'});
5707: return '';
5708: }
5709:
5710: my %infohash=('resource.0.intoken' => $token,
5711: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5712: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5713:
5714: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5715: return '';
5716: }
5717:
5718: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5719: &escape('Checkin - '.$token)) ne 'ok') {
5720: return '';
5721: }
5722:
5723: return ($symb,$tuname,$tudom,$tcrsid);
5724: }
5725:
1.110 www 5726: # --------------------------------------------- Set Expire Date for Spreadsheet
5727:
5728: sub expirespread {
5729: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5730: my $cid=$env{'request.course.id'};
1.110 www 5731: if ($cid) {
5732: my $now=time;
5733: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5734: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5735: $env{'course.'.$cid.'.num'}.
1.110 www 5736: ':nohist_expirationdates:'.
5737: &escape($key).'='.$now,
1.620 albertel 5738: $env{'course.'.$cid.'.home'})
1.110 www 5739: }
5740: return 'ok';
1.14 www 5741: }
5742:
1.109 www 5743: # ----------------------------------------------------- Devalidate Spreadsheets
5744:
5745: sub devalidate {
1.325 www 5746: my ($symb,$uname,$udom)=@_;
1.620 albertel 5747: my $cid=$env{'request.course.id'};
1.109 www 5748: if ($cid) {
1.391 matthew 5749: # delete the stored spreadsheets for
5750: # - the student level sheet of this user in course's homespace
5751: # - the assessment level sheet for this resource
5752: # for this user in user's homespace
1.553 albertel 5753: # - current conditional state info
1.325 www 5754: my $key=$uname.':'.$udom.':';
1.109 www 5755: my $status=
1.299 matthew 5756: &del('nohist_calculatedsheets',
1.391 matthew 5757: [$key.'studentcalc:'],
1.620 albertel 5758: $env{'course.'.$cid.'.domain'},
5759: $env{'course.'.$cid.'.num'})
1.133 albertel 5760: .' '.
5761: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5762: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5763: unless ($status eq 'ok ok') {
5764: &logthis('Could not devalidate spreadsheet '.
1.325 www 5765: $uname.' at '.$udom.' for '.
1.109 www 5766: $symb.': '.$status);
1.133 albertel 5767: }
1.553 albertel 5768: &delenv('user.state.'.$cid);
1.109 www 5769: }
5770: }
5771:
1.265 albertel 5772: sub get_scalar {
5773: my ($string,$end) = @_;
5774: my $value;
5775: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5776: $value = $1;
5777: } elsif ($$string =~ s/^([^&]*?)&//) {
5778: $value = $1;
5779: }
5780: return &unescape($value);
5781: }
5782:
5783: sub array2str {
5784: my (@array) = @_;
5785: my $result=&arrayref2str(\@array);
5786: $result=~s/^__ARRAY_REF__//;
5787: $result=~s/__END_ARRAY_REF__$//;
5788: return $result;
5789: }
5790:
1.204 albertel 5791: sub arrayref2str {
5792: my ($arrayref) = @_;
1.265 albertel 5793: my $result='__ARRAY_REF__';
1.204 albertel 5794: foreach my $elem (@$arrayref) {
1.265 albertel 5795: if(ref($elem) eq 'ARRAY') {
5796: $result.=&arrayref2str($elem).'&';
5797: } elsif(ref($elem) eq 'HASH') {
5798: $result.=&hashref2str($elem).'&';
5799: } elsif(ref($elem)) {
5800: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5801: } else {
5802: $result.=&escape($elem).'&';
5803: }
5804: }
5805: $result=~s/\&$//;
1.265 albertel 5806: $result .= '__END_ARRAY_REF__';
1.204 albertel 5807: return $result;
5808: }
5809:
1.168 albertel 5810: sub hash2str {
1.204 albertel 5811: my (%hash) = @_;
5812: my $result=&hashref2str(\%hash);
1.265 albertel 5813: $result=~s/^__HASH_REF__//;
5814: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5815: return $result;
5816: }
5817:
5818: sub hashref2str {
5819: my ($hashref)=@_;
1.265 albertel 5820: my $result='__HASH_REF__';
1.800 albertel 5821: foreach my $key (sort(keys(%$hashref))) {
5822: if (ref($key) eq 'ARRAY') {
5823: $result.=&arrayref2str($key).'=';
5824: } elsif (ref($key) eq 'HASH') {
5825: $result.=&hashref2str($key).'=';
5826: } elsif (ref($key)) {
1.265 albertel 5827: $result.='=';
1.800 albertel 5828: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5829: } else {
1.1132 raeburn 5830: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5831: }
5832:
1.800 albertel 5833: if(ref($hashref->{$key}) eq 'ARRAY') {
5834: $result.=&arrayref2str($hashref->{$key}).'&';
5835: } elsif(ref($hashref->{$key}) eq 'HASH') {
5836: $result.=&hashref2str($hashref->{$key}).'&';
5837: } elsif(ref($hashref->{$key})) {
1.265 albertel 5838: $result.='&';
1.800 albertel 5839: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5840: } else {
1.800 albertel 5841: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5842: }
5843: }
1.168 albertel 5844: $result=~s/\&$//;
1.265 albertel 5845: $result .= '__END_HASH_REF__';
1.168 albertel 5846: return $result;
5847: }
5848:
5849: sub str2hash {
1.265 albertel 5850: my ($string)=@_;
5851: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5852: return %$hash;
5853: }
5854:
5855: sub str2hashref {
1.168 albertel 5856: my ($string) = @_;
1.265 albertel 5857:
5858: my %hash;
5859:
5860: if($string !~ /^__HASH_REF__/) {
5861: if (! ($string eq '' || !defined($string))) {
5862: $hash{'error'}='Not hash reference';
5863: }
5864: return (\%hash, $string);
5865: }
5866:
5867: $string =~ s/^__HASH_REF__//;
5868:
5869: while($string !~ /^__END_HASH_REF__/) {
5870: #key
5871: my $key='';
5872: if($string =~ /^__HASH_REF__/) {
5873: ($key, $string)=&str2hashref($string);
5874: if(defined($key->{'error'})) {
5875: $hash{'error'}='Bad data';
5876: return (\%hash, $string);
5877: }
5878: } elsif($string =~ /^__ARRAY_REF__/) {
5879: ($key, $string)=&str2arrayref($string);
5880: if($key->[0] eq 'Array reference error') {
5881: $hash{'error'}='Bad data';
5882: return (\%hash, $string);
5883: }
5884: } else {
5885: $string =~ s/^(.*?)=//;
1.267 albertel 5886: $key=&unescape($1);
1.265 albertel 5887: }
5888: $string =~ s/^=//;
5889:
5890: #value
5891: my $value='';
5892: if($string =~ /^__HASH_REF__/) {
5893: ($value, $string)=&str2hashref($string);
5894: if(defined($value->{'error'})) {
5895: $hash{'error'}='Bad data';
5896: return (\%hash, $string);
5897: }
5898: } elsif($string =~ /^__ARRAY_REF__/) {
5899: ($value, $string)=&str2arrayref($string);
5900: if($value->[0] eq 'Array reference error') {
5901: $hash{'error'}='Bad data';
5902: return (\%hash, $string);
5903: }
5904: } else {
5905: $value=&get_scalar(\$string,'__END_HASH_REF__');
5906: }
5907: $string =~ s/^&//;
5908:
5909: $hash{$key}=$value;
1.204 albertel 5910: }
1.265 albertel 5911:
5912: $string =~ s/^__END_HASH_REF__//;
5913:
5914: return (\%hash, $string);
1.204 albertel 5915: }
5916:
5917: sub str2array {
1.265 albertel 5918: my ($string)=@_;
5919: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5920: return @$array;
5921: }
5922:
5923: sub str2arrayref {
1.204 albertel 5924: my ($string) = @_;
1.265 albertel 5925: my @array;
5926:
5927: if($string !~ /^__ARRAY_REF__/) {
5928: if (! ($string eq '' || !defined($string))) {
5929: $array[0]='Array reference error';
5930: }
5931: return (\@array, $string);
5932: }
5933:
5934: $string =~ s/^__ARRAY_REF__//;
5935:
5936: while($string !~ /^__END_ARRAY_REF__/) {
5937: my $value='';
5938: if($string =~ /^__HASH_REF__/) {
5939: ($value, $string)=&str2hashref($string);
5940: if(defined($value->{'error'})) {
5941: $array[0] ='Array reference error';
5942: return (\@array, $string);
5943: }
5944: } elsif($string =~ /^__ARRAY_REF__/) {
5945: ($value, $string)=&str2arrayref($string);
5946: if($value->[0] eq 'Array reference error') {
5947: $array[0] ='Array reference error';
5948: return (\@array, $string);
5949: }
5950: } else {
5951: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5952: }
5953: $string =~ s/^&//;
5954:
5955: push(@array, $value);
1.191 harris41 5956: }
1.265 albertel 5957:
5958: $string =~ s/^__END_ARRAY_REF__//;
5959:
5960: return (\@array, $string);
1.168 albertel 5961: }
5962:
1.167 albertel 5963: # -------------------------------------------------------------------Temp Store
5964:
1.168 albertel 5965: sub tmpreset {
5966: my ($symb,$namespace,$domain,$stuname) = @_;
5967: if (!$symb) {
5968: $symb=&symbread();
1.620 albertel 5969: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5970: }
5971: $symb=escape($symb);
5972:
1.620 albertel 5973: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5974: $namespace=~s/\//\_/g;
5975: $namespace=~s/\W//g;
5976:
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.1117 foxr 5982: my $path=LONCAPA::tempdir();
1.168 albertel 5983: my %hash;
5984: if (tie(%hash,'GDBM_File',
5985: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5986: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5987: foreach my $key (keys(%hash)) {
1.180 albertel 5988: if ($key=~ /:$symb/) {
1.168 albertel 5989: delete($hash{$key});
5990: }
5991: }
5992: }
5993: }
5994:
1.167 albertel 5995: sub tmpstore {
1.168 albertel 5996: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5997:
5998: if (!$symb) {
5999: $symb=&symbread();
1.620 albertel 6000: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6001: }
6002: $symb=escape($symb);
6003:
6004: if (!$namespace) {
6005: # I don't think we would ever want to store this for a course.
6006: # it seems this will only be used if we don't have a course.
1.620 albertel 6007: #$namespace=$env{'request.course.id'};
1.168 albertel 6008: #if (!$namespace) {
1.620 albertel 6009: $namespace=$env{'request.state'};
1.168 albertel 6010: #}
6011: }
6012: $namespace=~s/\//\_/g;
6013: $namespace=~s/\W//g;
1.620 albertel 6014: if (!$domain) { $domain=$env{'user.domain'}; }
6015: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6016: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6017: $stuname=&get_requestor_ip();
1.591 albertel 6018: }
1.168 albertel 6019: my $now=time;
6020: my %hash;
1.1117 foxr 6021: my $path=LONCAPA::tempdir();
1.168 albertel 6022: if (tie(%hash,'GDBM_File',
6023: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6024: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6025: $hash{"version:$symb"}++;
6026: my $version=$hash{"version:$symb"};
6027: my $allkeys='';
6028: foreach my $key (keys(%$storehash)) {
6029: $allkeys.=$key.':';
1.591 albertel 6030: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6031: }
6032: $hash{"$version:$symb:timestamp"}=$now;
6033: $allkeys.='timestamp';
6034: $hash{"$version:keys:$symb"}=$allkeys;
6035: if (untie(%hash)) {
6036: return 'ok';
6037: } else {
6038: return "error:$!";
6039: }
6040: } else {
6041: return "error:$!";
6042: }
6043: }
1.167 albertel 6044:
1.168 albertel 6045: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6046:
1.168 albertel 6047: sub tmprestore {
6048: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6049:
1.168 albertel 6050: if (!$symb) {
6051: $symb=&symbread();
1.620 albertel 6052: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6053: }
6054: $symb=escape($symb);
6055:
1.620 albertel 6056: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6057:
1.620 albertel 6058: if (!$domain) { $domain=$env{'user.domain'}; }
6059: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6060: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6061: $stuname=&get_requestor_ip();
1.591 albertel 6062: }
1.168 albertel 6063: my %returnhash;
6064: $namespace=~s/\//\_/g;
6065: $namespace=~s/\W//g;
6066: my %hash;
1.1117 foxr 6067: my $path=LONCAPA::tempdir();
1.168 albertel 6068: if (tie(%hash,'GDBM_File',
6069: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6070: &GDBM_READER(),0640)) {
1.168 albertel 6071: my $version=$hash{"version:$symb"};
6072: $returnhash{'version'}=$version;
6073: my $scope;
6074: for ($scope=1;$scope<=$version;$scope++) {
6075: my $vkeys=$hash{"$scope:keys:$symb"};
6076: my @keys=split(/:/,$vkeys);
6077: my $key;
6078: $returnhash{"$scope:keys"}=$vkeys;
6079: foreach $key (@keys) {
1.591 albertel 6080: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6081: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6082: }
6083: }
1.168 albertel 6084: if (!(untie(%hash))) {
6085: return "error:$!";
6086: }
6087: } else {
6088: return "error:$!";
6089: }
6090: return %returnhash;
1.167 albertel 6091: }
6092:
1.9 www 6093: # ----------------------------------------------------------------------- Store
6094:
6095: sub store {
1.1172.2.64 raeburn 6096: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6097: my $home='';
6098:
1.168 albertel 6099: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6100:
1.213 www 6101: $symb=&symbclean($symb);
1.122 albertel 6102: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6103:
1.620 albertel 6104: if (!$domain) { $domain=$env{'user.domain'}; }
6105: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6106:
6107: &devalidate($symb,$stuname,$domain);
1.109 www 6108:
6109: $symb=escape($symb);
1.187 www 6110: if (!$namespace) {
1.620 albertel 6111: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6112: return '';
6113: }
6114: }
1.620 albertel 6115: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6116:
1.1172.2.138 raeburn 6117: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6118: $$storehash{'host'}=$perlvar{'lonHostID'};
6119:
1.12 www 6120: my $namevalue='';
1.800 albertel 6121: foreach my $key (keys(%$storehash)) {
6122: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6123: }
1.12 www 6124: $namevalue=~s/\&$//;
1.187 www 6125: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6126: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6127: }
6128:
1.47 www 6129: # -------------------------------------------------------------- Critical Store
6130:
6131: sub cstore {
1.1172.2.64 raeburn 6132: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6133: my $home='';
6134:
1.168 albertel 6135: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6136:
1.213 www 6137: $symb=&symbclean($symb);
1.122 albertel 6138: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6139:
1.620 albertel 6140: if (!$domain) { $domain=$env{'user.domain'}; }
6141: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6142:
6143: &devalidate($symb,$stuname,$domain);
1.109 www 6144:
6145: $symb=escape($symb);
1.187 www 6146: if (!$namespace) {
1.620 albertel 6147: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6148: return '';
6149: }
6150: }
1.620 albertel 6151: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6152:
1.1172.2.138 raeburn 6153: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6154: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6155:
1.47 www 6156: my $namevalue='';
1.800 albertel 6157: foreach my $key (keys(%$storehash)) {
6158: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6159: }
1.47 www 6160: $namevalue=~s/\&$//;
1.187 www 6161: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6162: return critical
1.1172.2.64 raeburn 6163: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6164: }
6165:
1.9 www 6166: # --------------------------------------------------------------------- Restore
6167:
6168: sub restore {
1.124 www 6169: my ($symb,$namespace,$domain,$stuname) = @_;
6170: my $home='';
6171:
1.168 albertel 6172: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6173:
1.122 albertel 6174: if (!$symb) {
1.1172.2.26 raeburn 6175: return if ($namespace eq 'courserequests');
6176: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6177: } else {
1.1172.2.26 raeburn 6178: unless ($namespace eq 'courserequests') {
6179: $symb=&escape(&symbclean($symb));
6180: }
1.122 albertel 6181: }
1.188 www 6182: if (!$namespace) {
1.620 albertel 6183: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6184: return '';
6185: }
6186: }
1.620 albertel 6187: if (!$domain) { $domain=$env{'user.domain'}; }
6188: if (!$stuname) { $stuname=$env{'user.name'}; }
6189: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6190: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6191:
1.12 www 6192: my %returnhash=();
1.800 albertel 6193: foreach my $line (split(/\&/,$answer)) {
6194: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6195: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6196: }
1.75 www 6197: my $version;
6198: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6199: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6200: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6201: }
1.75 www 6202: }
1.13 www 6203: return %returnhash;
1.34 www 6204: }
6205:
6206: # ---------------------------------------------------------- Course Description
1.1118 foxr 6207: #
6208: #
1.34 www 6209:
6210: sub coursedescription {
1.731 albertel 6211: my ($courseid,$args)=@_;
1.34 www 6212: $courseid=~s/^\///;
1.49 www 6213: $courseid=~s/\_/\//g;
1.34 www 6214: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6215: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6216: my $normalid=$cdomain.'_'.$cnum;
6217: # need to always cache even if we get errors otherwise we keep
6218: # trying and trying and trying to get the course description.
6219: my %envhash=();
6220: my %returnhash=();
1.731 albertel 6221:
6222: my $expiretime=600;
6223: if ($env{'request.course.id'} eq $normalid) {
6224: $expiretime=120;
6225: }
6226:
6227: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6228: if (!$args->{'freshen_cache'}
6229: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6230: foreach my $key (keys(%env)) {
6231: next if ($key !~ /^\Q$prefix\E(.*)/);
6232: my ($setting) = $1;
6233: $returnhash{$setting} = $env{$key};
6234: }
6235: return %returnhash;
6236: }
6237:
1.1118 foxr 6238: # get the data again
6239:
1.731 albertel 6240: if (!$args->{'one_time'}) {
6241: $envhash{'course.'.$normalid.'.last_cache'}=time;
6242: }
1.811 albertel 6243:
1.34 www 6244: if ($chome ne 'no_host') {
1.302 albertel 6245: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6246: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6247: my $username = $env{'user.name'}; # Defult username
6248: if(defined $args->{'user'}) {
6249: $username = $args->{'user'};
6250: }
1.129 albertel 6251: $returnhash{'home'}= $chome;
6252: $returnhash{'domain'} = $cdomain;
6253: $returnhash{'num'} = $cnum;
1.741 raeburn 6254: if (!defined($returnhash{'type'})) {
6255: $returnhash{'type'} = 'Course';
6256: }
1.130 albertel 6257: while (my ($name,$value) = each %returnhash) {
1.53 www 6258: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6259: }
1.270 www 6260: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6261: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6262: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6263: $envhash{'course.'.$normalid.'.home'}=$chome;
6264: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6265: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6266: }
6267: }
1.731 albertel 6268: if (!$args->{'one_time'}) {
1.949 raeburn 6269: &appenv(\%envhash);
1.731 albertel 6270: }
1.302 albertel 6271: return %returnhash;
1.461 www 6272: }
6273:
1.1080 raeburn 6274: sub update_released_required {
6275: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6276: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6277: $cid = $env{'request.course.id'};
6278: $cdom = $env{'course.'.$cid.'.domain'};
6279: $cnum = $env{'course.'.$cid.'.num'};
6280: $chome = $env{'course.'.$cid.'.home'};
6281: }
6282: if ($needsrelease) {
6283: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6284: my $needsupdate;
6285: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6286: $needsupdate = 1;
6287: } else {
6288: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6289: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6290: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6291: $needsupdate = 1;
6292: }
6293: }
6294: if ($needsupdate) {
6295: my %needshash = (
6296: 'internal.releaserequired' => $needsrelease,
6297: );
6298: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6299: if ($putresult eq 'ok') {
6300: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6301: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6302: if (ref($crsinfo{$cid}) eq 'HASH') {
6303: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6304: &courseidput($cdom,\%crsinfo,$chome,'notime');
6305: }
6306: }
6307: }
6308: }
6309: return;
6310: }
6311:
1.461 www 6312: # -------------------------------------------------See if a user is privileged
6313:
6314: sub privileged {
1.1172.2.23 raeburn 6315: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6316: my $now = time;
1.1172.2.23 raeburn 6317: my $roles;
6318: if (ref($possroles) eq 'ARRAY') {
6319: $roles = $possroles;
6320: } else {
6321: $roles = ['dc','su'];
6322: }
6323: if (ref($possdomains) eq 'ARRAY') {
6324: my %privileged = &privileged_by_domain($possdomains,$roles);
6325: foreach my $dom (@{$possdomains}) {
6326: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6327: (ref($privileged{$dom}) eq 'HASH')) {
6328: foreach my $role (@{$roles}) {
6329: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6330: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6331: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6332: return 1 unless (($end && $end < $now) ||
6333: ($start && $start > $now));
6334: }
6335: }
6336: }
6337: }
6338: }
6339: } else {
6340: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6341: my $now = time;
1.1170 droeschl 6342:
1.1172.2.58 raeburn 6343: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6344: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6345: if (grep(/^\Q$trole\E$/,@{$roles})) {
6346: return 1 unless ($tend && $tend < $now)
6347: or ($tstart && $tstart > $now);
1.1170 droeschl 6348: }
1.1172.2.23 raeburn 6349: }
6350: }
1.461 www 6351: return 0;
1.9 www 6352: }
1.1 albertel 6353:
1.1172.2.23 raeburn 6354: sub privileged_by_domain {
6355: my ($domains,$roles) = @_;
6356: my %privileged = ();
6357: my $cachetime = 60*60*24;
6358: my $now = time;
6359: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6360: return %privileged;
6361: }
6362: foreach my $dom (@{$domains}) {
6363: next if (ref($privileged{$dom}) eq 'HASH');
6364: my $needroles;
6365: foreach my $role (@{$roles}) {
6366: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6367: if (defined($cached)) {
6368: if (ref($result) eq 'HASH') {
6369: $privileged{$dom}{$role} = $result;
6370: }
6371: } else {
6372: $needroles = 1;
6373: }
6374: }
6375: if ($needroles) {
6376: my %dompersonnel = &get_domain_roles($dom,$roles);
6377: $privileged{$dom} = {};
6378: foreach my $server (keys(%dompersonnel)) {
6379: if (ref($dompersonnel{$server}) eq 'HASH') {
6380: foreach my $item (keys(%{$dompersonnel{$server}})) {
6381: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6382: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6383: next if ($end && $end < $now);
6384: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6385: $dompersonnel{$server}{$item};
6386: }
6387: }
6388: }
6389: if (ref($privileged{$dom}) eq 'HASH') {
6390: foreach my $role (@{$roles}) {
6391: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6392: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6393: } else {
6394: my %hash = ();
6395: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6396: }
6397: }
6398: }
6399: }
6400: }
6401: return %privileged;
6402: }
6403:
1.103 harris41 6404: # -------------------------------------------------------- Get user privileges
1.11 www 6405:
6406: sub rolesinit {
1.1169 droeschl 6407: my ($domain, $username) = @_;
6408: my %userroles = ('user.login.time' => time);
6409: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6410:
6411: # firstaccess and timerinterval are related to timed maps/resources.
6412: # also, blocking can be triggered by an activating timer
6413: # it's saved in the user's %env.
6414: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6415: my %timerinterval = &dump('timerinterval', $domain, $username);
6416: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6417: %timerintchk, %timerintenv);
6418:
1.1162 raeburn 6419: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6420: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6421: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6422: }
1.1169 droeschl 6423:
1.1162 raeburn 6424: foreach my $key (keys(%timerinterval)) {
6425: my ($cid,$rest) = split(/\0/,$key);
6426: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6427: }
1.1169 droeschl 6428:
1.11 www 6429: my %allroles=();
1.1162 raeburn 6430: my %allgroups=();
1.11 www 6431:
1.1172.2.58 raeburn 6432: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6433: my $role = $rolesdump{$area};
6434: $area =~ s/\_\w\w$//;
6435:
6436: my ($trole, $tend, $tstart, $group_privs);
6437:
6438: if ($role =~ /^cr/) {
6439: # Custom role, defined by a user
6440: # e.g., user.role.cr/msu/smith/mynewrole
6441: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6442: $trole = $1;
6443: ($tend, $tstart) = split('_', $2);
6444: } else {
6445: $trole = $role;
6446: }
6447: } elsif ($role =~ m|^gr/|) {
6448: # Role of member in a group, defined within a course/community
6449: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6450: ($trole, $tend, $tstart) = split(/_/, $role);
6451: next if $tstart eq '-1';
6452: ($trole, $group_privs) = split(/\//, $trole);
6453: $group_privs = &unescape($group_privs);
6454: } else {
6455: # Just a normal role, defined in roles.tab
6456: ($trole, $tend, $tstart) = split(/_/,$role);
6457: }
6458:
6459: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6460: $username);
6461: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6462:
6463: # role expired or not available yet?
6464: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6465: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6466:
6467: next if $area eq '' or $trole eq '';
6468:
6469: my $spec = "$trole.$area";
6470: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6471:
6472: if ($trole =~ /^cr\//) {
6473: # Custom role, defined by a user
6474: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6475: } elsif ($trole eq 'gr') {
6476: # Role of a member in a group, defined within a course/community
6477: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6478: next;
6479: } else {
6480: # Normal role, defined in roles.tab
6481: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6482: }
6483:
6484: my $cid = $tdomain.'_'.$trest;
6485: unless ($firstaccchk{$cid}) {
6486: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6487: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6488: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6489: $coursetimerstarts{$cid}{$item};
6490: }
6491: }
6492: $firstaccchk{$cid} = 1;
6493: }
6494: unless ($timerintchk{$cid}) {
6495: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6496: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6497: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6498: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6499: }
1.12 www 6500: }
1.1169 droeschl 6501: $timerintchk{$cid} = 1;
1.191 harris41 6502: }
1.11 www 6503: }
1.1169 droeschl 6504:
1.1172.2.91 raeburn 6505: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6506: \%allroles, \%allgroups);
1.1169 droeschl 6507: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6508: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6509:
1.1162 raeburn 6510: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6511: }
6512:
1.567 raeburn 6513: sub set_arearole {
1.1172.2.19 raeburn 6514: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6515: unless ($nolog) {
1.567 raeburn 6516: # log the associated role with the area
1.1172.2.19 raeburn 6517: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6518: }
1.743 albertel 6519: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6520: }
6521:
6522: sub custom_roleprivs {
6523: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6524: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6525: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6526: if (&hostname($homsvr) ne '') {
1.567 raeburn 6527: my ($rdummy,$roledef)=
6528: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6529: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6530: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6531: if (defined($syspriv)) {
1.1043 raeburn 6532: if ($trest =~ /^$match_community$/) {
6533: $syspriv =~ s/bre\&S//;
6534: }
1.567 raeburn 6535: $$allroles{'cm./'}.=':'.$syspriv;
6536: $$allroles{$spec.'./'}.=':'.$syspriv;
6537: }
6538: if ($tdomain ne '') {
6539: if (defined($dompriv)) {
6540: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6541: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6542: }
6543: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6544: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6545: my $rolename = $1;
6546: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6547: }
1.567 raeburn 6548: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6549: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6550: }
6551: }
6552: }
6553: }
6554: }
6555:
1.1172.2.89 raeburn 6556: sub course_adhocrole_privs {
6557: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6558: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6559: if ($overrides{"internal.adhocpriv.$rolename"}) {
6560: my (%currprivs,%storeprivs);
6561: foreach my $item (split(/:/,$coursepriv)) {
6562: my ($priv,$restrict) = split(/\&/,$item);
6563: $currprivs{$priv} = $restrict;
6564: }
6565: my (%possadd,%possremove,%full);
6566: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6567: my ($priv,$restrict)=split(/\&/,$item);
6568: $full{$priv} = $restrict;
6569: }
6570: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6571: next if ($item eq '');
6572: my ($rule,$rest) = split(/=/,$item);
6573: next unless (($rule eq 'off') || ($rule eq 'on'));
6574: foreach my $priv (split(/:/,$rest)) {
6575: if ($priv ne '') {
6576: if ($rule eq 'off') {
6577: $possremove{$priv} = 1;
6578: } else {
6579: $possadd{$priv} = 1;
6580: }
6581: }
6582: }
6583: }
6584: foreach my $priv (sort(keys(%full))) {
6585: if (exists($currprivs{$priv})) {
6586: unless (exists($possremove{$priv})) {
6587: $storeprivs{$priv} = $currprivs{$priv};
6588: }
6589: } elsif (exists($possadd{$priv})) {
6590: $storeprivs{$priv} = $full{$priv};
6591: }
6592: }
6593: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6594: }
6595: return $coursepriv;
6596: }
6597:
1.678 raeburn 6598: sub group_roleprivs {
6599: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6600: my $access = 1;
6601: my $now = time;
6602: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6603: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6604: if ($access) {
1.811 albertel 6605: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6606: $$allgroups{$course}{$group} .=':'.$group_privs;
6607: }
6608: }
1.567 raeburn 6609:
6610: sub standard_roleprivs {
6611: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6612: if (defined($pr{$trole.':s'})) {
6613: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6614: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6615: }
6616: if ($tdomain ne '') {
6617: if (defined($pr{$trole.':d'})) {
6618: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6619: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6620: }
6621: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6622: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6623: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6624: }
6625: }
6626: }
6627:
6628: sub set_userprivs {
1.1064 raeburn 6629: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6630: my $author=0;
6631: my $adv=0;
1.1172.2.91 raeburn 6632: my $rar=0;
1.678 raeburn 6633: my %grouproles = ();
6634: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6635: my @groupkeys;
1.1000 raeburn 6636: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6637: push(@groupkeys,$role);
6638: }
6639: if (ref($groups_roles) eq 'HASH') {
6640: foreach my $key (keys(%{$groups_roles})) {
6641: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6642: push(@groupkeys,$key);
6643: }
6644: }
6645: }
6646: if (@groupkeys > 0) {
6647: foreach my $role (@groupkeys) {
6648: my ($trole,$area,$sec,$extendedarea);
6649: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6650: $trole = $1;
6651: $area = $2;
6652: $sec = $3;
6653: $extendedarea = $area.$sec;
6654: if (exists($$allgroups{$area})) {
6655: foreach my $group (keys(%{$$allgroups{$area}})) {
6656: my $spec = $trole.'.'.$extendedarea;
6657: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6658: $$allgroups{$area}{$group};
1.1064 raeburn 6659: }
1.678 raeburn 6660: }
6661: }
6662: }
6663: }
6664: }
1.800 albertel 6665: foreach my $group (keys(%grouproles)) {
6666: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6667: }
1.800 albertel 6668: foreach my $role (keys(%{$allroles})) {
6669: my %thesepriv;
1.941 raeburn 6670: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6671: foreach my $item (split(/:/,$$allroles{$role})) {
6672: if ($item ne '') {
6673: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6674: if ($restrictions eq '') {
6675: $thesepriv{$privilege}='F';
6676: } elsif ($thesepriv{$privilege} ne 'F') {
6677: $thesepriv{$privilege}.=$restrictions;
6678: }
6679: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6680: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6681: }
6682: }
6683: my $thesestr='';
1.1104 raeburn 6684: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6685: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6686: }
6687: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6688: }
1.1172.2.91 raeburn 6689: return ($author,$adv,$rar);
1.567 raeburn 6690: }
6691:
1.994 raeburn 6692: sub role_status {
1.1104 raeburn 6693: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6694: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6695: my ($one,$two) = split(m{\./},$rolekey,2);
6696: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6697: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6698: $$where = '/'.$two;
1.994 raeburn 6699: $$trolecode=$$role.'.'.$$where;
6700: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6701: $$tstatus='is';
1.1104 raeburn 6702: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6703: $$tstatus='future';
1.1034 raeburn 6704: if ($$tstart<$now) {
6705: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6706: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6707: my (%allroles,%allgroups,$group_privs,
6708: %groups_roles,@rolecodes);
1.1002 raeburn 6709: my %userroles = (
6710: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6711: );
1.1064 raeburn 6712: @rolecodes = ('cm');
1.1002 raeburn 6713: my $spec=$$role.'.'.$$where;
6714: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6715: if ($$role =~ /^cr\//) {
6716: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6717: push(@rolecodes,'cr');
1.1002 raeburn 6718: } elsif ($$role eq 'gr') {
1.1064 raeburn 6719: push(@rolecodes,$$role);
1.1002 raeburn 6720: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6721: $env{'user.name'});
1.1064 raeburn 6722: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6723: (undef,my $group_privs) = split(/\//,$trole);
6724: $group_privs = &unescape($group_privs);
6725: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6726: 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 6727: &get_groups_roles($tdomain,$trest,
6728: \%course_roles,\@rolecodes,
6729: \%groups_roles);
1.1002 raeburn 6730: } else {
1.1064 raeburn 6731: push(@rolecodes,$$role);
1.1002 raeburn 6732: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6733: }
1.1172.2.91 raeburn 6734: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6735: \%groups_roles);
1.1064 raeburn 6736: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6737: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6738: }
6739: }
1.1034 raeburn 6740: $$tstatus = 'is';
1.1002 raeburn 6741: }
1.994 raeburn 6742: }
6743: if ($$tend) {
1.1104 raeburn 6744: if ($$tend<$update) {
1.994 raeburn 6745: $$tstatus='expired';
6746: } elsif ($$tend<$now) {
6747: $$tstatus='will_not';
6748: }
6749: }
6750: }
6751: }
6752: }
6753:
1.1104 raeburn 6754: sub get_groups_roles {
6755: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6756: return unless((ref($cdom_courseroles) eq 'HASH') &&
6757: (ref($rolecodes) eq 'ARRAY') &&
6758: (ref($groups_roles) eq 'HASH'));
6759: if (keys(%{$cdom_courseroles}) > 0) {
6760: my ($cnum) = ($rest =~ /^($match_courseid)/);
6761: if ($cdom ne '' && $cnum ne '') {
6762: foreach my $key (keys(%{$cdom_courseroles})) {
6763: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6764: my $crsrole = $1;
6765: my $crssec = $2;
6766: if ($crsrole =~ /^cr/) {
6767: unless (grep(/^cr$/,@{$rolecodes})) {
6768: push(@{$rolecodes},'cr');
6769: }
6770: } else {
6771: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6772: push(@{$rolecodes},$crsrole);
6773: }
6774: }
6775: my $rolekey = "$crsrole./$cdom/$cnum";
6776: if ($crssec ne '') {
6777: $rolekey .= "/$crssec";
6778: }
6779: $rolekey .= './';
6780: $groups_roles->{$rolekey} = $rolecodes;
6781: }
6782: }
6783: }
6784: }
6785: return;
6786: }
6787:
6788: sub delete_env_groupprivs {
6789: my ($where,$courseroles,$possroles) = @_;
6790: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6791: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6792: unless (ref($courseroles->{$udom}) eq 'HASH') {
6793: %{$courseroles->{$udom}} =
6794: &get_my_roles('','','userroles',['active'],
6795: $possroles,[$udom],1);
6796: }
6797: if (ref($courseroles->{$udom}) eq 'HASH') {
6798: foreach my $item (keys(%{$courseroles->{$udom}})) {
6799: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6800: my $area = '/'.$cdom.'/'.$cnum;
6801: my $privkey = "user.priv.$crsrole.$area";
6802: if ($crssec ne '') {
6803: $privkey .= '/'.$crssec;
6804: }
6805: $privkey .= ".$area/$group";
6806: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6807: }
6808: }
6809: return;
6810: }
6811:
1.994 raeburn 6812: sub check_adhoc_privs {
1.1172.2.86 raeburn 6813: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6814: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6815: if ($sec) {
6816: $cckey .= '/'.$sec;
6817: }
1.1172.2.9 raeburn 6818: my $setprivs;
1.994 raeburn 6819: if ($env{$cckey}) {
6820: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6821: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6822: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6823: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6824: $setprivs = 1;
1.994 raeburn 6825: }
6826: } else {
1.1172.2.87 raeburn 6827: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6828: $setprivs = 1;
1.994 raeburn 6829: }
1.1172.2.9 raeburn 6830: return $setprivs;
1.994 raeburn 6831: }
6832:
6833: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6834: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6835: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6836: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6837: if ($sec ne '') {
6838: $area .= '/'.$sec;
6839: }
1.994 raeburn 6840: my $spec = $role.'.'.$area;
6841: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6842: $env{'user.name'},1);
1.1172.2.84 raeburn 6843: my %rolehash = ();
1.1172.2.89 raeburn 6844: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6845: my $rolename = $1;
1.1172.2.84 raeburn 6846: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6847: my %domdef = &get_domain_defaults($dcdom);
6848: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6849: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6850: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6851: }
6852: }
1.1172.2.84 raeburn 6853: } else {
6854: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6855: }
1.1172.2.91 raeburn 6856: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6857: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6858: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6859: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6860: &appenv( {'request.role' => $spec,
6861: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6862: 'request.course.sec' => $sec,
1.1088 raeburn 6863: }
6864: );
6865: my $tadv=0;
6866: if (&allowed('adv') eq 'F') { $tadv=1; }
6867: &appenv({'request.role.adv' => $tadv});
6868: }
1.994 raeburn 6869: }
6870:
1.12 www 6871: # --------------------------------------------------------------- get interface
6872:
6873: sub get {
1.131 albertel 6874: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6875: my $items='';
1.800 albertel 6876: foreach my $item (@$storearr) {
6877: $items.=&escape($item).'&';
1.191 harris41 6878: }
1.12 www 6879: $items=~s/\&$//;
1.620 albertel 6880: if (!$udomain) { $udomain=$env{'user.domain'}; }
6881: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6882: my $uhome=&homeserver($uname,$udomain);
6883:
1.133 albertel 6884: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6885: my @pairs=split(/\&/,$rep);
1.273 albertel 6886: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6887: return @pairs;
6888: }
1.15 www 6889: my %returnhash=();
1.42 www 6890: my $i=0;
1.800 albertel 6891: foreach my $item (@$storearr) {
6892: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6893: $i++;
1.191 harris41 6894: }
1.15 www 6895: return %returnhash;
1.27 www 6896: }
6897:
6898: # --------------------------------------------------------------- del interface
6899:
6900: sub del {
1.133 albertel 6901: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6902: my $items='';
1.800 albertel 6903: foreach my $item (@$storearr) {
6904: $items.=&escape($item).'&';
1.191 harris41 6905: }
1.984 neumanie 6906:
1.27 www 6907: $items=~s/\&$//;
1.620 albertel 6908: if (!$udomain) { $udomain=$env{'user.domain'}; }
6909: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6910: my $uhome=&homeserver($uname,$udomain);
6911: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6912: }
6913:
6914: # -------------------------------------------------------------- dump interface
6915:
1.1172.2.22 raeburn 6916: sub unserialize {
6917: my ($rep, $escapedkeys) = @_;
6918:
6919: return {} if $rep =~ /^error/;
6920:
6921: my %returnhash=();
6922: foreach my $item (split(/\&/,$rep)) {
6923: my ($key, $value) = split(/=/, $item, 2);
6924: $key = unescape($key) unless $escapedkeys;
6925: next if $key =~ /^error: 2 /;
6926: $returnhash{$key} = &thaw_unescape($value);
6927: }
6928: return \%returnhash;
6929: }
6930:
6931: # see Lond::dump_with_regexp
6932: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6933: sub dump {
1.1172.2.22 raeburn 6934: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6935: if (!$udomain) { $udomain=$env{'user.domain'}; }
6936: if (!$uname) { $uname=$env{'user.name'}; }
6937: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6938:
1.1172.2.55 raeburn 6939: if ($regexp) {
6940: $regexp=&escape($regexp);
6941: } else {
6942: $regexp='.';
6943: }
1.1172.2.22 raeburn 6944: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6945: # user is hosted on this machine
1.1172.2.55 raeburn 6946: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6947: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6948: return %{&unserialize($reply, $escapedkeys)};
6949: }
1.1166 raeburn 6950: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6951: my @pairs=split(/\&/,$rep);
6952: my %returnhash=();
1.1098 foxr 6953: if (!($rep =~ /^error/ )) {
6954: foreach my $item (@pairs) {
6955: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6956: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6957: next if ($key =~ /^error: 2 /);
6958: $returnhash{$key}=&thaw_unescape($value);
6959: }
1.755 albertel 6960: }
6961: return %returnhash;
1.407 www 6962: }
6963:
1.1098 foxr 6964:
1.717 albertel 6965: # --------------------------------------------------------- dumpstore interface
6966:
6967: sub dumpstore {
6968: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6969: # same as dump but keys must be escaped. They may contain colon separated
6970: # lists of values that may themself contain colons (e.g. symbs).
6971: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6972: }
6973:
1.407 www 6974: # -------------------------------------------------------------- keys interface
6975:
6976: sub getkeys {
6977: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6978: if (!$udomain) { $udomain=$env{'user.domain'}; }
6979: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6980: my $uhome=&homeserver($uname,$udomain);
6981: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6982: my @keyarray=();
1.800 albertel 6983: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6984: next if ($key =~ /^error: 2 /);
1.800 albertel 6985: push(@keyarray,&unescape($key));
1.407 www 6986: }
6987: return @keyarray;
1.318 matthew 6988: }
6989:
1.319 matthew 6990: # --------------------------------------------------------------- currentdump
6991: sub currentdump {
1.328 matthew 6992: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6993: $courseid = $env{'request.course.id'} if (! defined($courseid));
6994: $sdom = $env{'user.domain'} if (! defined($sdom));
6995: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6996: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6997: my $rep;
6998:
6999: if (grep { $_ eq $uhome } current_machine_ids()) {
7000: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7001: $courseid)));
7002: } else {
7003: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7004: }
7005:
1.318 matthew 7006: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7007: #
1.318 matthew 7008: my %returnhash=();
1.319 matthew 7009: #
7010: if ($rep eq "unknown_cmd") {
7011: # an old lond will not know currentdump
7012: # Do a dump and make it look like a currentdump
1.822 albertel 7013: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7014: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7015: my %hash = @tmp;
7016: @tmp=();
1.424 matthew 7017: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7018: } else {
7019: my @pairs=split(/\&/,$rep);
1.800 albertel 7020: foreach my $pair (@pairs) {
7021: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7022: my ($symb,$param) = split(/:/,$key);
7023: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7024: &thaw_unescape($value);
1.319 matthew 7025: }
1.191 harris41 7026: }
1.12 www 7027: return %returnhash;
1.424 matthew 7028: }
7029:
7030: sub convert_dump_to_currentdump{
7031: my %hash = %{shift()};
7032: my %returnhash;
7033: # Code ripped from lond, essentially. The only difference
7034: # here is the unescaping done by lonnet::dump(). Conceivably
7035: # we might run in to problems with parameter names =~ /^v\./
7036: while (my ($key,$value) = each(%hash)) {
7037: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7038: $symb = &unescape($symb);
7039: $param = &unescape($param);
1.424 matthew 7040: next if ($v eq 'version' || $symb eq 'keys');
7041: next if (exists($returnhash{$symb}) &&
7042: exists($returnhash{$symb}->{$param}) &&
7043: $returnhash{$symb}->{'v.'.$param} > $v);
7044: $returnhash{$symb}->{$param}=$value;
7045: $returnhash{$symb}->{'v.'.$param}=$v;
7046: }
7047: #
7048: # Remove all of the keys in the hashes which keep track of
7049: # the version of the parameter.
7050: while (my ($symb,$param_hash) = each(%returnhash)) {
7051: # use a foreach because we are going to delete from the hash.
7052: foreach my $key (keys(%$param_hash)) {
7053: delete($param_hash->{$key}) if ($key =~ /^v\./);
7054: }
7055: }
7056: return \%returnhash;
1.12 www 7057: }
7058:
1.627 albertel 7059: # ------------------------------------------------------ critical inc interface
7060:
7061: sub cinc {
7062: return &inc(@_,'critical');
7063: }
7064:
1.449 matthew 7065: # --------------------------------------------------------------- inc interface
7066:
7067: sub inc {
1.627 albertel 7068: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7069: if (!$udomain) { $udomain=$env{'user.domain'}; }
7070: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7071: my $uhome=&homeserver($uname,$udomain);
7072: my $items='';
7073: if (! ref($store)) {
7074: # got a single value, so use that instead
7075: $items = &escape($store).'=&';
7076: } elsif (ref($store) eq 'SCALAR') {
7077: $items = &escape($$store).'=&';
7078: } elsif (ref($store) eq 'ARRAY') {
7079: $items = join('=&',map {&escape($_);} @{$store});
7080: } elsif (ref($store) eq 'HASH') {
7081: while (my($key,$value) = each(%{$store})) {
7082: $items.= &escape($key).'='.&escape($value).'&';
7083: }
7084: }
7085: $items=~s/\&$//;
1.627 albertel 7086: if ($critical) {
7087: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7088: } else {
7089: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7090: }
1.449 matthew 7091: }
7092:
1.12 www 7093: # --------------------------------------------------------------- put interface
7094:
7095: sub put {
1.134 albertel 7096: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7097: if (!$udomain) { $udomain=$env{'user.domain'}; }
7098: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7099: my $uhome=&homeserver($uname,$udomain);
1.12 www 7100: my $items='';
1.800 albertel 7101: foreach my $item (keys(%$storehash)) {
7102: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7103: }
1.12 www 7104: $items=~s/\&$//;
1.134 albertel 7105: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7106: }
7107:
1.631 albertel 7108: # ------------------------------------------------------------ newput interface
7109:
7110: sub newput {
7111: my ($namespace,$storehash,$udomain,$uname)=@_;
7112: if (!$udomain) { $udomain=$env{'user.domain'}; }
7113: if (!$uname) { $uname=$env{'user.name'}; }
7114: my $uhome=&homeserver($uname,$udomain);
7115: my $items='';
7116: foreach my $key (keys(%$storehash)) {
7117: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7118: }
7119: $items=~s/\&$//;
7120: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7121: }
7122:
7123: # --------------------------------------------------------- putstore interface
7124:
1.524 raeburn 7125: sub putstore {
1.1172.2.59 raeburn 7126: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7127: if (!$udomain) { $udomain=$env{'user.domain'}; }
7128: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7129: my $uhome=&homeserver($uname,$udomain);
7130: my $items='';
1.715 albertel 7131: foreach my $key (keys(%$storehash)) {
7132: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7133: }
1.715 albertel 7134: $items=~s/\&$//;
1.716 albertel 7135: my $esc_symb=&escape($symb);
7136: my $esc_v=&escape($version);
1.715 albertel 7137: my $reply =
1.716 albertel 7138: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7139: $uhome);
1.1172.2.59 raeburn 7140: if (($tolog) && ($reply eq 'ok')) {
7141: my $namevalue='';
7142: foreach my $key (keys(%{$storehash})) {
7143: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7144: }
1.1172.2.134 raeburn 7145: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7146: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7147: '&host='.&escape($perlvar{'lonHostID'}).
7148: '&version='.$esc_v.
7149: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7150: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7151: }
1.715 albertel 7152: if ($reply eq 'unknown_cmd') {
1.716 albertel 7153: # gfall back to way things use to be done
1.715 albertel 7154: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7155: $uname);
1.524 raeburn 7156: }
1.715 albertel 7157: return $reply;
7158: }
7159:
7160: sub old_putstore {
1.716 albertel 7161: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7162: if (!$udomain) { $udomain=$env{'user.domain'}; }
7163: if (!$uname) { $uname=$env{'user.name'}; }
7164: my $uhome=&homeserver($uname,$udomain);
7165: my %newstorehash;
1.800 albertel 7166: foreach my $item (keys(%$storehash)) {
7167: my $key = $version.':'.&escape($symb).':'.$item;
7168: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7169: }
7170: my $items='';
7171: my %allitems = ();
1.800 albertel 7172: foreach my $item (keys(%newstorehash)) {
7173: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7174: my $key = $1.':keys:'.$2;
7175: $allitems{$key} .= $3.':';
7176: }
1.800 albertel 7177: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7178: }
1.800 albertel 7179: foreach my $item (keys(%allitems)) {
7180: $allitems{$item} =~ s/\:$//;
7181: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7182: }
7183: $items=~s/\&$//;
7184: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7185: }
7186:
1.47 www 7187: # ------------------------------------------------------ critical put interface
7188:
7189: sub cput {
1.134 albertel 7190: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7191: if (!$udomain) { $udomain=$env{'user.domain'}; }
7192: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7193: my $uhome=&homeserver($uname,$udomain);
1.47 www 7194: my $items='';
1.800 albertel 7195: foreach my $item (keys(%$storehash)) {
7196: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7197: }
1.47 www 7198: $items=~s/\&$//;
1.134 albertel 7199: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7200: }
7201:
7202: # -------------------------------------------------------------- eget interface
7203:
7204: sub eget {
1.133 albertel 7205: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7206: my $items='';
1.800 albertel 7207: foreach my $item (@$storearr) {
7208: $items.=&escape($item).'&';
1.191 harris41 7209: }
1.12 www 7210: $items=~s/\&$//;
1.620 albertel 7211: if (!$udomain) { $udomain=$env{'user.domain'}; }
7212: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7213: my $uhome=&homeserver($uname,$udomain);
7214: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7215: my @pairs=split(/\&/,$rep);
7216: my %returnhash=();
1.42 www 7217: my $i=0;
1.800 albertel 7218: foreach my $item (@$storearr) {
7219: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7220: $i++;
1.191 harris41 7221: }
1.12 www 7222: return %returnhash;
7223: }
7224:
1.667 albertel 7225: # ------------------------------------------------------------ tmpput interface
7226: sub tmpput {
1.802 raeburn 7227: my ($storehash,$server,$context)=@_;
1.667 albertel 7228: my $items='';
1.800 albertel 7229: foreach my $item (keys(%$storehash)) {
7230: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7231: }
7232: $items=~s/\&$//;
1.802 raeburn 7233: if (defined($context)) {
7234: $items .= ':'.&escape($context);
7235: }
1.667 albertel 7236: return &reply("tmpput:$items",$server);
7237: }
7238:
7239: # ------------------------------------------------------------ tmpget interface
7240: sub tmpget {
1.688 albertel 7241: my ($token,$server)=@_;
7242: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7243: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7244: my %returnhash;
1.1172.2.85 raeburn 7245: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7246: return %returnhash;
7247: }
1.667 albertel 7248: foreach my $item (split(/\&/,$rep)) {
7249: my ($key,$value)=split(/=/,$item);
7250: $returnhash{&unescape($key)}=&thaw_unescape($value);
7251: }
7252: return %returnhash;
7253: }
7254:
1.1113 raeburn 7255: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7256: sub tmpdel {
7257: my ($token,$server)=@_;
7258: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7259: return &reply("tmpdel:$token",$server);
7260: }
7261:
1.1172.2.13 raeburn 7262: # ------------------------------------------------------------ get_timebased_id
7263:
7264: sub get_timebased_id {
7265: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7266: $maxtries) = @_;
7267: my ($newid,$error,$dellock);
7268: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7269: return ('','ok','invalid call to get suffix');
7270: }
7271:
7272: # set defaults for any optional args for which values were not supplied
7273: if ($who eq '') {
7274: $who = $env{'user.name'}.':'.$env{'user.domain'};
7275: }
7276: if (!$locktries) {
7277: $locktries = 3;
7278: }
7279: if (!$maxtries) {
7280: $maxtries = 10;
7281: }
7282:
7283: if (($cdom eq '') || ($cnum eq '')) {
7284: if ($env{'request.course.id'}) {
7285: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7286: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7287: }
7288: if (($cdom eq '') || ($cnum eq '')) {
7289: return ('','ok','call to get suffix not in course context');
7290: }
7291: }
7292:
7293: # construct locking item
7294: my $lockhash = {
7295: $prefix."\0".'locked_'.$keyid => $who,
7296: };
7297: my $tries = 0;
7298:
7299: # attempt to get lock on nohist_$namespace file
7300: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7301: while (($gotlock ne 'ok') && $tries <$locktries) {
7302: $tries ++;
7303: sleep 1;
7304: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7305: }
7306:
7307: # attempt to get unique identifier, based on current timestamp
7308: if ($gotlock eq 'ok') {
7309: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7310: my $id = time;
7311: $newid = $id;
1.1172.2.56 raeburn 7312: if ($idtype eq 'addcode') {
7313: $newid .= &sixnum_code();
7314: }
1.1172.2.13 raeburn 7315: my $idtries = 0;
7316: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7317: if ($idtype eq 'concat') {
7318: $newid = $id.$idtries;
1.1172.2.56 raeburn 7319: } elsif ($idtype eq 'addcode') {
7320: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7321: } else {
7322: $newid ++;
7323: }
7324: $idtries ++;
7325: }
7326: if (!exists($inuse{$prefix."\0".$newid})) {
7327: my %new_item = (
7328: $prefix."\0".$newid => $who,
7329: );
7330: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7331: $cdom,$cnum);
7332: if ($putresult ne 'ok') {
7333: undef($newid);
7334: $error = 'error saving new item: '.$putresult;
7335: }
7336: } else {
1.1172.2.56 raeburn 7337: undef($newid);
1.1172.2.13 raeburn 7338: $error = ('error: no unique suffix available for the new item ');
7339: }
7340: # remove lock
7341: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7342: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7343: } else {
7344: $error = "error: could not obtain lockfile\n";
7345: $dellock = 'ok';
1.1172.2.58 raeburn 7346: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7347: $dellock = 'nolock';
7348: }
1.1172.2.13 raeburn 7349: }
7350: return ($newid,$dellock,$error);
7351: }
7352:
1.1172.2.56 raeburn 7353: sub sixnum_code {
7354: my $code;
7355: for (0..6) {
7356: $code .= int( rand(9) );
7357: }
7358: return $code;
7359: }
7360:
1.765 albertel 7361: # -------------------------------------------------- portfolio access checking
7362:
7363: sub portfolio_access {
1.1172.2.77 raeburn 7364: my ($requrl,$clientip) = @_;
1.765 albertel 7365: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7366: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7367: if ($result) {
7368: my %setters;
7369: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7370: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7371: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7372: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7373: return 'B';
7374: }
7375: } else {
1.1172.2.142 raeburn 7376: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7377: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7378: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7379: return 'B';
7380: }
7381: }
7382: }
1.765 albertel 7383: if ($result eq 'ok') {
1.766 albertel 7384: return 'F';
1.765 albertel 7385: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7386: return 'A';
1.765 albertel 7387: }
1.766 albertel 7388: return '';
1.765 albertel 7389: }
7390:
7391: sub get_portfolio_access {
1.1172.2.77 raeburn 7392: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7393:
7394: if (!ref($access_hash)) {
7395: my $current_perms = &get_portfile_permissions($udom,$unum);
7396: my %access_controls = &get_access_controls($current_perms,$group,
7397: $file_name);
7398: $access_hash = $access_controls{$file_name};
7399: }
7400:
1.1172.2.77 raeburn 7401: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7402: my $now = time;
7403: if (ref($access_hash) eq 'HASH') {
7404: foreach my $key (keys(%{$access_hash})) {
7405: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7406: if ($start > $now) {
7407: next;
7408: }
7409: if ($end && $end<$now) {
7410: next;
7411: }
7412: if ($scope eq 'public') {
7413: $public = $key;
7414: last;
7415: } elsif ($scope eq 'guest') {
7416: $guest = $key;
7417: } elsif ($scope eq 'domains') {
7418: push(@domains,$key);
7419: } elsif ($scope eq 'users') {
7420: push(@users,$key);
7421: } elsif ($scope eq 'course') {
7422: push(@courses,$key);
7423: } elsif ($scope eq 'group') {
7424: push(@groups,$key);
1.1172.2.77 raeburn 7425: } elsif ($scope eq 'ip') {
7426: push(@ips,$key);
1.765 albertel 7427: }
7428: }
7429: if ($public) {
7430: return 'ok';
1.1172.2.77 raeburn 7431: } elsif (@ips > 0) {
7432: my $allowed;
7433: foreach my $ipkey (@ips) {
7434: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7435: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7436: $allowed = 1;
7437: last;
7438: }
7439: }
7440: }
7441: if ($allowed) {
7442: return 'ok';
7443: }
1.765 albertel 7444: }
7445: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7446: if ($guest) {
7447: return $guest;
7448: }
7449: } else {
7450: if (@domains > 0) {
7451: foreach my $domkey (@domains) {
7452: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7453: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7454: return 'ok';
7455: }
7456: }
7457: }
7458: }
7459: if (@users > 0) {
7460: foreach my $userkey (@users) {
1.865 raeburn 7461: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7462: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7463: if (ref($item) eq 'HASH') {
7464: if (($item->{'uname'} eq $env{'user.name'}) &&
7465: ($item->{'udom'} eq $env{'user.domain'})) {
7466: return 'ok';
7467: }
7468: }
7469: }
7470: }
1.765 albertel 7471: }
7472: }
7473: my %roleshash;
7474: my @courses_and_groups = @courses;
7475: push(@courses_and_groups,@groups);
7476: if (@courses_and_groups > 0) {
7477: my (%allgroups,%allroles);
7478: my ($start,$end,$role,$sec,$group);
7479: foreach my $envkey (%env) {
1.1060 raeburn 7480: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7481: my $cid = $2.'_'.$3;
7482: if ($1 eq 'gr') {
7483: $group = $4;
7484: $allgroups{$cid}{$group} = $env{$envkey};
7485: } else {
7486: if ($4 eq '') {
7487: $sec = 'none';
7488: } else {
7489: $sec = $4;
7490: }
7491: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7492: }
1.811 albertel 7493: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7494: my $cid = $2.'_'.$3;
7495: if ($4 eq '') {
7496: $sec = 'none';
7497: } else {
7498: $sec = $4;
7499: }
7500: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7501: }
7502: }
7503: if (keys(%allroles) == 0) {
7504: return;
7505: }
7506: foreach my $key (@courses_and_groups) {
7507: my %content = %{$$access_hash{$key}};
7508: my $cnum = $content{'number'};
7509: my $cdom = $content{'domain'};
7510: my $cid = $cdom.'_'.$cnum;
7511: if (!exists($allroles{$cid})) {
7512: next;
7513: }
7514: foreach my $role_id (keys(%{$content{'roles'}})) {
7515: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7516: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7517: my @status = @{$content{'roles'}{$role_id}{'access'}};
7518: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7519: foreach my $role (keys(%{$allroles{$cid}})) {
7520: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7521: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7522: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7523: if (grep/^all$/,@sections) {
7524: return 'ok';
7525: } else {
7526: if (grep/^$sec$/,@sections) {
7527: return 'ok';
7528: }
7529: }
7530: }
7531: }
7532: if (keys(%{$allgroups{$cid}}) == 0) {
7533: if (grep/^none$/,@groups) {
7534: return 'ok';
7535: }
7536: } else {
7537: if (grep/^all$/,@groups) {
7538: return 'ok';
7539: }
7540: foreach my $group (keys(%{$allgroups{$cid}})) {
7541: if (grep/^$group$/,@groups) {
7542: return 'ok';
7543: }
7544: }
7545: }
7546: }
7547: }
7548: }
7549: }
7550: }
7551: if ($guest) {
7552: return $guest;
7553: }
7554: }
7555: }
7556: return;
7557: }
7558:
7559: sub course_group_datechecker {
7560: my ($dates,$now,$status) = @_;
7561: my ($start,$end) = split(/\./,$dates);
7562: if (!$start && !$end) {
7563: return 'ok';
7564: }
7565: if (grep/^active$/,@{$status}) {
7566: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7567: return 'ok';
7568: }
7569: }
7570: if (grep/^previous$/,@{$status}) {
7571: if ($end > $now ) {
7572: return 'ok';
7573: }
7574: }
7575: if (grep/^future$/,@{$status}) {
7576: if ($start > $now) {
7577: return 'ok';
7578: }
7579: }
7580: return;
7581: }
7582:
7583: sub parse_portfolio_url {
7584: my ($url) = @_;
7585:
7586: my ($type,$udom,$unum,$group,$file_name);
7587:
1.823 albertel 7588: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7589: $type = 1;
7590: $udom = $1;
7591: $unum = $2;
7592: $file_name = $3;
1.823 albertel 7593: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7594: $type = 2;
7595: $udom = $1;
7596: $unum = $2;
7597: $group = $3;
7598: $file_name = $3.'/'.$4;
7599: }
7600: if (wantarray) {
7601: return ($type,$udom,$unum,$file_name,$group);
7602: }
7603: return $type;
7604: }
7605:
7606: sub is_portfolio_url {
7607: my ($url) = @_;
7608: return scalar(&parse_portfolio_url($url));
7609: }
7610:
1.798 raeburn 7611: sub is_portfolio_file {
7612: my ($file) = @_;
1.820 raeburn 7613: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7614: return 1;
7615: }
7616: return;
7617: }
7618:
1.976 raeburn 7619: sub usertools_access {
1.1084 raeburn 7620: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7621: my ($access,%tools);
7622: if ($context eq '') {
7623: $context = 'tools';
7624: }
7625: if ($context eq 'requestcourses') {
7626: %tools = (
7627: official => 1,
7628: unofficial => 1,
1.1006 raeburn 7629: community => 1,
1.1172.2.37 raeburn 7630: textbook => 1,
1.985 raeburn 7631: );
1.1172.2.9 raeburn 7632: } elsif ($context eq 'requestauthor') {
7633: %tools = (
7634: requestauthor => 1,
7635: );
1.985 raeburn 7636: } else {
7637: %tools = (
7638: aboutme => 1,
7639: blog => 1,
1.1172.2.6 raeburn 7640: webdav => 1,
1.985 raeburn 7641: portfolio => 1,
7642: );
7643: }
1.976 raeburn 7644: return if (!defined($tools{$tool}));
7645:
1.1172.2.35 raeburn 7646: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7647: $udom = $env{'user.domain'};
7648: $uname = $env{'user.name'};
7649: }
7650:
1.978 raeburn 7651: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7652: if ($action ne 'reload') {
1.985 raeburn 7653: if ($context eq 'requestcourses') {
7654: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7655: } elsif ($context eq 'requestauthor') {
7656: return $env{'environment.canrequest.author'};
1.985 raeburn 7657: } else {
7658: return $env{'environment.availabletools.'.$tool};
7659: }
7660: }
1.976 raeburn 7661: }
7662:
1.1172.2.9 raeburn 7663: my ($toolstatus,$inststatus,$envkey);
7664: if ($context eq 'requestauthor') {
7665: $envkey = $context;
7666: } else {
7667: $envkey = $context.'.'.$tool;
7668: }
1.976 raeburn 7669:
1.985 raeburn 7670: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7671: ($action ne 'reload')) {
1.1172.2.9 raeburn 7672: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7673: $inststatus = $env{'environment.inststatus'};
7674: } else {
1.1084 raeburn 7675: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7676: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7677: $inststatus = $userenvref->{'inststatus'};
7678: } else {
1.1172.2.9 raeburn 7679: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7680: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7681: $inststatus = $userenv{'inststatus'};
7682: }
1.976 raeburn 7683: }
7684:
7685: if ($toolstatus ne '') {
7686: if ($toolstatus) {
7687: $access = 1;
7688: } else {
7689: $access = 0;
7690: }
7691: return $access;
7692: }
7693:
1.1084 raeburn 7694: my ($is_adv,%domdef);
7695: if (ref($is_advref) eq 'HASH') {
7696: $is_adv = $is_advref->{'is_adv'};
7697: } else {
7698: $is_adv = &is_advanced_user($udom,$uname);
7699: }
7700: if (ref($domdefref) eq 'HASH') {
7701: %domdef = %{$domdefref};
7702: } else {
7703: %domdef = &get_domain_defaults($udom);
7704: }
1.976 raeburn 7705: if (ref($domdef{$tool}) eq 'HASH') {
7706: if ($is_adv) {
7707: if ($domdef{$tool}{'_LC_adv'} ne '') {
7708: if ($domdef{$tool}{'_LC_adv'}) {
7709: $access = 1;
7710: } else {
7711: $access = 0;
7712: }
7713: return $access;
7714: }
7715: }
7716: if ($inststatus ne '') {
7717: my ($hasaccess,$hasnoaccess);
7718: foreach my $affiliation (split(/:/,$inststatus)) {
7719: if ($domdef{$tool}{$affiliation} ne '') {
7720: if ($domdef{$tool}{$affiliation}) {
7721: $hasaccess = 1;
7722: } else {
7723: $hasnoaccess = 1;
7724: }
7725: }
7726: }
7727: if ($hasaccess || $hasnoaccess) {
7728: if ($hasaccess) {
7729: $access = 1;
7730: } elsif ($hasnoaccess) {
7731: $access = 0;
7732: }
7733: return $access;
7734: }
7735: } else {
7736: if ($domdef{$tool}{'default'} ne '') {
7737: if ($domdef{$tool}{'default'}) {
7738: $access = 1;
7739: } elsif ($domdef{$tool}{'default'} == 0) {
7740: $access = 0;
7741: }
7742: return $access;
7743: }
7744: }
7745: } else {
1.1172.2.6 raeburn 7746: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7747: $access = 1;
7748: } else {
7749: $access = 0;
7750: }
1.976 raeburn 7751: return $access;
7752: }
7753: }
7754:
1.1050 raeburn 7755: sub is_course_owner {
7756: my ($cdom,$cnum,$udom,$uname) = @_;
7757: if (($udom eq '') || ($uname eq '')) {
7758: $udom = $env{'user.domain'};
7759: $uname = $env{'user.name'};
7760: }
7761: unless (($udom eq '') || ($uname eq '')) {
7762: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7763: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7764: return 1;
7765: } else {
7766: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7767: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7768: return 1;
7769: }
7770: }
7771: }
7772: }
7773: return;
7774: }
7775:
1.976 raeburn 7776: sub is_advanced_user {
7777: my ($udom,$uname) = @_;
1.1085 raeburn 7778: if ($udom ne '' && $uname ne '') {
7779: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7780: if (wantarray) {
7781: return ($env{'user.adv'},$env{'user.author'});
7782: } else {
7783: return $env{'user.adv'};
7784: }
1.1085 raeburn 7785: }
7786: }
1.976 raeburn 7787: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7788: my %allroles;
1.1128 raeburn 7789: my ($is_adv,$is_author);
1.976 raeburn 7790: foreach my $role (keys(%roleshash)) {
7791: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7792: my $area = '/'.$tdomain.'/'.$trest;
7793: if ($sec ne '') {
7794: $area .= '/'.$sec;
7795: }
7796: if (($area ne '') && ($trole ne '')) {
7797: my $spec=$trole.'.'.$area;
7798: if ($trole =~ /^cr\//) {
7799: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7800: } elsif ($trole ne 'gr') {
7801: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7802: }
1.1128 raeburn 7803: if ($trole eq 'au') {
7804: $is_author = 1;
7805: }
1.976 raeburn 7806: }
7807: }
7808: foreach my $role (keys(%allroles)) {
7809: last if ($is_adv);
7810: foreach my $item (split(/:/,$allroles{$role})) {
7811: if ($item ne '') {
7812: my ($privilege,$restrictions)=split(/&/,$item);
7813: if ($privilege eq 'adv') {
7814: $is_adv = 1;
7815: last;
7816: }
7817: }
7818: }
7819: }
1.1128 raeburn 7820: if (wantarray) {
7821: return ($is_adv,$is_author);
7822: }
1.976 raeburn 7823: return $is_adv;
7824: }
1.798 raeburn 7825:
1.1035 raeburn 7826: sub check_can_request {
1.1036 raeburn 7827: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7828: my $canreq = 0;
7829: my ($types,$typename) = &Apache::loncommon::course_types();
7830: my @options = ('approval','validate','autolimit');
7831: my $optregex = join('|',@options);
7832: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7833: foreach my $type (@{$types}) {
7834: if (&usertools_access($env{'user.name'},
7835: $env{'user.domain'},
7836: $type,undef,'requestcourses')) {
7837: $canreq ++;
1.1036 raeburn 7838: if (ref($request_domains) eq 'HASH') {
7839: push(@{$request_domains->{$type}},$env{'user.domain'});
7840: }
1.1035 raeburn 7841: if ($dom eq $env{'user.domain'}) {
7842: $can_request->{$type} = 1;
7843: }
7844: }
7845: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7846: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7847: if (@curr > 0) {
1.1036 raeburn 7848: foreach my $item (@curr) {
7849: if (ref($request_domains) eq 'HASH') {
7850: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7851: if ($otherdom ne '') {
7852: if (ref($request_domains->{$type}) eq 'ARRAY') {
7853: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7854: push(@{$request_domains->{$type}},$otherdom);
7855: }
7856: } else {
7857: push(@{$request_domains->{$type}},$otherdom);
7858: }
7859: }
7860: }
7861: }
7862: unless($dom eq $env{'user.domain'}) {
7863: $canreq ++;
1.1035 raeburn 7864: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7865: $can_request->{$type} = 1;
7866: }
7867: }
7868: }
7869: }
7870: }
7871: }
7872: return $canreq;
7873: }
7874:
1.341 www 7875: # ---------------------------------------------- Custom access rule evaluation
7876:
7877: sub customaccess {
7878: my ($priv,$uri)=@_;
1.807 albertel 7879: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7880: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7881: $udom = &LONCAPA::clean_domain($udom);
7882: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7883: my $access=0;
1.800 albertel 7884: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7885: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7886: if ($type eq 'user') {
7887: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7888: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7889: if ($tdom) {
7890: if ($tdom ne $env{'user.domain'}) { next; }
7891: }
1.896 albertel 7892: if ($tuname) {
7893: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7894: }
7895: $access=($effect eq 'allow');
7896: last;
7897: }
7898: } else {
7899: if ($role) {
7900: if ($role ne $urole) { next; }
7901: }
7902: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7903: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7904: if ($tdom) {
7905: if ($tdom ne $udom) { next; }
7906: }
7907: if ($tcrs) {
7908: if ($tcrs ne $ucrs) { next; }
7909: }
7910: if ($tsec) {
7911: if ($tsec ne $usec) { next; }
7912: }
7913: $access=($effect eq 'allow');
7914: last;
7915: }
7916: if ($realm eq '' && $role eq '') {
7917: $access=($effect eq 'allow');
7918: }
1.402 bowersj2 7919: }
1.341 www 7920: }
7921: return $access;
7922: }
7923:
1.103 harris41 7924: # ------------------------------------------------- Check for a user privilege
1.12 www 7925:
7926: sub allowed {
1.1172.2.126 raeburn 7927: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7928: my $ver_orguri=$uri;
1.439 www 7929: $uri=&deversion($uri);
1.152 www 7930: my $orguri=$uri;
1.52 www 7931: $uri=&declutter($uri);
1.809 raeburn 7932:
1.810 raeburn 7933: if ($priv eq 'evb') {
7934: # Evade communication block restrictions for specified role in a course
7935: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7936: return $1;
7937: } else {
7938: return;
7939: }
7940: }
7941:
1.620 albertel 7942: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7943: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7944: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7945: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7946: && ($priv eq 'bre')) {
1.14 www 7947: return 'F';
1.159 www 7948: }
7949:
1.545 banghart 7950: # Free bre access to user's own portfolio contents
1.714 raeburn 7951: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7952: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7953: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7954: my %setters;
1.1172.2.142 raeburn 7955: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7956: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7957: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7958: return 'B';
7959: } else {
7960: return 'F';
7961: }
1.545 banghart 7962: }
7963:
1.762 raeburn 7964: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7965: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7966: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7967: if (exists($env{'request.course.id'})) {
7968: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7969: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7970: if (($domain eq $cdom) && ($name eq $cnum)) {
7971: my $courseprivid=$env{'request.course.id'};
7972: $courseprivid=~s/\_/\//;
7973: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7974: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7975: return $1;
1.762 raeburn 7976: } else {
7977: if ($env{'request.course.sec'}) {
7978: $courseprivid.='/'.$env{'request.course.sec'};
7979: }
7980: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7981: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7982: return $2;
7983: }
1.714 raeburn 7984: }
7985: }
7986: }
7987: }
7988:
1.159 www 7989: # Free bre to public access
7990:
7991: if ($priv eq 'bre') {
1.238 www 7992: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7993: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7994: return 'F';
7995: }
1.238 www 7996: if ($copyright eq 'priv') {
7997: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7998: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7999: return '';
8000: }
8001: }
8002: if ($copyright eq 'domain') {
8003: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8004: unless (($env{'user.domain'} eq $1) ||
8005: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8006: return '';
8007: }
1.262 matthew 8008: }
1.620 albertel 8009: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8010: # Library role, so allow browsing of resources in this domain.
8011: return 'F';
1.238 www 8012: }
1.341 www 8013: if ($copyright eq 'custom') {
8014: unless (&customaccess($priv,$uri)) { return ''; }
8015: }
1.14 www 8016: }
1.264 matthew 8017: # Domain coordinator is trying to create a course
1.620 albertel 8018: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8019: # uri is the requested domain in this case.
8020: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8021: # a role of dc for the domain in question.
1.620 albertel 8022: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8023: }
1.29 www 8024:
1.52 www 8025: my $thisallowed='';
8026: my $statecond=0;
8027: my $courseprivid='';
8028:
1.1039 raeburn 8029: my $ownaccess;
1.1043 raeburn 8030: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8031: if (($priv eq 'bro') && ($env{'user.author'})) {
8032: if ($uri eq '') {
8033: $ownaccess = 1;
8034: } else {
8035: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8036: my $udom = $env{'user.domain'};
8037: my $uname = $env{'user.name'};
8038: if ($uri =~ m{^\Q$udom\E/?$}) {
8039: $ownaccess = 1;
1.1040 raeburn 8040: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8041: unless ($uri =~ m{\.\./}) {
8042: $ownaccess = 1;
8043: }
8044: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8045: my $now = time;
8046: if ($uri =~ m{^([^/]+)/?$}) {
8047: my $adom = $1;
8048: foreach my $key (keys(%env)) {
1.1042 raeburn 8049: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8050: my ($start,$end) = split(/\./,$env{$key});
8051: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8052: $ownaccess = 1;
8053: last;
8054: }
8055: }
8056: }
8057: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8058: my $adom = $1;
8059: my $aname = $2;
1.1042 raeburn 8060: foreach my $role ('ca','aa') {
8061: if ($env{"user.role.$role./$adom/$aname"}) {
8062: my ($start,$end) =
1.1172.2.142 raeburn 8063: split(/\./,$env{"user.role.$role./$adom/$aname"});
8064: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8065: $ownaccess = 1;
8066: last;
8067: }
1.1039 raeburn 8068: }
8069: }
8070: }
8071: }
8072: }
8073: }
8074: }
8075:
1.52 www 8076: # Course
8077:
1.620 albertel 8078: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8079: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8080: $thisallowed.=$1;
8081: }
1.52 www 8082: }
1.29 www 8083:
1.52 www 8084: # Domain
8085:
1.620 albertel 8086: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8087: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8088: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8089: $thisallowed.=$1;
8090: }
1.12 www 8091: }
1.52 www 8092:
1.1141 raeburn 8093: # User who is not author or co-author might still be able to edit
8094: # resource of an author in the domain (e.g., if Domain Coordinator).
8095: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8096: (&allowed('mdc',$env{'request.course.id'}))) {
8097: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8098: $thisallowed.=$1;
8099: }
8100: }
8101:
1.52 www 8102: # Course: uri itself is a course
1.66 www 8103: my $courseuri=$uri;
8104: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8105: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8106:
1.620 albertel 8107: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8108: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8109: if ($priv eq 'mip') {
8110: my $rem = $1;
8111: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8112: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8113: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8114: if ($cdom ne '') {
8115: my %passwdconf = &get_passwdconf($cdom);
8116: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8117: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8118: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8119: my @inststatuses = split(':',$env{'environment.inststatus'});
8120: unless (@inststatuses) {
8121: @inststatuses = ('default');
8122: }
8123: foreach my $status (@inststatuses) {
8124: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8125: $thisallowed.=$rem;
8126: }
8127: }
8128: }
8129: }
8130: }
8131: }
8132: }
8133: } else {
8134: unless (($priv eq 'bro') && (!$ownaccess)) {
8135: $thisallowed.=$1;
8136: }
1.1039 raeburn 8137: }
1.12 www 8138: }
1.29 www 8139:
1.665 albertel 8140: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8141: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8142: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8143: $thisallowed='';
1.671 raeburn 8144: my ($match)=&is_on_map($uri);
8145: if ($match) {
8146: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8147: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8148: my $value = $1;
8149: if ($noblockcheck) {
8150: $thisallowed.=$value;
1.1162 raeburn 8151: } else {
1.1172.2.126 raeburn 8152: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8153: if (@blockers > 0) {
8154: $thisallowed = 'B';
8155: } else {
8156: $thisallowed.=$value;
8157: }
1.1162 raeburn 8158: }
1.671 raeburn 8159: }
8160: } else {
1.705 albertel 8161: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8162: if ($refuri) {
8163: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8164: $thisallowed='F';
1.671 raeburn 8165: } else {
8166: $refuri=&declutter($refuri);
8167: my ($match) = &is_on_map($refuri);
8168: if ($match) {
1.1172.2.65 raeburn 8169: if ($noblockcheck) {
1.1162 raeburn 8170: $thisallowed='F';
1.1172.2.65 raeburn 8171: } else {
1.1172.2.127 raeburn 8172: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8173: if (@blockers > 0) {
8174: $thisallowed = 'B';
8175: } else {
8176: $thisallowed='F';
8177: }
1.1162 raeburn 8178: }
1.671 raeburn 8179: }
1.669 raeburn 8180: }
1.671 raeburn 8181: }
8182: }
1.314 www 8183: }
1.492 albertel 8184:
1.766 albertel 8185: if ($priv eq 'bre'
8186: && $thisallowed ne 'F'
8187: && $thisallowed ne '2'
8188: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8189: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8190: }
8191:
1.52 www 8192: # Full access at system, domain or course-wide level? Exit.
1.29 www 8193: if ($thisallowed=~/F/) {
8194: return 'F';
8195: }
8196:
1.52 www 8197: # If this is generating or modifying users, exit with special codes
1.29 www 8198:
1.643 www 8199: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8200: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8201: my ($audom,$auname)=split('/',$uri);
1.643 www 8202: # no author name given, so this just checks on the general right to make a co-author in this domain
8203: unless ($auname) { return $thisallowed; }
8204: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8205: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8206: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8207: ($audom ne $env{'request.role.domain'}))) { return ''; }
8208: }
1.52 www 8209: return $thisallowed;
8210: }
8211: #
1.103 harris41 8212: # Gathered so far: system, domain and course wide privileges
1.52 www 8213: #
8214: # Course: See if uri or referer is an individual resource that is part of
8215: # the course
8216:
1.620 albertel 8217: if ($env{'request.course.id'}) {
1.232 www 8218:
1.1172.2.115 raeburn 8219: # If this is modifying password (internal auth) domains must match for user and user's role.
8220:
8221: if ($priv eq 'mip') {
8222: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8223: return $thisallowed;
8224: } else {
8225: return '';
8226: }
8227: }
8228:
1.620 albertel 8229: $courseprivid=$env{'request.course.id'};
8230: if ($env{'request.course.sec'}) {
8231: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8232: }
8233: $courseprivid=~s/\_/\//;
8234: my $checkreferer=1;
1.232 www 8235: my ($match,$cond)=&is_on_map($uri);
8236: if ($match) {
8237: $statecond=$cond;
1.620 albertel 8238: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8239: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8240: my $value = $1;
8241: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8242: if ($noblockcheck) {
1.1162 raeburn 8243: $thisallowed.=$value;
1.1172.2.65 raeburn 8244: } else {
1.1172.2.126 raeburn 8245: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8246: if (@blockers > 0) {
8247: $thisallowed = 'B';
8248: } else {
8249: $thisallowed.=$value;
8250: }
1.1162 raeburn 8251: }
8252: } else {
8253: $thisallowed.=$value;
8254: }
1.52 www 8255: $checkreferer=0;
8256: }
1.29 www 8257: }
1.1172.2.126 raeburn 8258:
1.148 www 8259: if ($checkreferer) {
1.620 albertel 8260: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8261: unless ($refuri) {
1.800 albertel 8262: foreach my $key (keys(%env)) {
8263: if ($key=~/^httpref\..*\*/) {
8264: my $pattern=$key;
1.156 www 8265: $pattern=~s/^httpref\.\/res\///;
1.148 www 8266: $pattern=~s/\*/\[\^\/\]\+/g;
8267: $pattern=~s/\//\\\//g;
1.152 www 8268: if ($orguri=~/$pattern/) {
1.800 albertel 8269: $refuri=$env{$key};
1.148 www 8270: }
8271: }
1.191 harris41 8272: }
1.148 www 8273: }
1.232 www 8274:
1.148 www 8275: if ($refuri) {
1.152 www 8276: $refuri=&declutter($refuri);
1.232 www 8277: my ($match,$cond)=&is_on_map($refuri);
8278: if ($match) {
8279: my $refstatecond=$cond;
1.620 albertel 8280: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8281: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8282: my $value = $1;
8283: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8284: if ($noblockcheck) {
1.1162 raeburn 8285: $thisallowed.=$value;
1.1172.2.65 raeburn 8286: } else {
1.1172.2.127 raeburn 8287: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8288: if (@blockers > 0) {
8289: $thisallowed = 'B';
8290: } else {
8291: $thisallowed.=$value;
8292: }
1.1162 raeburn 8293: }
8294: } else {
8295: $thisallowed.=$value;
8296: }
1.53 www 8297: $uri=$refuri;
8298: $statecond=$refstatecond;
1.52 www 8299: }
8300: }
1.148 www 8301: }
1.29 www 8302: }
1.52 www 8303: }
1.29 www 8304:
1.52 www 8305: #
1.103 harris41 8306: # Gathered now: all privileges that could apply, and condition number
1.52 www 8307: #
8308: #
8309: # Full or no access?
8310: #
1.29 www 8311:
1.52 www 8312: if ($thisallowed=~/F/) {
8313: return 'F';
8314: }
1.29 www 8315:
1.52 www 8316: unless ($thisallowed) {
8317: return '';
8318: }
1.29 www 8319:
1.52 www 8320: # Restrictions exist, deal with them
8321: #
8322: # C:according to course preferences
8323: # R:according to resource settings
8324: # L:unless locked
8325: # X:according to user session state
8326: #
8327:
8328: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8329: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8330: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8331: # courses, and 2 minutes for current course, in which user has st or ta role
8332: # which is neither expired nor a future role (unless current course).
1.52 www 8333:
1.1172.2.142 raeburn 8334: my ($needlockcheck,$now,$crsonly);
1.52 www 8335: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8336: $now = time;
8337: if ($priv eq 'bre') {
8338: if ($uri ne '') {
8339: if ($orguri =~ m{^/+res/}) {
8340: if ($uri =~ m{^lib/templates/}) {
8341: if ($env{'request.course.id'}) {
8342: $crsonly = 1;
8343: $needlockcheck = 1;
8344: }
8345: } else {
8346: $needlockcheck = 1;
8347: }
8348: } elsif ($env{'request.course.id'}) {
8349: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8350: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8351: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8352: $crsonly = 1;
8353: }
8354: $needlockcheck = 1;
8355: }
8356: }
8357: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8358: $needlockcheck = 1;
8359: }
8360: }
8361: if ($needlockcheck) {
8362: foreach my $envkey (keys(%env)) {
1.54 www 8363: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8364: my $courseid=$2;
8365: my $roleid=$1.'.'.$2;
1.92 www 8366: $courseid=~s/^\///;
1.1172.2.142 raeburn 8367: unless ($env{'request.role'} eq $roleid) {
8368: my ($start,$end) = split(/\./,$env{$envkey});
8369: next unless (($now >= $start) && (!$end || $end > $now));
8370: }
1.54 www 8371: my $expiretime=600;
1.620 albertel 8372: if ($env{'request.role'} eq $roleid) {
1.54 www 8373: $expiretime=120;
8374: }
8375: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8376: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8377: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8378: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8379: }
1.620 albertel 8380: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8381: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8382: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8383: &log($env{'user.domain'},$env{'user.name'},
8384: $env{'user.home'},
1.57 www 8385: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8386: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8387: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8388: return '';
8389: }
8390: }
1.620 albertel 8391: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8392: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8393: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8394: &log($env{'user.domain'},$env{'user.name'},
8395: $env{'user.home'},
1.57 www 8396: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8397: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8398: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8399: return '';
8400: }
8401: }
8402: }
1.29 www 8403: }
1.52 www 8404: }
1.1172.2.126 raeburn 8405:
1.52 www 8406: #
8407: # Rest of the restrictions depend on selected course
8408: #
8409:
1.620 albertel 8410: unless ($env{'request.course.id'}) {
1.766 albertel 8411: if ($thisallowed eq 'A') {
8412: return 'A';
1.814 raeburn 8413: } elsif ($thisallowed eq 'B') {
8414: return 'B';
1.766 albertel 8415: } else {
8416: return '1';
8417: }
1.52 www 8418: }
1.29 www 8419:
1.52 www 8420: #
8421: # Now user is definitely in a course
8422: #
1.53 www 8423:
8424:
8425: # Course preferences
8426:
8427: if ($thisallowed=~/C/) {
1.620 albertel 8428: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8429: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8430: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8431: =~/\Q$rolecode\E/) {
1.1103 raeburn 8432: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8433: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8434: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8435: $env{'request.course.id'});
8436: }
1.237 www 8437: return '';
8438: }
8439:
1.620 albertel 8440: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8441: =~/\Q$unamedom\E/) {
1.1103 raeburn 8442: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8443: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8444: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8445: $env{'request.course.id'});
8446: }
1.54 www 8447: return '';
8448: }
1.53 www 8449: }
8450:
8451: # Resource preferences
8452:
8453: if ($thisallowed=~/R/) {
1.620 albertel 8454: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8455: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8456: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8457: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8458: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8459: }
8460: return '';
1.54 www 8461: }
1.53 www 8462: }
1.30 www 8463:
1.246 www 8464: # Restricted by state or randomout?
1.30 www 8465:
1.52 www 8466: if ($thisallowed=~/X/) {
1.620 albertel 8467: if ($env{'acc.randomout'}) {
1.579 albertel 8468: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8469: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8470: return '';
8471: }
1.247 www 8472: }
8473: if (&condval($statecond)) {
1.52 www 8474: return '2';
8475: } else {
8476: return '';
8477: }
8478: }
1.30 www 8479:
1.766 albertel 8480: if ($thisallowed eq 'A') {
8481: return 'A';
1.814 raeburn 8482: } elsif ($thisallowed eq 'B') {
8483: return 'B';
1.766 albertel 8484: }
1.52 www 8485: return 'F';
1.232 www 8486: }
1.1162 raeburn 8487:
1.1172.2.13 raeburn 8488: # ------------------------------------------- Check construction space access
8489:
8490: sub constructaccess {
8491: my ($url,$setpriv)=@_;
8492:
8493: # We do not allow editing of previous versions of files
8494: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8495:
8496: # Get username and domain from URL
8497: my ($ownername,$ownerdomain,$ownerhome);
8498:
8499: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8500: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8501:
8502: # The URL does not really point to any authorspace, forget it
8503: unless (($ownername) && ($ownerdomain)) { return ''; }
8504:
8505: # Now we need to see if the user has access to the authorspace of
8506: # $ownername at $ownerdomain
8507:
8508: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8509: # Real author for this?
8510: $ownerhome = $env{'user.home'};
8511: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8512: return ($ownername,$ownerdomain,$ownerhome);
8513: }
8514: } else {
8515: # Co-author for this?
8516: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8517: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8518: $ownerhome = &homeserver($ownername,$ownerdomain);
8519: return ($ownername,$ownerdomain,$ownerhome);
8520: }
8521: }
8522:
8523: # We don't have any access right now. If we are not possibly going to do anything about this,
8524: # we might as well leave
8525: unless ($setpriv) { return ''; }
8526:
8527: # Backdoor access?
8528: my $allowed=&allowed('eco',$ownerdomain);
8529: # Nope
8530: unless ($allowed) { return ''; }
8531: # Looks like we may have access, but could be locked by the owner of the construction space
8532: if ($allowed eq 'U') {
8533: my %blocked=&get('environment',['domcoord.author'],
8534: $ownerdomain,$ownername);
8535: # Is blocked by owner
8536: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8537: }
8538: if (($allowed eq 'F') || ($allowed eq 'U')) {
8539: # Grant temporary access
8540: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8541: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8542: if (!$update) { $update = $then; }
8543: my $refresh=$env{'user.refresh.time'};
8544: if (!$refresh) { $refresh = $update; }
8545: my $now = time;
8546: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8547: $now,'ca','constructaccess');
8548: $ownerhome = &homeserver($ownername,$ownerdomain);
8549: return($ownername,$ownerdomain,$ownerhome);
8550: }
8551: # No business here
8552: return '';
8553: }
8554:
1.1172.2.66 raeburn 8555: # ----------------------------------------------------------- Content Blocking
8556:
8557: {
8558: # Caches for faster Course Contents display where content blocking
8559: # is in operation (i.e., interval param set) for timed quiz.
8560: #
8561: # User for whom data are being temporarily cached.
8562: my $cacheduser='';
1.1172.2.126 raeburn 8563: # Course for which data are being temporarily cached.
8564: my $cachedcid='';
1.1172.2.66 raeburn 8565: # Cached blockers for this user (a hash of blocking items).
8566: my %cachedblockers=();
8567: # When the data were last cached.
8568: my $cachedlast='';
8569:
8570: sub load_all_blockers {
1.1172.2.128 raeburn 8571: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8572: if (($uname ne '') && ($udom ne '')) {
8573: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8574: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8575: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8576: return;
8577: }
8578: }
8579: $cachedlast=time;
8580: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8581: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8582: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8583: return;
1.1172.2.66 raeburn 8584: }
8585:
1.1162 raeburn 8586: sub get_comm_blocks {
8587: my ($cdom,$cnum) = @_;
8588: if ($cdom eq '' || $cnum eq '') {
8589: return unless ($env{'request.course.id'});
8590: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8591: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8592: }
8593: my %commblocks;
8594: my $hashid=$cdom.'_'.$cnum;
8595: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8596: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8597: %commblocks = %{$blocksref};
8598: } else {
8599: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8600: my $cachetime = 600;
8601: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8602: }
8603: return %commblocks;
8604: }
8605:
1.1172.2.66 raeburn 8606: sub get_commblock_resources {
8607: my ($blocks) = @_;
8608: my %blockers = ();
8609: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8610: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8611: if ($env{'request.course.sec'}) {
8612: $courseurl .= '/'.$env{'request.course.sec'};
8613: }
8614: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8615: my %commblocks;
8616: if (ref($blocks) eq 'HASH') {
8617: %commblocks = %{$blocks};
8618: } else {
8619: %commblocks = &get_comm_blocks();
8620: }
1.1172.2.66 raeburn 8621: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8622: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8623: return %blockers unless (ref($navmap));
8624: my $now = time;
1.1162 raeburn 8625: foreach my $block (keys(%commblocks)) {
8626: if ($block =~ /^(\d+)____(\d+)$/) {
8627: my ($start,$end) = ($1,$2);
8628: if ($start <= $now && $end >= $now) {
8629: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8630: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8631: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8632: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8633: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8634: }
8635: }
8636: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8637: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8638: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8639: }
8640: }
8641: }
8642: }
8643: }
8644: } elsif ($block =~ /^firstaccess____(.+)$/) {
8645: my $item = $1;
8646: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8647: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8648: my (@interval,$mapname);
1.1172.2.66 raeburn 8649: my $type = 'map';
8650: if ($item eq 'course') {
8651: $type = 'course';
8652: @interval=&EXT("resource.0.interval");
8653: } else {
8654: if ($item =~ /___\d+___/) {
8655: $type = 'resource';
8656: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8657: } else {
1.1172.2.142 raeburn 8658: $mapname = &deversion($item);
8659: if (ref($navmap)) {
8660: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8661: @interval = ($timelimit,'map');
1.1162 raeburn 8662: }
8663: }
1.1172.2.66 raeburn 8664: }
8665: if ($interval[0] =~ /^\d+$/) {
8666: my $first_access;
8667: if ($type eq 'resource') {
8668: $first_access=&get_first_access($interval[1],$item);
8669: } elsif ($type eq 'map') {
8670: $first_access=&get_first_access($interval[1],undef,$item);
8671: } else {
8672: $first_access=&get_first_access($interval[1]);
8673: }
8674: if ($first_access) {
8675: my $timesup = $first_access+$interval[0];
8676: if ($timesup > $now) {
8677: my $activeblock;
1.1172.2.142 raeburn 8678: if ($type eq 'resource') {
8679: if (ref($navmap)) {
8680: my $res = $navmap->getBySymb($item);
8681: if ($res->answerable()) {
8682: $activeblock = 1;
8683: }
8684: }
8685: } elsif ($type eq 'map') {
8686: my $mapsymb = &symbread($mapname,1);
8687: if (($mapsymb) && (ref($navmap))) {
8688: my $mapres = $navmap->getBySymb($mapsymb);
8689: if (ref($mapres)) {
8690: my $first = $mapres->map_start();
8691: my $finish = $mapres->map_finish();
8692: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8693: if (ref($it)) {
8694: my $res;
8695: while ($res = $it->next(undef,1)) {
8696: next unless (ref($res));
8697: my $symb = $res->symb();
8698: next if (($symb eq $mapsymb) || ($symb eq ''));
8699: @interval=&EXT("resource.0.interval",$symb);
8700: if ($interval[1] eq 'map') {
8701: if ($res->answerable()) {
8702: $activeblock = 1;
8703: last;
8704: }
8705: }
8706: }
8707: }
8708: }
1.1172.2.66 raeburn 8709: }
8710: }
8711: if ($activeblock) {
8712: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8713: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8714: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8715: }
8716: }
8717: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8718: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8719: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8720: }
1.1162 raeburn 8721: }
8722: }
8723: }
8724: }
8725: }
8726: }
8727: }
8728: }
8729: }
1.1172.2.66 raeburn 8730: return %blockers;
1.1162 raeburn 8731: }
8732:
1.1172.2.66 raeburn 8733: sub has_comm_blocking {
1.1172.2.128 raeburn 8734: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8735: my @blockers;
8736: return unless ($env{'request.course.id'});
8737: return unless ($priv eq 'bre');
8738: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8739: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8740: if ($env{'request.course.sec'}) {
8741: $courseurl .= '/'.$env{'request.course.sec'};
8742: }
8743: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8744: my %blockinfo;
8745: if (ref($blocks) eq 'HASH') {
8746: %blockinfo = &get_commblock_resources($blocks);
8747: } else {
8748: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8749: %blockinfo = %cachedblockers;
8750: }
8751: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8752: my (%possibles,@symbs);
8753: if (!$symb) {
1.1172.2.128 raeburn 8754: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8755: }
1.1172.2.66 raeburn 8756: if ($symb) {
8757: @symbs = ($symb);
8758: } elsif (keys(%possibles)) {
8759: @symbs = keys(%possibles);
8760: }
8761: my $noblock;
8762: foreach my $symb (@symbs) {
8763: last if ($noblock);
8764: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8765: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8766: if ($block =~ /^firstaccess____(.+)$/) {
8767: my $item = $1;
1.1172.2.126 raeburn 8768: unless ($blocked) {
8769: if (($item eq $map) || ($item eq $symb)) {
8770: $noblock = 1;
8771: last;
8772: }
1.1172.2.66 raeburn 8773: }
1.1162 raeburn 8774: }
1.1172.2.128 raeburn 8775: if (ref($blockinfo{$block}) eq 'HASH') {
8776: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8777: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8778: unless (grep(/^\Q$block\E$/,@blockers)) {
8779: push(@blockers,$block);
8780: }
8781: }
8782: }
1.1172.2.128 raeburn 8783: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8784: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8785: unless (grep(/^\Q$block\E$/,@blockers)) {
8786: push(@blockers,$block);
8787: }
1.1172.2.66 raeburn 8788: }
8789: }
1.1162 raeburn 8790: }
8791: }
8792: }
1.1172.2.126 raeburn 8793: unless ($noblock) {
8794: return @blockers;
8795: }
8796: return;
1.1172.2.66 raeburn 8797: }
1.1162 raeburn 8798: }
8799:
1.1172.2.66 raeburn 8800: # -------------------------------- Deversion and split uri into path an filename
8801:
1.1133 foxr 8802: #
1.1172.2.66 raeburn 8803: # Removes the version from a URI and
1.1133 foxr 8804: # splits it in to its filename and path to the filename.
8805: # Seems like File::Basename could have done this more clearly.
8806: # Parameters:
8807: # $uri - input URI
8808: # Returns:
8809: # Two element list consisting of
8810: # $pathname - the URI up to and excluding the trailing /
8811: # $filename - The part of the URI following the last /
8812: # NOTE:
8813: # Another realization of this is simply:
8814: # use File::Basename;
8815: # ...
8816: # $uri = shift;
8817: # $filename = basename($uri);
8818: # $path = dirname($uri);
8819: # return ($filename, $path);
8820: #
8821: # The implementation below is probably faster however.
8822: #
1.710 albertel 8823: sub split_uri_for_cond {
8824: my $uri=&deversion(&declutter(shift));
8825: my @uriparts=split(/\//,$uri);
8826: my $filename=pop(@uriparts);
8827: my $pathname=join('/',@uriparts);
8828: return ($pathname,$filename);
8829: }
1.232 www 8830: # --------------------------------------------------- Is a resource on the map?
8831:
8832: sub is_on_map {
1.710 albertel 8833: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8834: #Trying to find the conditional for the file
1.620 albertel 8835: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8836: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8837: if ($match) {
1.289 bowersj2 8838: return (1,$1);
8839: } else {
1.434 www 8840: return (0,0);
1.289 bowersj2 8841: }
1.12 www 8842: }
8843:
1.427 www 8844: # --------------------------------------------------------- Get symb from alias
8845:
8846: sub get_symb_from_alias {
8847: my $symb=shift;
8848: my ($map,$resid,$url)=&decode_symb($symb);
8849: # Already is a symb
8850: if ($url) { return $symb; }
8851: # Must be an alias
8852: my $aliassymb='';
8853: my %bighash;
1.620 albertel 8854: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8855: &GDBM_READER(),0640)) {
8856: my $rid=$bighash{'mapalias_'.$symb};
8857: if ($rid) {
8858: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8859: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8860: $resid,$bighash{'src_'.$rid});
1.427 www 8861: }
8862: untie %bighash;
8863: }
8864: return $aliassymb;
8865: }
8866:
1.12 www 8867: # ----------------------------------------------------------------- Define Role
8868:
8869: sub definerole {
8870: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8871: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8872: foreach my $role (split(':',$sysrole)) {
8873: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8874: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8875: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8876: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8877: return "refused:s:$crole&$cqual";
8878: }
8879: }
1.191 harris41 8880: }
1.800 albertel 8881: foreach my $role (split(':',$domrole)) {
8882: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8883: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8884: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8885: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8886: return "refused:d:$crole&$cqual";
8887: }
8888: }
1.191 harris41 8889: }
1.800 albertel 8890: foreach my $role (split(':',$courole)) {
8891: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8892: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8893: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8894: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8895: return "refused:c:$crole&$cqual";
8896: }
8897: }
1.191 harris41 8898: }
1.1172.2.84 raeburn 8899: my $uhome;
8900: if (($uname ne '') && ($udom ne '')) {
8901: $uhome = &homeserver($uname,$udom);
8902: return $uhome if ($uhome eq 'no_host');
8903: } else {
8904: $uname = $env{'user.name'};
8905: $udom = $env{'user.domain'};
8906: $uhome = $env{'user.home'};
8907: }
1.620 albertel 8908: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8909: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8910: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8911: return reply($command,$uhome);
1.12 www 8912: } else {
8913: return 'refused';
8914: }
1.105 harris41 8915: }
8916:
8917: # ---------------- Make a metadata query against the network of library servers
8918:
8919: sub metadata_query {
1.1172.2.33 raeburn 8920: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8921: my %rhash;
1.845 albertel 8922: my %libserv = &all_library();
1.244 matthew 8923: my @server_list = (defined($server_array) ? @$server_array
8924: : keys(%libserv) );
8925: for my $server (@server_list) {
1.1172.2.33 raeburn 8926: my $domains = '';
8927: if (ref($domains_hash) eq 'HASH') {
8928: $domains = $domains_hash->{$server};
8929: }
1.118 harris41 8930: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8931: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8932: $rhash{$server}=$reply;
8933: }
8934: else {
8935: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8936: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8937: $server);
8938: $rhash{$server}=$reply;
8939: }
1.112 harris41 8940: }
1.118 harris41 8941: return \%rhash;
1.240 www 8942: }
8943:
8944: # ----------------------------------------- Send log queries and wait for reply
8945:
8946: sub log_query {
8947: my ($uname,$udom,$query,%filters)=@_;
8948: my $uhome=&homeserver($uname,$udom);
8949: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8950: my $uhost=&hostname($uhome);
1.800 albertel 8951: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8952: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8953: $uhome);
1.479 albertel 8954: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8955: return get_query_reply($queryid);
8956: }
8957:
1.818 raeburn 8958: # -------------------------- Update MySQL table for portfolio file
8959:
8960: sub update_portfolio_table {
1.821 raeburn 8961: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8962: if ($group ne '') {
8963: $file_name =~s /^\Q$group\E//;
8964: }
1.818 raeburn 8965: my $homeserver = &homeserver($uname,$udom);
8966: my $queryid=
1.821 raeburn 8967: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8968: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8969: my $reply = &get_query_reply($queryid);
8970: return $reply;
8971: }
8972:
1.899 raeburn 8973: # -------------------------- Update MySQL allusers table
8974:
8975: sub update_allusers_table {
8976: my ($uname,$udom,$names) = @_;
8977: my $homeserver = &homeserver($uname,$udom);
8978: my $queryid=
8979: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8980: 'lastname='.&escape($names->{'lastname'}).'%%'.
8981: 'firstname='.&escape($names->{'firstname'}).'%%'.
8982: 'middlename='.&escape($names->{'middlename'}).'%%'.
8983: 'generation='.&escape($names->{'generation'}).'%%'.
8984: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8985: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8986: return;
1.899 raeburn 8987: }
8988:
1.508 raeburn 8989: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8990:
8991: sub fetch_enrollment_query {
1.511 raeburn 8992: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8993: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8994: my $maxtries = 1;
1.508 raeburn 8995: if ($context eq 'automated') {
8996: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8997: $sleep = 2;
8998: $loopmax = 100;
1.547 raeburn 8999: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9000: } else {
9001: $homeserver = &homeserver($cnum,$dom);
9002: }
1.838 albertel 9003: my $host=&hostname($homeserver);
1.506 raeburn 9004: my $cmd = '';
1.1000 raeburn 9005: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9006: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9007: }
9008: $cmd =~ s/%%$//;
9009: $cmd = &escape($cmd);
9010: my $query = 'fetchenrollment';
1.620 albertel 9011: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9012: unless ($queryid=~/^\Q$host\E\_/) {
9013: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9014: return 'error: '.$queryid;
9015: }
1.1172.2.93 raeburn 9016: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9017: my $tries = 1;
9018: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 9019: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9020: $tries ++;
9021: }
1.526 raeburn 9022: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9023: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9024: } else {
1.901 albertel 9025: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9026: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9027: foreach my $line (@responses) {
9028: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9029: $$replyref{$key} = $value;
9030: }
9031: } else {
1.1117 foxr 9032: my $pathname = LONCAPA::tempdir();
1.800 albertel 9033: foreach my $line (@responses) {
9034: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9035: $$replyref{$key} = $value;
9036: if ($value > 0) {
1.800 albertel 9037: foreach my $item (@{$$affiliatesref{$key}}) {
9038: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9039: my $destname = $pathname.'/'.$filename;
9040: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9041: if ($xml_classlist =~ /^error/) {
9042: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9043: } else {
1.1172.2.96 raeburn 9044: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9045: print FILE &unescape($xml_classlist);
9046: close(FILE);
1.526 raeburn 9047: } else {
9048: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9049: }
9050: }
9051: }
9052: }
9053: }
9054: }
9055: return 'ok';
9056: }
9057: return 'error';
9058: }
9059:
1.242 www 9060: sub get_query_reply {
1.1172.2.79 raeburn 9061: my ($queryid,$sleep,$loopmax) = @_;
9062: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9063: $sleep = 0.2;
9064: }
9065: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9066: $loopmax = 100;
9067: }
1.1117 foxr 9068: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9069: my $reply='';
1.1172.2.79 raeburn 9070: for (1..$loopmax) {
9071: sleep($sleep);
1.240 www 9072: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9073: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9074: $reply = join('',<$fh>);
9075: close($fh);
1.240 www 9076: } else { return 'error: reply_file_error'; }
1.242 www 9077: return &unescape($reply);
9078: }
1.240 www 9079: }
1.242 www 9080: return 'timeout:'.$queryid;
1.240 www 9081: }
9082:
9083: sub courselog_query {
1.241 www 9084: #
9085: # possible filters:
9086: # url: url or symb
9087: # username
9088: # domain
9089: # action: view, submit, grade
9090: # start: timestamp
9091: # end: timestamp
9092: #
1.240 www 9093: my (%filters)=@_;
1.620 albertel 9094: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9095: if ($filters{'url'}) {
9096: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9097: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9098: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9099: }
1.620 albertel 9100: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9101: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9102: return &log_query($cname,$cdom,'courselog',%filters);
9103: }
9104:
9105: sub userlog_query {
1.858 raeburn 9106: #
9107: # possible filters:
9108: # action: log check role
9109: # start: timestamp
9110: # end: timestamp
9111: #
1.240 www 9112: my ($uname,$udom,%filters)=@_;
9113: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9114: }
9115:
1.506 raeburn 9116: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9117:
9118: sub auto_run {
1.508 raeburn 9119: my ($cnum,$cdom) = @_;
1.876 raeburn 9120: my $response = 0;
9121: my $settings;
9122: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9123: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9124: $settings = $domconfig{'autoenroll'};
9125: if ($settings->{'run'} eq '1') {
9126: $response = 1;
9127: }
9128: } else {
1.934 raeburn 9129: my $homeserver;
9130: if (&is_course($cdom,$cnum)) {
9131: $homeserver = &homeserver($cnum,$cdom);
9132: } else {
9133: $homeserver = &domain($cdom,'primary');
9134: }
9135: if ($homeserver ne 'no_host') {
9136: $response = &reply('autorun:'.$cdom,$homeserver);
9137: }
1.876 raeburn 9138: }
1.506 raeburn 9139: return $response;
9140: }
1.776 albertel 9141:
1.506 raeburn 9142: sub auto_get_sections {
1.508 raeburn 9143: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9144: my $homeserver;
9145: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9146: $homeserver = &homeserver($cnum,$cdom);
9147: }
9148: if (!defined($homeserver)) {
9149: if ($cdom =~ /^$match_domain$/) {
9150: $homeserver = &domain($cdom,'primary');
9151: }
9152: }
9153: my @secs;
9154: if (defined($homeserver)) {
9155: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9156: unless ($response eq 'refused') {
9157: @secs = split(/:/,$response);
9158: }
1.506 raeburn 9159: }
9160: return @secs;
9161: }
1.776 albertel 9162:
1.506 raeburn 9163: sub auto_new_course {
1.1099 raeburn 9164: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9165: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9166: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9167: return $response;
9168: }
1.776 albertel 9169:
1.506 raeburn 9170: sub auto_validate_courseID {
1.508 raeburn 9171: my ($cnum,$cdom,$inst_course_id) = @_;
9172: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9173: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9174: return $response;
9175: }
1.776 albertel 9176:
1.1007 raeburn 9177: sub auto_validate_instcode {
1.1020 raeburn 9178: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9179: my ($homeserver,$response);
9180: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9181: $homeserver = &homeserver($cnum,$cdom);
9182: }
9183: if (!defined($homeserver)) {
9184: if ($cdom =~ /^$match_domain$/) {
9185: $homeserver = &domain($cdom,'primary');
9186: }
9187: }
1.1065 raeburn 9188: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9189: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9190: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9191: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9192: }
9193:
1.1172.2.141 raeburn 9194: sub auto_validate_inst_crosslist {
9195: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9196: my ($homeserver,$response);
9197: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9198: $homeserver = &homeserver($cnum,$cdom);
9199: }
9200: if (!defined($homeserver)) {
9201: if ($cdom =~ /^$match_domain$/) {
9202: $homeserver = &domain($cdom,'primary');
9203: }
9204: }
9205: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9206: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9207: &escape($instcode).':'.&escape($inst_xlist).':'.
9208: &escape($coowner),$homeserver);
9209: }
9210: return $response;
9211: }
9212:
1.506 raeburn 9213: sub auto_create_password {
1.873 raeburn 9214: my ($cnum,$cdom,$authparam,$udom) = @_;
9215: my ($homeserver,$response);
1.506 raeburn 9216: my $create_passwd = 0;
9217: my $authchk = '';
1.873 raeburn 9218: if ($udom =~ /^$match_domain$/) {
9219: $homeserver = &domain($udom,'primary');
9220: }
9221: if ($homeserver eq '') {
9222: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9223: $homeserver = &homeserver($cnum,$cdom);
9224: }
9225: }
9226: if ($homeserver eq '') {
9227: $authchk = 'nodomain';
1.506 raeburn 9228: } else {
1.873 raeburn 9229: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9230: if ($response eq 'refused') {
9231: $authchk = 'refused';
9232: } else {
1.901 albertel 9233: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9234: }
1.506 raeburn 9235: }
9236: return ($authparam,$create_passwd,$authchk);
9237: }
9238:
1.706 raeburn 9239: sub auto_photo_permission {
9240: my ($cnum,$cdom,$students) = @_;
9241: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9242: my ($outcome,$perm_reqd,$conditions) =
9243: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9244: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9245: return (undef,undef);
9246: }
1.706 raeburn 9247: return ($outcome,$perm_reqd,$conditions);
9248: }
9249:
9250: sub auto_checkphotos {
9251: my ($uname,$udom,$pid) = @_;
9252: my $homeserver = &homeserver($uname,$udom);
9253: my ($result,$resulttype);
9254: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9255: &escape($uname).':'.&escape($pid),
9256: $homeserver));
1.709 albertel 9257: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9258: return (undef,undef);
9259: }
1.706 raeburn 9260: if ($outcome) {
9261: ($result,$resulttype) = split(/:/,$outcome);
9262: }
9263: return ($result,$resulttype);
9264: }
9265:
9266: sub auto_photochoice {
9267: my ($cnum,$cdom) = @_;
9268: my $homeserver = &homeserver($cnum,$cdom);
9269: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9270: &escape($cdom),
9271: $homeserver)));
1.709 albertel 9272: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9273: return (undef,undef);
9274: }
1.706 raeburn 9275: return ($update,$comment);
9276: }
9277:
9278: sub auto_photoupdate {
9279: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9280: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9281: my $host=&hostname($homeserver);
1.706 raeburn 9282: my $cmd = '';
9283: my $maxtries = 1;
1.800 albertel 9284: foreach my $affiliate (keys(%{$affiliatesref})) {
9285: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9286: }
9287: $cmd =~ s/%%$//;
9288: $cmd = &escape($cmd);
9289: my $query = 'institutionalphotos';
9290: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9291: unless ($queryid=~/^\Q$host\E\_/) {
9292: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9293: return 'error: '.$queryid;
9294: }
9295: my $reply = &get_query_reply($queryid);
9296: my $tries = 1;
9297: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9298: $reply = &get_query_reply($queryid);
9299: $tries ++;
9300: }
9301: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9302: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9303: } else {
9304: my @responses = split(/:/,$reply);
9305: my $outcome = shift(@responses);
9306: foreach my $item (@responses) {
9307: my ($key,$value) = split(/=/,$item);
9308: $$photo{$key} = $value;
9309: }
9310: return $outcome;
9311: }
9312: return 'error';
9313: }
9314:
1.521 raeburn 9315: sub auto_instcode_format {
1.793 albertel 9316: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9317: $cat_order) = @_;
1.521 raeburn 9318: my $courses = '';
1.772 raeburn 9319: my @homeservers;
1.521 raeburn 9320: if ($caller eq 'global') {
1.841 albertel 9321: my %servers = &get_servers($codedom,'library');
9322: foreach my $tryserver (keys(%servers)) {
9323: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9324: push(@homeservers,$tryserver);
9325: }
1.584 raeburn 9326: }
1.1022 raeburn 9327: } elsif ($caller eq 'requests') {
9328: if ($codedom =~ /^$match_domain$/) {
9329: my $chome = &domain($codedom,'primary');
9330: unless ($chome eq 'no_host') {
9331: push(@homeservers,$chome);
9332: }
9333: }
1.521 raeburn 9334: } else {
1.772 raeburn 9335: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9336: }
1.793 albertel 9337: foreach my $code (keys(%{$instcodes})) {
9338: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9339: }
9340: chop($courses);
1.772 raeburn 9341: my $ok_response = 0;
9342: my $response;
9343: while (@homeservers > 0 && $ok_response == 0) {
9344: my $server = shift(@homeservers);
9345: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9346: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9347: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9348: split(/:/,$response);
1.772 raeburn 9349: %{$codes} = (%{$codes},&str2hash($codes_str));
9350: push(@{$codetitles},&str2array($codetitles_str));
9351: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9352: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9353: $ok_response = 1;
9354: }
9355: }
9356: if ($ok_response) {
1.521 raeburn 9357: return 'ok';
1.772 raeburn 9358: } else {
9359: return $response;
1.521 raeburn 9360: }
9361: }
9362:
1.792 raeburn 9363: sub auto_instcode_defaults {
9364: my ($domain,$returnhash,$code_order) = @_;
9365: my @homeservers;
1.841 albertel 9366:
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: }
1.792 raeburn 9372: }
1.841 albertel 9373:
1.792 raeburn 9374: my $response;
1.841 albertel 9375: foreach my $server (@homeservers) {
1.792 raeburn 9376: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9377: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9378:
9379: foreach my $pair (split(/\&/,$response)) {
9380: my ($name,$value)=split(/\=/,$pair);
9381: if ($name eq 'code_order') {
9382: @{$code_order} = split(/\&/,&unescape($value));
9383: } else {
9384: $returnhash->{&unescape($name)}=&unescape($value);
9385: }
9386: }
9387: return 'ok';
1.792 raeburn 9388: }
1.841 albertel 9389:
9390: return $response;
1.1003 raeburn 9391: }
9392:
9393: sub auto_possible_instcodes {
1.1007 raeburn 9394: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9395: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9396: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9397: return;
9398: }
1.1003 raeburn 9399: my (@homeservers,$uhome);
9400: if (defined(&domain($domain,'primary'))) {
9401: $uhome=&domain($domain,'primary');
9402: push(@homeservers,&domain($domain,'primary'));
9403: } else {
9404: my %servers = &get_servers($domain,'library');
9405: foreach my $tryserver (keys(%servers)) {
9406: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9407: push(@homeservers,$tryserver);
9408: }
9409: }
9410: }
9411: my $response;
9412: foreach my $server (@homeservers) {
9413: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9414: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9415: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9416: split(':',$response);
9417: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9418: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9419: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9420: my ($name,$value)=split('=',$item);
9421: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9422: }
9423: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9424: my ($name,$value)=split('=',$item);
9425: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9426: }
9427: return 'ok';
9428: }
9429: return $response;
9430: }
1.792 raeburn 9431:
1.1010 raeburn 9432: sub auto_courserequest_checks {
9433: my ($dom) = @_;
1.1020 raeburn 9434: my ($homeserver,%validations);
9435: if ($dom =~ /^$match_domain$/) {
9436: $homeserver = &domain($dom,'primary');
9437: }
9438: unless ($homeserver eq 'no_host') {
9439: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9440: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9441: my @items = split(/&/,$response);
9442: foreach my $item (@items) {
9443: my ($key,$value) = split('=',$item);
9444: $validations{&unescape($key)} = &thaw_unescape($value);
9445: }
9446: }
9447: }
1.1010 raeburn 9448: return %validations;
9449: }
9450:
1.1020 raeburn 9451: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9452: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9453: my ($homeserver,$response);
9454: if ($dom =~ /^$match_domain$/) {
9455: $homeserver = &domain($dom,'primary');
9456: }
1.1172.2.43 raeburn 9457: unless ($homeserver eq 'no_host') {
9458: my $customdata;
9459: if (ref($custominfo) eq 'HASH') {
9460: $customdata = &freeze_escape($custominfo);
9461: }
1.1020 raeburn 9462: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9463: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9464: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9465: $customdata,$homeserver));
1.1020 raeburn 9466: }
9467: return $response;
9468: }
9469:
1.777 albertel 9470: sub auto_validate_class_sec {
1.918 raeburn 9471: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9472: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9473: my $ownerlist;
9474: if (ref($owners) eq 'ARRAY') {
9475: $ownerlist = join(',',@{$owners});
9476: } else {
9477: $ownerlist = $owners;
9478: }
1.773 raeburn 9479: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9480: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9481: return $response;
9482: }
9483:
1.1172.2.141 raeburn 9484: sub auto_instsec_reformat {
9485: my ($cdom,$action,$instsecref) = @_;
9486: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9487: my @homeservers;
9488: if (defined(&domain($cdom,'primary'))) {
9489: push(@homeservers,&domain($cdom,'primary'));
9490: } else {
9491: my %servers = &get_servers($cdom,'library');
9492: foreach my $tryserver (keys(%servers)) {
9493: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9494: push(@homeservers,$tryserver);
9495: }
9496: }
9497: }
9498: my $response;
9499: my %reformatted = %{$instsecref};
9500: foreach my $server (@homeservers) {
9501: if (ref($instsecref) eq 'HASH') {
9502: my $info = &freeze_escape($instsecref);
9503: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9504: $action.':'.$info,$server);
9505: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9506: my @items = split(/&/,$response);
9507: foreach my $item (@items) {
9508: my ($key,$value) = split(/=/,$item);
9509: $reformatted{&unescape($key)} = &thaw_unescape($value);
9510: }
9511: }
9512: }
9513: return %reformatted;
9514: }
9515:
1.1172.2.94 raeburn 9516: sub auto_validate_instclasses {
9517: my ($cdom,$cnum,$owners,$classesref) = @_;
9518: my ($homeserver,%validations);
9519: $homeserver = &homeserver($cnum,$cdom);
9520: unless ($homeserver eq 'no_host') {
9521: my $ownerlist;
9522: if (ref($owners) eq 'ARRAY') {
9523: $ownerlist = join(',',@{$owners});
9524: } else {
9525: $ownerlist = $owners;
9526: }
9527: if (ref($classesref) eq 'HASH') {
9528: my $classes = &freeze_escape($classesref);
9529: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9530: ':'.$cdom.':'.$classes,$homeserver);
9531: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9532: my @items = split(/&/,$response);
9533: foreach my $item (@items) {
9534: my ($key,$value) = split('=',$item);
9535: $validations{&unescape($key)} = &thaw_unescape($value);
9536: }
9537: }
9538: }
9539: }
9540: return %validations;
9541: }
9542:
1.1172.2.38 raeburn 9543: sub auto_crsreq_update {
9544: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9545: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9546: my ($homeserver,%crsreqresponse);
9547: if ($cdom =~ /^$match_domain$/) {
9548: $homeserver = &domain($cdom,'primary');
9549: }
9550: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9551: my $info;
9552: if (ref($inbound) eq 'HASH') {
9553: $info = &freeze_escape($inbound);
9554: }
9555: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9556: ':'.&escape($action).':'.&escape($ownername).':'.
9557: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9558: &escape($title).':'.&escape($code).':'.
9559: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9560: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9561: my @items = split(/&/,$response);
9562: foreach my $item (@items) {
9563: my ($key,$value) = split('=',$item);
9564: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9565: }
9566: }
9567: }
9568: return \%crsreqresponse;
9569: }
9570:
1.1172.2.78 raeburn 9571: sub auto_export_grades {
9572: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9573: my ($homeserver,%exportresponse);
9574: if ($cdom =~ /^$match_domain$/) {
9575: $homeserver = &domain($cdom,'primary');
9576: }
9577: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9578: my $info;
9579: if (ref($inforef) eq 'HASH') {
9580: $info = &freeze_escape($inforef);
9581: }
9582: if (ref($gradesref) eq 'HASH') {
9583: my $grades = &freeze_escape($gradesref);
9584: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9585: $info.':'.$grades,$homeserver);
9586: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9587: my @items = split(/&/,$response);
9588: foreach my $item (@items) {
9589: my ($key,$value) = split('=',$item);
9590: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9591: }
9592: }
9593: }
9594: }
9595: return \%exportresponse;
9596: }
9597:
1.1172.2.68 raeburn 9598: sub check_instcode_cloning {
9599: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9600: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9601: return;
9602: }
9603: my $canclone;
9604: if (@{$code_order} > 0) {
9605: my $instcoderegexp ='^';
9606: my @clonecodes = split(/\&/,$cloner);
9607: foreach my $item (@{$code_order}) {
9608: if (grep(/^\Q$item\E=/,@clonecodes)) {
9609: foreach my $pair (@clonecodes) {
9610: my ($key,$val) = split(/\=/,$pair,2);
9611: $val = &unescape($val);
9612: if ($key eq $item) {
9613: $instcoderegexp .= '('.$val.')';
9614: last;
9615: }
9616: }
9617: } else {
9618: $instcoderegexp .= $codedefaults->{$item};
9619: }
9620: }
9621: $instcoderegexp .= '$';
9622: my (@from,@to);
9623: eval {
9624: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9625: (@to) = ($clonetocode =~ /$instcoderegexp/);
9626: };
9627: if ((@from > 0) && (@to > 0)) {
9628: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9629: if (!@diffs) {
9630: $canclone = 1;
9631: }
9632: }
9633: }
9634: return $canclone;
9635: }
9636:
9637: sub default_instcode_cloning {
9638: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9639: my (%codedefaults,@code_order,$canclone);
9640: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9641: %codedefaults = %{$codedefaultsref};
9642: @code_order = @{$codeorderref};
9643: } elsif ($clonedom) {
9644: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9645: }
9646: if (($domdefclone) && (@code_order)) {
9647: my @clonecodes = split(/\+/,$domdefclone);
9648: my $instcoderegexp ='^';
9649: foreach my $item (@code_order) {
9650: if (grep(/^\Q$item\E$/,@clonecodes)) {
9651: $instcoderegexp .= '('.$codedefaults{$item}.')';
9652: } else {
9653: $instcoderegexp .= $codedefaults{$item};
9654: }
9655: }
9656: $instcoderegexp .= '$';
9657: my (@from,@to);
9658: eval {
9659: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9660: (@to) = ($clonetocode =~ /$instcoderegexp/);
9661: };
9662: if ((@from > 0) && (@to > 0)) {
9663: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9664: if (!@diffs) {
9665: $canclone = 1;
9666: }
9667: }
9668: }
9669: return $canclone;
9670: }
9671:
1.679 raeburn 9672: # ------------------------------------------------------- Course Group routines
9673:
9674: sub get_coursegroups {
1.809 raeburn 9675: my ($cdom,$cnum,$group,$namespace) = @_;
9676: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9677: }
9678:
1.679 raeburn 9679: sub modify_coursegroup {
9680: my ($cdom,$cnum,$groupsettings) = @_;
9681: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9682: }
9683:
1.809 raeburn 9684: sub toggle_coursegroup_status {
9685: my ($cdom,$cnum,$group,$action) = @_;
9686: my ($from_namespace,$to_namespace);
9687: if ($action eq 'delete') {
9688: $from_namespace = 'coursegroups';
9689: $to_namespace = 'deleted_groups';
9690: } else {
9691: $from_namespace = 'deleted_groups';
9692: $to_namespace = 'coursegroups';
9693: }
9694: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9695: if (my $tmp = &error(%curr_group)) {
9696: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9697: return ('read error',$tmp);
9698: } else {
9699: my %savedsettings = %curr_group;
1.809 raeburn 9700: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9701: my $deloutcome;
9702: if ($result eq 'ok') {
1.809 raeburn 9703: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9704: } else {
9705: return ('write error',$result);
9706: }
9707: if ($deloutcome eq 'ok') {
9708: return 'ok';
9709: } else {
9710: return ('delete error',$deloutcome);
9711: }
9712: }
9713: }
9714:
1.679 raeburn 9715: sub modify_group_roles {
1.957 raeburn 9716: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9717: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9718: my $role = 'gr/'.&escape($userprivs);
9719: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9720: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9721: if ($result eq 'ok') {
9722: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9723: }
1.679 raeburn 9724: return $result;
9725: }
9726:
9727: sub modify_coursegroup_membership {
9728: my ($cdom,$cnum,$membership) = @_;
9729: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9730: return $result;
9731: }
9732:
1.682 raeburn 9733: sub get_active_groups {
9734: my ($udom,$uname,$cdom,$cnum) = @_;
9735: my $now = time;
9736: my %groups = ();
9737: foreach my $key (keys(%env)) {
1.811 albertel 9738: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9739: my ($start,$end) = split(/\./,$env{$key});
9740: if (($end!=0) && ($end<$now)) { next; }
9741: if (($start!=0) && ($start>$now)) { next; }
9742: if ($1 eq $cdom && $2 eq $cnum) {
9743: $groups{$3} = $env{$key} ;
9744: }
9745: }
9746: }
9747: return %groups;
9748: }
9749:
1.683 raeburn 9750: sub get_group_membership {
9751: my ($cdom,$cnum,$group) = @_;
9752: return(&dump('groupmembership',$cdom,$cnum,$group));
9753: }
9754:
9755: sub get_users_groups {
9756: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9757: my @usersgroups;
1.683 raeburn 9758: my $cachetime=1800;
9759:
9760: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9761: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9762: if (defined($cached)) {
1.734 albertel 9763: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9764: } else {
9765: $grouplist = '';
1.816 raeburn 9766: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9767: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9768: my $access_end = $env{'course.'.$courseid.
9769: '.default_enrollment_end_date'};
9770: my $now = time;
9771: foreach my $key (keys(%roleshash)) {
9772: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9773: my $group = $1;
9774: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9775: my $start = $2;
9776: my $end = $1;
9777: if ($start == -1) { next; } # deleted from group
9778: if (($start!=0) && ($start>$now)) { next; }
9779: if (($end!=0) && ($end<$now)) {
9780: if ($access_end && $access_end < $now) {
9781: if ($access_end - $end < 86400) {
9782: push(@usersgroups,$group);
1.733 raeburn 9783: }
9784: }
1.817 raeburn 9785: next;
1.733 raeburn 9786: }
1.817 raeburn 9787: push(@usersgroups,$group);
1.683 raeburn 9788: }
9789: }
9790: }
1.817 raeburn 9791: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9792: $grouplist = join(':',@usersgroups);
9793: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9794: }
1.733 raeburn 9795: return @usersgroups;
1.683 raeburn 9796: }
9797:
9798: sub devalidate_getgroups_cache {
9799: my ($udom,$uname,$cdom,$cnum)=@_;
9800: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9801:
1.683 raeburn 9802: my $hashid="$udom:$uname:$courseid";
9803: &devalidate_cache_new('getgroups',$hashid);
9804: }
9805:
1.12 www 9806: # ------------------------------------------------------------------ Plain Text
9807:
9808: sub plaintext {
1.988 raeburn 9809: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9810: if ($short =~ m{^cr/}) {
1.758 albertel 9811: return (split('/',$short))[-1];
9812: }
1.742 raeburn 9813: if (!defined($cid)) {
9814: $cid = $env{'request.course.id'};
9815: }
9816: my %rolenames = (
1.1008 raeburn 9817: Course => 'std',
9818: Community => 'alt1',
1.742 raeburn 9819: );
1.1037 raeburn 9820: if ($cid ne '') {
9821: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9822: unless ($forcedefault) {
9823: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9824: &Apache::lonlocal::mt_escape(\$roletext);
9825: return &Apache::lonlocal::mt($roletext);
9826: }
9827: }
9828: }
9829: if ((defined($type)) && (defined($rolenames{$type})) &&
9830: (defined($rolenames{$type})) &&
9831: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9832: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9833: } elsif ($cid ne '') {
9834: my $crstype = $env{'course.'.$cid.'.type'};
9835: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9836: (defined($prp{$short}{$rolenames{$crstype}}))) {
9837: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9838: }
1.742 raeburn 9839: }
1.1037 raeburn 9840: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9841: }
9842:
9843: # ----------------------------------------------------------------- Assign Role
9844:
9845: sub assignrole {
1.957 raeburn 9846: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9847: $context)=@_;
1.21 www 9848: my $mrole;
9849: if ($role =~ /^cr\//) {
1.393 www 9850: my $cwosec=$url;
1.811 albertel 9851: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9852: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9853: my $refused = 1;
9854: if ($context eq 'requestcourses') {
9855: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9856: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9857: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9858: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9859: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9860: if ($crsenv{'internal.courseowner'} eq
9861: $env{'user.name'}.':'.$env{'user.domain'}) {
9862: $refused = '';
9863: }
9864: }
9865: }
9866: }
9867: }
9868: if ($refused) {
9869: &logthis('Refused custom assignrole: '.
9870: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9871: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9872: return 'refused';
9873: }
1.104 www 9874: }
1.21 www 9875: $mrole='cr';
1.678 raeburn 9876: } elsif ($role =~ /^gr\//) {
9877: my $cwogrp=$url;
1.811 albertel 9878: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9879: unless (&allowed('mdg',$cwogrp)) {
9880: &logthis('Refused group assignrole: '.
9881: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9882: $env{'user.name'}.' at '.$env{'user.domain'});
9883: return 'refused';
9884: }
9885: $mrole='gr';
1.21 www 9886: } else {
1.82 www 9887: my $cwosec=$url;
1.811 albertel 9888: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9889: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9890: my $refused;
9891: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9892: if (!(&allowed('c'.$role,$url))) {
9893: $refused = 1;
9894: }
9895: } else {
9896: $refused = 1;
9897: }
1.947 raeburn 9898: if ($refused) {
1.1045 raeburn 9899: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9900: if (!$selfenroll && $context eq 'course') {
9901: my %crsenv;
9902: if ($role eq 'cc' || $role eq 'co') {
9903: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9904: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9905: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9906: if ($crsenv{'internal.courseowner'} eq
9907: $env{'user.name'}.':'.$env{'user.domain'}) {
9908: $refused = '';
9909: }
9910: }
9911: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9912: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9913: if ($crsenv{'internal.courseowner'} eq
9914: $env{'user.name'}.':'.$env{'user.domain'}) {
9915: $refused = '';
9916: }
9917: }
9918: }
9919: }
9920: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9921: $refused = '';
1.1017 raeburn 9922: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9923: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9924: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9925: my $wrongcc;
9926: if ($cnum =~ /^$match_community$/) {
9927: $wrongcc = 1 if ($role eq 'cc');
9928: } else {
9929: $wrongcc = 1 if ($role eq 'co');
9930: }
9931: unless ($wrongcc) {
9932: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9933: if ($crsenv{'internal.courseowner'} eq
9934: $env{'user.name'}.':'.$env{'user.domain'}) {
9935: $refused = '';
9936: }
1.1017 raeburn 9937: }
9938: }
1.1172.2.9 raeburn 9939: } elsif ($context eq 'requestauthor') {
9940: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9941: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9942: if ($env{'environment.requestauthor'} eq 'automatic') {
9943: $refused = '';
9944: } else {
9945: my %domdefaults = &get_domain_defaults($udom);
9946: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9947: my $checkbystatus;
9948: if ($env{'user.adv'}) {
9949: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9950: if ($disposition eq 'automatic') {
9951: $refused = '';
9952: } elsif ($disposition eq '') {
9953: $checkbystatus = 1;
9954: }
9955: } else {
9956: $checkbystatus = 1;
9957: }
9958: if ($checkbystatus) {
9959: if ($env{'environment.inststatus'}) {
9960: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9961: foreach my $type (@inststatuses) {
9962: if (($type ne '') &&
9963: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9964: $refused = '';
9965: }
9966: }
9967: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9968: $refused = '';
9969: }
9970: }
9971: }
9972: }
9973: }
1.1017 raeburn 9974: }
9975: if ($refused) {
1.947 raeburn 9976: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9977: ' '.$role.' '.$end.' '.$start.' by '.
9978: $env{'user.name'}.' at '.$env{'user.domain'});
9979: return 'refused';
9980: }
1.932 raeburn 9981: }
1.1131 raeburn 9982: } elsif ($role eq 'au') {
9983: if ($url ne '/'.$udom.'/') {
9984: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9985: ' to assign author role for '.$uname.':'.$udom.
9986: ' in domain: '.$url.' refused (wrong domain).');
9987: return 'refused';
9988: }
1.104 www 9989: }
1.21 www 9990: $mrole=$role;
9991: }
1.620 albertel 9992: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9993: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9994: if ($end) { $command.='_'.$end; }
1.21 www 9995: if ($start) {
9996: if ($end) {
1.81 www 9997: $command.='_'.$start;
1.21 www 9998: } else {
1.81 www 9999: $command.='_0_'.$start;
1.21 www 10000: }
10001: }
1.739 raeburn 10002: my $origstart = $start;
10003: my $origend = $end;
1.957 raeburn 10004: my $delflag;
1.357 www 10005: # actually delete
10006: if ($deleteflag) {
1.373 www 10007: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10008: # modify command to delete the role
1.620 albertel 10009: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10010: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10011: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10012: # set start and finish to negative values for userrolelog
10013: $start=-1;
10014: $end=-1;
1.957 raeburn 10015: $delflag = 1;
1.357 www 10016: }
10017: }
10018: # send command
1.349 www 10019: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10020: # log new user role if status is ok
1.349 www 10021: if ($answer eq 'ok') {
1.663 raeburn 10022: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 10023: if (($role eq 'cc') || ($role eq 'in') ||
10024: ($role eq 'ep') || ($role eq 'ad') ||
10025: ($role eq 'ta') || ($role eq 'st') ||
10026: ($role=~/^cr/) || ($role eq 'gr') ||
10027: ($role eq 'co')) {
1.1172.2.13 raeburn 10028: # for course roles, perform group memberships changes triggered by role change.
10029: unless ($role =~ /^gr/) {
10030: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10031: $origstart,$selfenroll,$context);
10032: }
1.1172.2.9 raeburn 10033: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10034: $selfenroll,$context);
10035: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10036: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10037: ($role eq 'da')) {
1.1172.2.9 raeburn 10038: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10039: $context);
10040: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10041: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10042: $context);
10043: }
1.1053 raeburn 10044: if ($role eq 'cc') {
10045: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10046: }
1.349 www 10047: }
10048: return $answer;
1.169 harris41 10049: }
10050:
1.1053 raeburn 10051: sub autoupdate_coowners {
10052: my ($url,$end,$start,$uname,$udom) = @_;
10053: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10054: if (($cdom ne '') && ($cnum ne '')) {
10055: my $now = time;
10056: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10057: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10058: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10059: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10060: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10061: if ($instcode ne '') {
1.1056 raeburn 10062: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10063: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10064: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10065: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10066: unless ($result eq 'valid') {
10067: if ($xlists ne '') {
10068: foreach my $xlist (split(',',$xlists)) {
10069: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10070: $result =
10071: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10072: $inst_crosslist,$uname.':'.$udom);
10073: last if ($result eq 'valid');
10074: }
10075: }
10076: }
1.1056 raeburn 10077: if ($result eq 'valid') {
10078: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10079: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10080: push(@newcoowners,$coowner);
10081: }
10082: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10083: push(@newcoowners,$uname.':'.$udom);
10084: }
10085: @newcoowners = sort(@newcoowners);
10086: } else {
10087: push(@newcoowners,$uname.':'.$udom);
10088: }
1.1172.2.141 raeburn 10089: } elsif ($coursehash{'internal.co-owners'}) {
10090: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10091: unless ($coowner eq $uname.':'.$udom) {
10092: push(@newcoowners,$coowner);
1.1053 raeburn 10093: }
10094: }
1.1172.2.141 raeburn 10095: unless (@newcoowners > 0) {
10096: $delcoowners = 1;
10097: $coowners = '';
10098: }
1.1053 raeburn 10099: }
10100: if (@newcoowners || $delcoowners) {
10101: &store_coowners($cdom,$cnum,$coursehash{'home'},
10102: $delcoowners,@newcoowners);
10103: }
10104: }
10105: }
10106: }
10107: }
10108: }
10109: }
10110:
10111: sub store_coowners {
10112: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10113: my $cid = $cdom.'_'.$cnum;
10114: my ($coowners,$delresult,$putresult);
10115: if (@newcoowners) {
10116: $coowners = join(',',@newcoowners);
10117: my %coownershash = (
10118: 'internal.co-owners' => $coowners,
10119: );
10120: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10121: if ($putresult eq 'ok') {
10122: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10123: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10124: }
10125: }
10126: }
10127: if ($delcoowners) {
10128: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10129: if ($delresult eq 'ok') {
10130: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10131: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10132: }
10133: }
10134: }
10135: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10136: my %crsinfo =
10137: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10138: if (ref($crsinfo{$cid}) eq 'HASH') {
10139: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10140: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10141: }
10142: }
10143: }
10144:
1.169 harris41 10145: # -------------------------------------------------- Modify user authentication
1.197 www 10146: # Overrides without validation
10147:
1.169 harris41 10148: sub modifyuserauth {
10149: my ($udom,$uname,$umode,$upass)=@_;
10150: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10151: my $allowed;
10152: if (&allowed('mau',$udom)) {
10153: $allowed = 1;
10154: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10155: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10156: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10157: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10158: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10159: if (($cdom ne '') && ($cnum ne '')) {
10160: my $is_owner = &is_course_owner($cdom,$cnum);
10161: if ($is_owner) {
10162: $allowed = 1;
10163: }
10164: }
10165: }
10166: unless ($allowed) { return 'refused'; }
1.197 www 10167: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10168: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10169: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10170: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10171: &escape($upass),$uhome);
1.1172.2.134 raeburn 10172: my $ip = &get_requestor_ip();
1.620 albertel 10173: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10174: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10175: '(Remote '.$ip.'): '.$reply);
1.197 www 10176: &log($udom,,$uname,$uhome,
1.620 albertel 10177: 'Authentication changed by '.$env{'user.domain'}.', '.
10178: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10179: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10180: unless ($reply eq 'ok') {
1.197 www 10181: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10182: return 'error: '.$reply;
10183: }
1.170 harris41 10184: return 'ok';
1.80 www 10185: }
10186:
1.81 www 10187: # --------------------------------------------------------------- Modify a user
1.80 www 10188:
1.81 www 10189: sub modifyuser {
1.206 matthew 10190: my ($udom, $uname, $uid,
10191: $umode, $upass, $first,
10192: $middle, $last, $gene,
1.1058 raeburn 10193: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10194: $udom= &LONCAPA::clean_domain($udom);
10195: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10196: my $showcandelete = 'none';
10197: if (ref($candelete) eq 'ARRAY') {
10198: if (@{$candelete} > 0) {
10199: $showcandelete = join(', ',@{$candelete});
10200: }
10201: }
1.81 www 10202: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10203: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10204: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10205: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10206: ' desiredhome not specified').
1.620 albertel 10207: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10208: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10209: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10210: my $newuser;
10211: if ($uhome eq 'no_host') {
10212: $newuser = 1;
10213: }
1.80 www 10214: # ----------------------------------------------------------------- Create User
1.406 albertel 10215: if (($uhome eq 'no_host') &&
10216: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10217: my $unhome='';
1.844 albertel 10218: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10219: $unhome = $desiredhome;
1.620 albertel 10220: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10221: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10222: } else { # load balancing routine for determining $unhome
1.81 www 10223: my $loadm=10000000;
1.841 albertel 10224: my %servers = &get_servers($udom,'library');
10225: foreach my $tryserver (keys(%servers)) {
10226: my $answer=reply('load',$tryserver);
10227: if (($answer=~/\d+/) && ($answer<$loadm)) {
10228: $loadm=$answer;
10229: $unhome=$tryserver;
10230: }
1.80 www 10231: }
10232: }
10233: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10234: return 'error: unable to find a home server for '.$uname.
10235: ' in domain '.$udom;
1.80 www 10236: }
10237: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10238: &escape($upass),$unhome);
10239: unless ($reply eq 'ok') {
10240: return 'error: '.$reply;
10241: }
1.230 stredwic 10242: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10243: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10244: return 'error: unable verify users home machine.';
1.80 www 10245: }
1.209 matthew 10246: } # End of creation of new user
1.80 www 10247: # ---------------------------------------------------------------------- Add ID
10248: if ($uid) {
10249: $uid=~tr/A-Z/a-z/;
10250: my %uidhash=&idrget($udom,$uname);
1.196 www 10251: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10252: && (!$forceid)) {
1.80 www 10253: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10254: return 'error: user id "'.$uid.'" does not match '.
10255: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10256: }
10257: } else {
10258: &idput($udom,($uname => $uid));
10259: }
10260: }
10261: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10262: my @tmp=&get('environment',
1.899 raeburn 10263: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10264: 'permanentemail','inststatus'],
1.134 albertel 10265: $udom,$uname);
1.1075 raeburn 10266: my (%names,%oldnames);
1.313 matthew 10267: if ($tmp[0] =~ m/^error:.*/) {
10268: %names=();
10269: } else {
10270: %names = @tmp;
1.1075 raeburn 10271: %oldnames = %names;
1.313 matthew 10272: }
1.388 www 10273: #
1.1058 raeburn 10274: # If name, email and/or uid are blank (e.g., because an uploaded file
10275: # of users did not contain them), do not overwrite existing values
10276: # unless field is in $candelete array ref.
10277: #
10278:
10279: my @fields = ('firstname','middlename','lastname','generation',
10280: 'permanentemail','id');
10281: my %newvalues;
10282: if (ref($candelete) eq 'ARRAY') {
10283: foreach my $field (@fields) {
10284: if (grep(/^\Q$field\E$/,@{$candelete})) {
10285: if ($field eq 'firstname') {
10286: $names{$field} = $first;
10287: } elsif ($field eq 'middlename') {
10288: $names{$field} = $middle;
10289: } elsif ($field eq 'lastname') {
10290: $names{$field} = $last;
10291: } elsif ($field eq 'generation') {
10292: $names{$field} = $gene;
10293: } elsif ($field eq 'permanentemail') {
10294: $names{$field} = $email;
10295: } elsif ($field eq 'id') {
10296: $names{$field} = $uid;
10297: }
10298: }
10299: }
10300: }
1.388 www 10301: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10302: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10303: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10304: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10305: if ($email) {
10306: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10307: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10308: }
1.899 raeburn 10309: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10310: if (defined($inststatus)) {
10311: $names{'inststatus'} = '';
10312: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10313: if (ref($usertypes) eq 'HASH') {
10314: my @okstatuses;
10315: foreach my $item (split(/:/,$inststatus)) {
10316: if (defined($usertypes->{$item})) {
10317: push(@okstatuses,$item);
10318: }
10319: }
10320: if (@okstatuses) {
10321: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10322: }
10323: }
10324: }
1.1075 raeburn 10325: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10326: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10327: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10328: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10329: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10330: } else {
10331: $logmsg .= ' during self creation';
10332: }
1.1075 raeburn 10333: my $changed;
10334: if ($newuser) {
10335: $changed = 1;
10336: } else {
10337: foreach my $field (@fields) {
10338: if ($names{$field} ne $oldnames{$field}) {
10339: $changed = 1;
10340: last;
10341: }
10342: }
10343: }
10344: unless ($changed) {
10345: $logmsg = 'No changes in user information needed for: '.$logmsg;
10346: &logthis($logmsg);
10347: return 'ok';
10348: }
10349: my $reply = &put('environment', \%names, $udom,$uname);
10350: if ($reply ne 'ok') {
10351: return 'error: '.$reply;
10352: }
1.1087 raeburn 10353: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10354: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10355: }
1.1075 raeburn 10356: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10357: &devalidate_cache_new('namescache',$uname.':'.$udom);
10358: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10359: &logthis($logmsg);
1.134 albertel 10360: return 'ok';
1.80 www 10361: }
10362:
1.81 www 10363: # -------------------------------------------------------------- Modify student
1.80 www 10364:
1.81 www 10365: sub modifystudent {
10366: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10367: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10368: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10369: if (!$cid) {
1.620 albertel 10370: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10371: return 'not_in_class';
10372: }
1.80 www 10373: }
10374: # --------------------------------------------------------------- Make the user
1.81 www 10375: my $reply=&modifyuser
1.209 matthew 10376: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10377: $desiredhome,$email,$inststatus);
1.80 www 10378: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10379: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10380: # student's environment
1.297 matthew 10381: $uid = undef if (!$forceid);
1.455 albertel 10382: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10383: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10384: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10385: return $reply;
10386: }
10387:
10388: sub modify_student_enrollment {
1.1172.2.23 raeburn 10389: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10390: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10391: my ($cdom,$cnum,$chome);
10392: if (!$cid) {
1.620 albertel 10393: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10394: return 'not_in_class';
10395: }
1.620 albertel 10396: $cdom=$env{'course.'.$cid.'.domain'};
10397: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10398: } else {
10399: ($cdom,$cnum)=split(/_/,$cid);
10400: }
1.620 albertel 10401: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10402: if (!$chome) {
1.457 raeburn 10403: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10404: }
1.455 albertel 10405: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10406: # Make sure the user exists
1.81 www 10407: my $uhome=&homeserver($uname,$udom);
10408: if (($uhome eq '') || ($uhome eq 'no_host')) {
10409: return 'error: no such user';
10410: }
1.297 matthew 10411: # Get student data if we were not given enough information
10412: if (!defined($first) || $first eq '' ||
10413: !defined($last) || $last eq '' ||
10414: !defined($uid) || $uid eq '' ||
10415: !defined($middle) || $middle eq '' ||
10416: !defined($gene) || $gene eq '') {
1.294 matthew 10417: # They did not supply us with enough data to enroll the student, so
10418: # we need to pick up more information.
1.297 matthew 10419: my %tmp = &get('environment',
1.294 matthew 10420: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10421: ,$udom,$uname);
10422:
1.800 albertel 10423: #foreach my $key (keys(%tmp)) {
10424: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10425: #}
1.294 matthew 10426: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10427: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10428: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10429: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10430: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10431: }
1.556 albertel 10432: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10433: my $user = "$uname:$udom";
10434: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10435: my $reply=cput('classlist',
1.1148 raeburn 10436: {$user =>
1.1172.2.76 raeburn 10437: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10438: $cdom,$cnum);
1.1148 raeburn 10439: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10440: &devalidate_getsection_cache($udom,$uname,$cid);
10441: } else {
1.81 www 10442: return 'error: '.$reply;
10443: }
1.297 matthew 10444: # Add student role to user
1.83 www 10445: my $uurl='/'.$cid;
1.81 www 10446: $uurl=~s/\_/\//g;
10447: if ($usec) {
10448: $uurl.='/'.$usec;
10449: }
1.1148 raeburn 10450: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10451: $selfenroll,$context);
10452: if ($result ne 'ok') {
10453: if ($old_entry{$user} ne '') {
10454: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10455: } else {
10456: $reply = &del('classlist',[$user],$cdom,$cnum);
10457: }
10458: }
10459: return $result;
1.21 www 10460: }
10461:
1.556 albertel 10462: sub format_name {
10463: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10464: my $name;
10465: if ($first ne 'lastname') {
10466: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10467: } else {
10468: if ($lastname=~/\S/) {
10469: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10470: $name=~s/\s+,/,/;
10471: } else {
10472: $name.= $firstname.' '.$middlename.' '.$generation;
10473: }
10474: }
10475: $name=~s/^\s+//;
10476: $name=~s/\s+$//;
10477: $name=~s/\s+/ /g;
10478: return $name;
10479: }
10480:
1.84 www 10481: # ------------------------------------------------- Write to course preferences
10482:
10483: sub writecoursepref {
10484: my ($courseid,%prefs)=@_;
10485: $courseid=~s/^\///;
10486: $courseid=~s/\_/\//g;
10487: my ($cdomain,$cnum)=split(/\//,$courseid);
10488: my $chome=homeserver($cnum,$cdomain);
10489: if (($chome eq '') || ($chome eq 'no_host')) {
10490: return 'error: no such course';
10491: }
10492: my $cstring='';
1.800 albertel 10493: foreach my $pref (keys(%prefs)) {
10494: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10495: }
1.84 www 10496: $cstring=~s/\&$//;
10497: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10498: }
10499:
10500: # ---------------------------------------------------------- Make/modify course
10501:
10502: sub createcourse {
1.741 raeburn 10503: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10504: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10505: $url=&declutter($url);
10506: my $cid='';
1.1028 raeburn 10507: if ($context eq 'requestcourses') {
10508: my $can_create = 0;
10509: my ($ownername,$ownerdom) = split(':',$course_owner);
10510: if ($udom eq $ownerdom) {
10511: if (&usertools_access($ownername,$ownerdom,$category,undef,
10512: $context)) {
10513: $can_create = 1;
10514: }
10515: } else {
10516: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10517: $category);
10518: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10519: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10520: if (@curr > 0) {
10521: my @options = qw(approval validate autolimit);
10522: my $optregex = join('|',@options);
10523: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10524: $can_create = 1;
10525: }
10526: }
10527: }
10528: }
10529: if ($can_create) {
10530: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10531: unless (&allowed('ccc',$udom)) {
10532: return 'refused';
10533: }
1.1017 raeburn 10534: }
10535: } else {
10536: return 'refused';
10537: }
1.1028 raeburn 10538: } elsif (!&allowed('ccc',$udom)) {
10539: return 'refused';
1.84 www 10540: }
1.1011 raeburn 10541: # --------------------------------------------------------------- Get Unique ID
10542: my $uname;
10543: if ($cnum =~ /^$match_courseid$/) {
10544: my $chome=&homeserver($cnum,$udom,'true');
10545: if (($chome eq '') || ($chome eq 'no_host')) {
10546: $uname = $cnum;
10547: } else {
1.1038 raeburn 10548: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10549: }
10550: } else {
1.1038 raeburn 10551: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10552: }
10553: return $uname if ($uname =~ /^error/);
10554: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10555: if (!defined($course_server)) {
10556: if (defined(&domain($udom,'primary'))) {
10557: $course_server = &domain($udom,'primary');
10558: } else {
10559: $course_server = $env{'user.home'};
10560: }
10561: }
10562: my %host_servers =
10563: &Apache::lonnet::get_servers($udom,'library');
10564: unless ($host_servers{$course_server}) {
10565: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10566: }
1.84 www 10567: # ------------------------------------------------------------- Make the course
10568: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10569: $course_server);
1.84 www 10570: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10571: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10572: if (($uhome eq '') || ($uhome eq 'no_host')) {
10573: return 'error: no such course';
10574: }
1.271 www 10575: # ----------------------------------------------------------------- Course made
1.516 raeburn 10576: # log existence
1.1029 raeburn 10577: my $now = time;
1.918 raeburn 10578: my $newcourse = {
10579: $udom.'_'.$uname => {
1.921 raeburn 10580: description => $description,
10581: inst_code => $inst_code,
10582: owner => $course_owner,
10583: type => $crstype,
1.1029 raeburn 10584: creator => $env{'user.name'}.':'.
10585: $env{'user.domain'},
10586: created => $now,
10587: context => $context,
1.918 raeburn 10588: },
10589: };
1.921 raeburn 10590: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10591: # set toplevel url
1.271 www 10592: my $topurl=$url;
10593: unless ($nonstandard) {
10594: # ------------------------------------------ For standard courses, make top url
10595: my $mapurl=&clutter($url);
1.278 www 10596: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10597: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10598: <map>
10599: <resource id="1" type="start"></resource>
10600: <resource id="2" src="$mapurl"></resource>
10601: <resource id="3" type="finish"></resource>
10602: <link index="1" from="1" to="2"></link>
10603: <link index="2" from="2" to="3"></link>
10604: </map>
10605: ENDINITMAP
10606: $topurl=&declutter(
1.638 albertel 10607: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10608: );
10609: }
10610: # ----------------------------------------------------------- Write preferences
1.84 www 10611: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10612: ('description' => $description,
10613: 'url' => $topurl,
10614: 'internal.creator' => $env{'user.name'}.':'.
10615: $env{'user.domain'},
10616: 'internal.created' => $now,
10617: 'internal.creationcontext' => $context)
10618: );
1.84 www 10619: return '/'.$udom.'/'.$uname;
10620: }
10621:
1.1011 raeburn 10622: # ------------------------------------------------------------------- Create ID
10623: sub generate_coursenum {
1.1038 raeburn 10624: my ($udom,$crstype) = @_;
1.1011 raeburn 10625: my $domdesc = &domain($udom);
10626: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10627: my $first;
10628: if ($crstype eq 'Community') {
10629: $first = '0';
10630: } else {
10631: $first = int(1+rand(9));
10632: }
10633: my $uname=$first.
1.1011 raeburn 10634: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10635: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10636: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10637: # ----------------------------------------------- Make sure that does not exist
10638: my $uhome=&homeserver($uname,$udom,'true');
10639: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10640: if ($crstype eq 'Community') {
10641: $first = '0';
10642: } else {
10643: $first = int(1+rand(9));
10644: }
10645: $uname=$first.
1.1011 raeburn 10646: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10647: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10648: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10649: $uhome=&homeserver($uname,$udom,'true');
10650: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10651: return 'error: unable to generate unique course-ID';
10652: }
10653: }
10654: return $uname;
10655: }
10656:
1.813 albertel 10657: sub is_course {
1.1167 droeschl 10658: my ($cdom, $cnum) = scalar(@_) == 1 ?
10659: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10660: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10661: my $uhome=&homeserver($cnum,$cdom);
10662: my $iscourse;
10663: if (grep { $_ eq $uhome } current_machine_ids()) {
10664: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10665: } else {
10666: my $hashid = $cdom.':'.$cnum;
10667: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10668: unless (defined($cached)) {
10669: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10670: $cnum,undef,undef,'.');
10671: $iscourse = 0;
10672: if (exists($courses{$cdom.'_'.$cnum})) {
10673: $iscourse = 1;
10674: }
10675: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10676: }
10677: }
10678: return unless($iscourse);
1.1167 droeschl 10679: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10680: }
10681:
1.1015 raeburn 10682: sub store_userdata {
10683: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10684: my $result;
1.1016 raeburn 10685: if ($datakey ne '') {
1.1013 raeburn 10686: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10687: if ($udom eq '' || $uname eq '') {
10688: $udom = $env{'user.domain'};
10689: $uname = $env{'user.name'};
10690: }
10691: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10692: if (($uhome eq '') || ($uhome eq 'no_host')) {
10693: $result = 'error: no_host';
10694: } else {
1.1172.2.138 raeburn 10695: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10696: $storehash->{'host'} = $perlvar{'lonHostID'};
10697:
10698: my $namevalue='';
10699: foreach my $key (keys(%{$storehash})) {
10700: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10701: }
10702: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10703: unless ($namespace eq 'courserequests') {
10704: $datakey = &escape($datakey);
10705: }
1.1105 raeburn 10706: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10707: $namevalue,$uhome);
1.1013 raeburn 10708: }
10709: } else {
10710: $result = 'error: data to store was not a hash reference';
10711: }
10712: } else {
10713: $result= 'error: invalid requestkey';
10714: }
10715: return $result;
10716: }
10717:
1.21 www 10718: # ---------------------------------------------------------- Assign Custom Role
10719:
10720: sub assigncustomrole {
1.957 raeburn 10721: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10722: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10723: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10724: }
10725:
10726: # ----------------------------------------------------------------- Revoke Role
10727:
10728: sub revokerole {
1.957 raeburn 10729: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10730: my $now=time;
1.965 raeburn 10731: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10732: }
10733:
10734: # ---------------------------------------------------------- Revoke Custom Role
10735:
10736: sub revokecustomrole {
1.957 raeburn 10737: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10738: my $now=time;
1.357 www 10739: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10740: $deleteflag,$selfenroll,$context);
1.17 www 10741: }
10742:
1.533 banghart 10743: # ------------------------------------------------------------ Disk usage
1.535 albertel 10744: sub diskusage {
1.955 raeburn 10745: my ($udom,$uname,$directorypath,$getpropath)=@_;
10746: $directorypath =~ s/\/$//;
10747: my $listing=&reply('du2:'.&escape($directorypath).':'
10748: .&escape($getpropath).':'.&escape($uname).':'
10749: .&escape($udom),homeserver($uname,$udom));
10750: if ($listing eq 'unknown_cmd') {
10751: if ($getpropath) {
10752: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10753: }
10754: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10755: }
1.514 albertel 10756: return $listing;
1.512 banghart 10757: }
10758:
1.566 banghart 10759: sub is_locked {
1.1096 raeburn 10760: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10761: my @check;
10762: my $is_locked;
1.1093 raeburn 10763: push (@check,$file_name);
1.613 albertel 10764: my %locked = &get('file_permissions',\@check,
1.620 albertel 10765: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10766: my ($tmp)=keys(%locked);
10767: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10768:
1.566 banghart 10769: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10770: $is_locked = 'false';
10771: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10772: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10773: $is_locked = 'true';
1.1096 raeburn 10774: if (ref($which) eq 'ARRAY') {
10775: push(@{$which},$entry);
10776: } else {
10777: last;
10778: }
1.745 raeburn 10779: }
10780: }
1.566 banghart 10781: } else {
10782: $is_locked = 'false';
10783: }
1.1093 raeburn 10784: return $is_locked;
1.566 banghart 10785: }
10786:
1.759 albertel 10787: sub declutter_portfile {
10788: my ($file) = @_;
1.833 albertel 10789: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10790: return $file;
10791: }
10792:
1.559 banghart 10793: # ------------------------------------------------------------- Mark as Read Only
10794:
10795: sub mark_as_readonly {
10796: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10797: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10798: my ($tmp)=keys(%current_permissions);
10799: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10800: foreach my $file (@{$files}) {
1.759 albertel 10801: $file = &declutter_portfile($file);
1.561 banghart 10802: push(@{$current_permissions{$file}},$what);
1.559 banghart 10803: }
1.613 albertel 10804: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10805: return;
10806: }
10807:
1.572 banghart 10808: # ------------------------------------------------------------Save Selected Files
10809:
10810: sub save_selected_files {
10811: my ($user, $path, @files) = @_;
10812: my $filename = $user."savedfiles";
1.573 banghart 10813: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10814: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10815: foreach my $file (@files) {
1.620 albertel 10816: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10817: }
10818: foreach my $file (@other_files) {
1.574 banghart 10819: print (OUT $file."\n");
1.572 banghart 10820: }
1.574 banghart 10821: close (OUT);
1.572 banghart 10822: return 'ok';
10823: }
10824:
1.574 banghart 10825: sub clear_selected_files {
10826: my ($user) = @_;
10827: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10828: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10829: print (OUT undef);
10830: close (OUT);
10831: return ("ok");
10832: }
10833:
1.572 banghart 10834: sub files_in_path {
10835: my ($user, $path) = @_;
10836: my $filename = $user."savedfiles";
10837: my %return_files;
1.1172.2.96 raeburn 10838: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10839: while (my $line_in = <IN>) {
1.574 banghart 10840: chomp ($line_in);
10841: my @paths_and_file = split (m!/!, $line_in);
10842: my $file_part = pop (@paths_and_file);
10843: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10844: $path_part.='/';
10845: my $path_and_file = $path_part.$file_part;
10846: if ($path_part eq $path) {
10847: $return_files{$file_part}= 'selected';
10848: }
10849: }
1.574 banghart 10850: close (IN);
10851: return (\%return_files);
1.572 banghart 10852: }
10853:
10854: # called in portfolio select mode, to show files selected NOT in current directory
10855: sub files_not_in_path {
10856: my ($user, $path) = @_;
10857: my $filename = $user."savedfiles";
10858: my @return_files;
10859: my $path_part;
1.1172.2.96 raeburn 10860: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10861: while (my $line = <IN>) {
1.572 banghart 10862: #ok, I know it's clunky, but I want it to work
1.800 albertel 10863: my @paths_and_file = split(m|/|, $line);
10864: my $file_part = pop(@paths_and_file);
10865: chomp($file_part);
10866: my $path_part = join('/', @paths_and_file);
1.572 banghart 10867: $path_part .= '/';
10868: my $path_and_file = $path_part.$file_part;
10869: if ($path_part ne $path) {
1.800 albertel 10870: push(@return_files, ($path_and_file));
1.572 banghart 10871: }
10872: }
1.800 albertel 10873: close(OUT);
1.574 banghart 10874: return (@return_files);
1.572 banghart 10875: }
10876:
1.745 raeburn 10877: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10878:
1.745 raeburn 10879: sub get_portfile_permissions {
10880: my ($domain,$user) = @_;
1.613 albertel 10881: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10882: my ($tmp)=keys(%current_permissions);
10883: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10884: return \%current_permissions;
10885: }
10886:
10887: #---------------------------------------------Get portfolio file access controls
10888:
1.749 raeburn 10889: sub get_access_controls {
1.745 raeburn 10890: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10891: my %access;
10892: my $real_file = $file;
10893: $file =~ s/\.meta$//;
1.745 raeburn 10894: if (defined($file)) {
1.749 raeburn 10895: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10896: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10897: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10898: }
10899: }
1.745 raeburn 10900: } else {
1.749 raeburn 10901: foreach my $key (keys(%{$current_permissions})) {
10902: if ($key =~ /\0accesscontrol$/) {
10903: if (defined($group)) {
10904: if ($key !~ m-^\Q$group\E/-) {
10905: next;
10906: }
10907: }
10908: my ($fullpath) = split(/\0/,$key);
10909: if (ref($$current_permissions{$key}) eq 'HASH') {
10910: foreach my $control (keys(%{$$current_permissions{$key}})) {
10911: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10912: }
10913: }
10914: }
10915: }
10916: }
10917: return %access;
10918: }
10919:
10920: sub modify_access_controls {
10921: my ($file_name,$changes,$domain,$user)=@_;
10922: my ($outcome,$deloutcome);
10923: my %store_permissions;
10924: my %new_values;
10925: my %new_control;
10926: my %translation;
10927: my @deletions = ();
10928: my $now = time;
10929: if (exists($$changes{'activate'})) {
10930: if (ref($$changes{'activate'}) eq 'HASH') {
10931: my @newitems = sort(keys(%{$$changes{'activate'}}));
10932: my $numnew = scalar(@newitems);
10933: for (my $i=0; $i<$numnew; $i++) {
10934: my $newkey = $newitems[$i];
10935: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10936: if ($newkey =~ /^\d+:/) {
10937: $newkey =~ s/^(\d+)/$newid/;
10938: $translation{$1} = $newid;
10939: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10940: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10941: $translation{$1} = $newid;
10942: }
1.749 raeburn 10943: $new_values{$file_name."\0".$newkey} =
10944: $$changes{'activate'}{$newitems[$i]};
10945: $new_control{$newkey} = $now;
10946: }
10947: }
10948: }
10949: my %todelete;
10950: my %changed_items;
10951: foreach my $action ('delete','update') {
10952: if (exists($$changes{$action})) {
10953: if (ref($$changes{$action}) eq 'HASH') {
10954: foreach my $key (keys(%{$$changes{$action}})) {
10955: my ($itemnum) = ($key =~ /^([^:]+):/);
10956: if ($action eq 'delete') {
10957: $todelete{$itemnum} = 1;
10958: } else {
10959: $changed_items{$itemnum} = $key;
10960: }
10961: }
1.745 raeburn 10962: }
10963: }
1.749 raeburn 10964: }
10965: # get lock on access controls for file.
10966: my $lockhash = {
10967: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10968: ':'.$env{'user.domain'},
10969: };
10970: my $tries = 0;
10971: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10972:
1.1172.2.79 raeburn 10973: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10974: $tries ++;
1.1172.2.79 raeburn 10975: sleep(0.1);
1.749 raeburn 10976: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10977: }
10978: if ($gotlock eq 'ok') {
10979: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10980: my ($tmp)=keys(%curr_permissions);
10981: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10982: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10983: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10984: if (ref($curr_controls) eq 'HASH') {
10985: foreach my $control_item (keys(%{$curr_controls})) {
10986: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10987: if (defined($todelete{$itemnum})) {
10988: push(@deletions,$file_name."\0".$control_item);
10989: } else {
10990: if (defined($changed_items{$itemnum})) {
10991: $new_control{$changed_items{$itemnum}} = $now;
10992: push(@deletions,$file_name."\0".$control_item);
10993: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10994: } else {
10995: $new_control{$control_item} = $$curr_controls{$control_item};
10996: }
10997: }
1.745 raeburn 10998: }
10999: }
11000: }
1.970 raeburn 11001: my ($group);
11002: if (&is_course($domain,$user)) {
11003: ($group,my $file) = split(/\//,$file_name,2);
11004: }
1.749 raeburn 11005: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11006: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11007: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11008: # remove lock
11009: my @del_lock = ($file_name."\0".'locked_access_records');
11010: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11011: my $sqlresult =
1.970 raeburn 11012: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11013: $group);
1.749 raeburn 11014: } else {
11015: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11016: }
1.749 raeburn 11017: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11018: }
11019:
1.827 raeburn 11020: sub make_public_indefinitely {
11021: my ($requrl) = @_;
11022: my $now = time;
11023: my $action = 'activate';
11024: my $aclnum = 0;
11025: if (&is_portfolio_url($requrl)) {
11026: my (undef,$udom,$unum,$file_name,$group) =
11027: &parse_portfolio_url($requrl);
11028: my $current_perms = &get_portfile_permissions($udom,$unum);
11029: my %access_controls = &get_access_controls($current_perms,
11030: $group,$file_name);
11031: foreach my $key (keys(%{$access_controls{$file_name}})) {
11032: my ($num,$scope,$end,$start) =
11033: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11034: if ($scope eq 'public') {
11035: if ($start <= $now && $end == 0) {
11036: $action = 'none';
11037: } else {
11038: $action = 'update';
11039: $aclnum = $num;
11040: }
11041: last;
11042: }
11043: }
11044: if ($action eq 'none') {
11045: return 'ok';
11046: } else {
11047: my %changes;
11048: my $newend = 0;
11049: my $newstart = $now;
11050: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11051: $changes{$action}{$newkey} = {
11052: type => 'public',
11053: time => {
11054: start => $newstart,
11055: end => $newend,
11056: },
11057: };
11058: my ($outcome,$deloutcome,$new_values,$translation) =
11059: &modify_access_controls($file_name,\%changes,$udom,$unum);
11060: return $outcome;
11061: }
11062: } else {
11063: return 'invalid';
11064: }
11065: }
11066:
1.745 raeburn 11067: #------------------------------------------------------Get Marked as Read Only
11068:
11069: sub get_marked_as_readonly {
11070: my ($domain,$user,$what,$group) = @_;
11071: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11072: my @readonly_files;
1.629 banghart 11073: my $cmp1=$what;
11074: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11075: while (my ($file_name,$value) = each(%{$current_permissions})) {
11076: if (defined($group)) {
11077: if ($file_name !~ m-^\Q$group\E/-) {
11078: next;
11079: }
11080: }
1.561 banghart 11081: if (ref($value) eq "ARRAY"){
11082: foreach my $stored_what (@{$value}) {
1.629 banghart 11083: my $cmp2=$stored_what;
1.759 albertel 11084: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11085: $cmp2=join('',@{$stored_what});
1.745 raeburn 11086: }
1.629 banghart 11087: if ($cmp1 eq $cmp2) {
1.561 banghart 11088: push(@readonly_files, $file_name);
1.745 raeburn 11089: last;
1.563 banghart 11090: } elsif (!defined($what)) {
11091: push(@readonly_files, $file_name);
1.745 raeburn 11092: last;
1.561 banghart 11093: }
11094: }
1.745 raeburn 11095: }
1.561 banghart 11096: }
11097: return @readonly_files;
11098: }
1.577 banghart 11099: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11100:
1.577 banghart 11101: sub get_marked_as_readonly_hash {
1.745 raeburn 11102: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11103: my %readonly_files;
1.745 raeburn 11104: while (my ($file_name,$value) = each(%{$current_permissions})) {
11105: if (defined($group)) {
11106: if ($file_name !~ m-^\Q$group\E/-) {
11107: next;
11108: }
11109: }
1.577 banghart 11110: if (ref($value) eq "ARRAY"){
11111: foreach my $stored_what (@{$value}) {
1.745 raeburn 11112: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11113: foreach my $lock_descriptor(@{$stored_what}) {
11114: if ($lock_descriptor eq 'graded') {
11115: $readonly_files{$file_name} = 'graded';
11116: } elsif ($lock_descriptor eq 'handback') {
11117: $readonly_files{$file_name} = 'handback';
11118: } else {
11119: if (!exists($readonly_files{$file_name})) {
11120: $readonly_files{$file_name} = 'locked';
11121: }
11122: }
1.745 raeburn 11123: }
1.750 banghart 11124: }
1.577 banghart 11125: }
11126: }
11127: }
11128: return %readonly_files;
11129: }
1.559 banghart 11130: # ------------------------------------------------------------ Unmark as Read Only
11131:
11132: sub unmark_as_readonly {
1.629 banghart 11133: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11134: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11135: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11136: $file_name = &declutter_portfile($file_name);
1.634 albertel 11137: my $symb_crs = $what;
11138: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11139: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11140: my ($tmp)=keys(%current_permissions);
11141: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11142: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11143: foreach my $file (@readonly_files) {
1.759 albertel 11144: my $clean_file = &declutter_portfile($file);
11145: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11146: my $current_locks = $current_permissions{$file};
1.563 banghart 11147: my @new_locks;
11148: my @del_keys;
11149: if (ref($current_locks) eq "ARRAY"){
11150: foreach my $locker (@{$current_locks}) {
1.632 albertel 11151: my $compare=$locker;
1.749 raeburn 11152: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11153: $compare=join('',@{$locker});
1.746 raeburn 11154: if ($compare ne $symb_crs) {
11155: push(@new_locks, $locker);
11156: }
1.563 banghart 11157: }
11158: }
1.650 albertel 11159: if (scalar(@new_locks) > 0) {
1.563 banghart 11160: $current_permissions{$file} = \@new_locks;
11161: } else {
11162: push(@del_keys, $file);
1.613 albertel 11163: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11164: delete($current_permissions{$file});
1.563 banghart 11165: }
11166: }
1.561 banghart 11167: }
1.613 albertel 11168: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11169: return;
11170: }
1.512 banghart 11171:
1.17 www 11172: # ------------------------------------------------------------ Directory lister
11173:
11174: sub dirlist {
1.955 raeburn 11175: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11176: $uri=~s/^\///;
11177: $uri=~s/\/$//;
1.253 stredwic 11178: my ($udom, $uname);
1.955 raeburn 11179: if ($getuserdir) {
1.253 stredwic 11180: $udom = $userdomain;
11181: $uname = $username;
1.955 raeburn 11182: } else {
11183: (undef,$udom,$uname)=split(/\//,$uri);
11184: if(defined($userdomain)) {
11185: $udom = $userdomain;
11186: }
11187: if(defined($username)) {
11188: $uname = $username;
11189: }
1.253 stredwic 11190: }
1.955 raeburn 11191: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11192:
1.955 raeburn 11193: $dirRoot = $perlvar{'lonDocRoot'};
11194: if (defined($getpropath)) {
11195: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11196: $dirRoot =~ s/\/$//;
1.955 raeburn 11197: } elsif (defined($getuserdir)) {
11198: my $subdir=$uname.'__';
11199: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11200: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11201: ."/$udom/$subdir/$uname";
11202: } elsif (defined($alternateRoot)) {
11203: $dirRoot = $alternateRoot;
1.751 banghart 11204: }
1.253 stredwic 11205:
11206: if($udom) {
11207: if($uname) {
1.1135 raeburn 11208: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11209: if ($uhome eq 'no_host') {
11210: return ([],'no_host');
11211: }
1.955 raeburn 11212: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11213: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11214: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11215: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11216: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11217: } else {
11218: @listing_results = map { &unescape($_); } split(/:/,$listing);
11219: }
1.605 matthew 11220: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11221: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11222: @listing_results = split(/:/,$listing);
11223: } else {
11224: @listing_results = map { &unescape($_); } split(/:/,$listing);
11225: }
1.1135 raeburn 11226: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11227: ($listing eq 'rejected') || ($listing eq 'refused') ||
11228: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11229: return ([],$listing);
11230: } else {
11231: return (\@listing_results);
1.1135 raeburn 11232: }
1.955 raeburn 11233: } elsif(!$alternateRoot) {
1.1136 raeburn 11234: my (%allusers,%listerror);
1.841 albertel 11235: my %servers = &get_servers($udom,'library');
1.955 raeburn 11236: foreach my $tryserver (keys(%servers)) {
11237: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11238: &escape($udom),$tryserver);
11239: if ($listing eq 'unknown_cmd') {
11240: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11241: $udom, $tryserver);
11242: } else {
11243: @listing_results = map { &unescape($_); } split(/:/,$listing);
11244: }
1.841 albertel 11245: if ($listing eq 'unknown_cmd') {
11246: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11247: $udom, $tryserver);
11248: @listing_results = split(/:/,$listing);
11249: } else {
11250: @listing_results =
11251: map { &unescape($_); } split(/:/,$listing);
11252: }
1.1136 raeburn 11253: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11254: ($listing eq 'rejected') || ($listing eq 'refused') ||
11255: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11256: $listerror{$tryserver} = $listing;
11257: } else {
1.841 albertel 11258: foreach my $line (@listing_results) {
11259: my ($entry) = split(/&/,$line,2);
11260: $allusers{$entry} = 1;
11261: }
11262: }
1.253 stredwic 11263: }
1.1136 raeburn 11264: my @alluserslist=();
1.800 albertel 11265: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11266: push(@alluserslist,$user.'&user');
1.253 stredwic 11267: }
1.1172.2.80 raeburn 11268: if (!%listerror) {
11269: # no errors
11270: return (\@alluserslist);
11271: } elsif (scalar(keys(%servers)) == 1) {
11272: # one library server, one error
11273: my ($key) = keys(%listerror);
11274: return (\@alluserslist, $listerror{$key});
11275: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11276: # con_lost indicates that we might miss data from at least one
11277: # library server
11278: return (\@alluserslist, 'con_lost');
11279: } else {
11280: # multiple library servers and no con_lost -> data should be
11281: # complete.
11282: return (\@alluserslist);
11283: }
11284:
1.253 stredwic 11285: } else {
1.1136 raeburn 11286: return ([],'missing username');
1.253 stredwic 11287: }
1.955 raeburn 11288: } elsif(!defined($getpropath)) {
1.1136 raeburn 11289: my $path = $perlvar{'lonDocRoot'}.'/res/';
11290: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11291: return (\@all_domains);
1.955 raeburn 11292: } else {
1.1136 raeburn 11293: return ([],'missing domain');
1.275 stredwic 11294: }
11295: }
11296:
11297: # --------------------------------------------- GetFileTimestamp
11298: # This function utilizes dirlist and returns the date stamp for
11299: # when it was last modified. It will also return an error of -1
11300: # if an error occurs
11301:
11302: sub GetFileTimestamp {
1.955 raeburn 11303: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11304: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11305: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11306: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11307: undef,$getuserdir);
11308: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11309: return -1;
11310: }
11311: if (ref($fileref) eq 'ARRAY') {
11312: my @stats = split('&',$fileref->[0]);
1.375 matthew 11313: # @stats contains first the filename, then the stat output
11314: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11315: } else {
11316: return -1;
1.253 stredwic 11317: }
1.26 www 11318: }
11319:
1.712 albertel 11320: sub stat_file {
11321: my ($uri) = @_;
1.787 albertel 11322: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11323:
1.955 raeburn 11324: my ($udom,$uname,$file);
1.712 albertel 11325: if ($uri =~ m-^/(uploaded|editupload)/-) {
11326: ($udom,$uname,$file) =
1.811 albertel 11327: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11328: $file = 'userfiles/'.$file;
11329: }
11330: if ($uri =~ m-^/res/-) {
11331: ($udom,$uname) =
1.807 albertel 11332: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11333: $file = $uri;
11334: }
11335:
11336: if (!$udom || !$uname || !$file) {
11337: # unable to handle the uri
11338: return ();
11339: }
1.956 raeburn 11340: my $getpropath;
11341: if ($file =~ /^userfiles\//) {
11342: $getpropath = 1;
11343: }
1.1136 raeburn 11344: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11345: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11346: return ();
11347: } else {
11348: if (ref($listref) eq 'ARRAY') {
11349: my @stats = split('&',$listref->[0]);
11350: shift(@stats); #filename is first
11351: return @stats;
11352: }
1.712 albertel 11353: }
11354: return ();
11355: }
11356:
1.26 www 11357: # -------------------------------------------------------- Value of a Condition
11358:
1.713 albertel 11359: # gets the value of a specific preevaluated condition
11360: # stored in the string $env{user.state.<cid>}
11361: # or looks up a condition reference in the bighash and if if hasn't
11362: # already been evaluated recurses into docondval to get the value of
11363: # the condition, then memoizing it to
11364: # $env{user.state.<cid>.<condition>}
1.40 www 11365: sub directcondval {
11366: my $number=shift;
1.620 albertel 11367: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11368: &Apache::lonuserstate::evalstate();
11369: }
1.713 albertel 11370: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11371: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11372: } elsif ($number =~ /^_/) {
11373: my $sub_condition;
11374: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11375: &GDBM_READER(),0640)) {
11376: $sub_condition=$bighash{'conditions'.$number};
11377: untie(%bighash);
11378: }
11379: my $value = &docondval($sub_condition);
1.949 raeburn 11380: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11381: return $value;
11382: }
1.620 albertel 11383: if ($env{'user.state.'.$env{'request.course.id'}}) {
11384: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11385: } else {
11386: return 2;
11387: }
11388: }
11389:
1.713 albertel 11390: # get the collection of conditions for this resource
1.26 www 11391: sub condval {
11392: my $condidx=shift;
1.54 www 11393: my $allpathcond='';
1.713 albertel 11394: foreach my $cond (split(/\|/,$condidx)) {
11395: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11396: $allpathcond.=
11397: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11398: }
1.191 harris41 11399: }
1.54 www 11400: $allpathcond=~s/\|$//;
1.713 albertel 11401: return &docondval($allpathcond);
11402: }
11403:
11404: #evaluates an expression of conditions
11405: sub docondval {
11406: my ($allpathcond) = @_;
11407: my $result=0;
11408: if ($env{'request.course.id'}
11409: && defined($allpathcond)) {
11410: my $operand='|';
11411: my @stack;
11412: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11413: if ($chunk eq '(') {
11414: push @stack,($operand,$result);
11415: } elsif ($chunk eq ')') {
11416: my $before=pop @stack;
11417: if (pop @stack eq '&') {
11418: $result=$result>$before?$before:$result;
11419: } else {
11420: $result=$result>$before?$result:$before;
11421: }
11422: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11423: $operand=$chunk;
11424: } else {
11425: my $new=directcondval($chunk);
11426: if ($operand eq '&') {
11427: $result=$result>$new?$new:$result;
11428: } else {
11429: $result=$result>$new?$result:$new;
11430: }
11431: }
11432: }
1.26 www 11433: }
11434: return $result;
1.421 albertel 11435: }
11436:
11437: # ---------------------------------------------------- Devalidate courseresdata
11438:
11439: sub devalidatecourseresdata {
11440: my ($coursenum,$coursedomain)=@_;
11441: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11442: &devalidate_cache_new('courseres',$hashid);
1.28 www 11443: }
11444:
1.763 www 11445:
1.200 www 11446: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11447: #
11448: # Parameters:
11449: # $coursenum - Number of the course.
11450: # $coursedomain - Domain at which the course was created.
11451: # Returns:
11452: # A hash of the course parameters along (I think) with timestamps
11453: # and version info.
1.877 foxr 11454:
1.624 albertel 11455: sub get_courseresdata {
11456: my ($coursenum,$coursedomain)=@_;
1.200 www 11457: my $coursehom=&homeserver($coursenum,$coursedomain);
11458: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11459: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11460: my %dumpreply;
1.417 albertel 11461: unless (defined($cached)) {
1.624 albertel 11462: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11463: $result=\%dumpreply;
1.251 albertel 11464: my ($tmp) = keys(%dumpreply);
11465: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11466: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11467: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11468: return $tmp;
1.416 albertel 11469: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11470: $result=undef;
1.599 albertel 11471: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11472: }
11473: }
1.624 albertel 11474: return $result;
11475: }
11476:
1.633 albertel 11477: sub devalidateuserresdata {
11478: my ($uname,$udom)=@_;
11479: my $hashid="$udom:$uname";
11480: &devalidate_cache_new('userres',$hashid);
11481: }
11482:
1.624 albertel 11483: sub get_userresdata {
11484: my ($uname,$udom)=@_;
11485: #most student don\'t have any data set, check if there is some data
11486: if (&EXT_cache_status($udom,$uname)) { return undef; }
11487:
11488: my $hashid="$udom:$uname";
11489: my ($result,$cached)=&is_cached_new('userres',$hashid);
11490: if (!defined($cached)) {
11491: my %resourcedata=&dump('resourcedata',$udom,$uname);
11492: $result=\%resourcedata;
11493: &do_cache_new('userres',$hashid,$result,600);
11494: }
11495: my ($tmp)=keys(%$result);
11496: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11497: return $result;
11498: }
11499: #error 2 occurs when the .db doesn't exist
11500: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11501: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11502: &logthis("<font color=\"blue\">WARNING:".
11503: " Trying to get resource data for ".
11504: $uname." at ".$udom.": ".
11505: $tmp."</font>");
11506: }
1.624 albertel 11507: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11508: #&EXT_cache_set($udom,$uname);
11509: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11510: undef($tmp); # not really an error so don't send it back
1.624 albertel 11511: }
11512: return $tmp;
11513: }
1.879 foxr 11514: #----------------------------------------------- resdata - return resource data
11515: # Purpose:
11516: # Return resource data for either users or for a course.
11517: # Parameters:
11518: # $name - Course/user name.
11519: # $domain - Name of the domain the user/course is registered on.
11520: # $type - Type of thing $name is (must be 'course' or 'user'
11521: # @which - Array of names of resources desired.
11522: # Returns:
11523: # The value of the first reasource in @which that is found in the
11524: # resource hash.
11525: # Exceptional Conditions:
11526: # If the $type passed in is not valid (not the string 'course' or
11527: # 'user', an undefined reference is returned.
11528: # If none of the resources are found, an undef is returned
1.624 albertel 11529: sub resdata {
11530: my ($name,$domain,$type,@which)=@_;
11531: my $result;
11532: if ($type eq 'course') {
11533: $result=&get_courseresdata($name,$domain);
11534: } elsif ($type eq 'user') {
11535: $result=&get_userresdata($name,$domain);
11536: }
11537: if (!ref($result)) { return $result; }
1.251 albertel 11538: foreach my $item (@which) {
1.927 albertel 11539: if (defined($result->{$item->[0]})) {
11540: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11541: }
1.250 albertel 11542: }
1.291 albertel 11543: return undef;
1.200 www 11544: }
11545:
1.1172.2.31 raeburn 11546: sub get_numsuppfiles {
11547: my ($cnum,$cdom,$ignorecache)=@_;
11548: my $hashid=$cnum.':'.$cdom;
11549: my ($suppcount,$cached);
11550: unless ($ignorecache) {
11551: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11552: }
11553: unless (defined($cached)) {
11554: my $chome=&homeserver($cnum,$cdom);
11555: unless ($chome eq 'no_host') {
11556: ($suppcount,my $errors) = (0,0);
11557: my $suppmap = 'supplemental.sequence';
11558: ($suppcount,$errors) =
11559: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11560: }
11561: &do_cache_new('suppcount',$hashid,$suppcount,600);
11562: }
11563: return $suppcount;
11564: }
11565:
1.379 matthew 11566: #
11567: # EXT resource caching routines
11568: #
11569:
11570: sub clear_EXT_cache_status {
1.383 albertel 11571: &delenv('cache.EXT.');
1.379 matthew 11572: }
11573:
11574: sub EXT_cache_status {
11575: my ($target_domain,$target_user) = @_;
1.383 albertel 11576: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11577: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11578: # We know already the user has no data
11579: return 1;
11580: } else {
11581: return 0;
11582: }
11583: }
11584:
11585: sub EXT_cache_set {
11586: my ($target_domain,$target_user) = @_;
1.383 albertel 11587: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11588: #&appenv({$cachename => time});
1.379 matthew 11589: }
11590:
1.28 www 11591: # --------------------------------------------------------- Value of a Variable
1.58 www 11592: sub EXT {
1.715 albertel 11593:
1.1172.2.28 raeburn 11594: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11595: unless ($varname) { return ''; }
1.218 albertel 11596: #get real user name/domain, courseid and symb
11597: my $courseid;
1.359 albertel 11598: my $publicuser;
1.427 www 11599: if ($symbparm) {
11600: $symbparm=&get_symb_from_alias($symbparm);
11601: }
1.218 albertel 11602: if (!($uname && $udom)) {
1.790 albertel 11603: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11604: if (!$symbparm) { $symbparm=$cursymb; }
11605: } else {
1.620 albertel 11606: $courseid=$env{'request.course.id'};
1.218 albertel 11607: }
1.48 www 11608: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11609: my $rest;
1.320 albertel 11610: if (defined($therest[0])) {
1.48 www 11611: $rest=join('.',@therest);
11612: } else {
11613: $rest='';
11614: }
1.320 albertel 11615:
1.57 www 11616: my $qualifierrest=$qualifier;
11617: if ($rest) { $qualifierrest.='.'.$rest; }
11618: my $spacequalifierrest=$space;
11619: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11620: if ($realm eq 'user') {
1.48 www 11621: # --------------------------------------------------------------- user.resource
11622: if ($space eq 'resource') {
1.651 albertel 11623: if ( (defined($Apache::lonhomework::parsing_a_problem)
11624: || defined($Apache::lonhomework::parsing_a_task))
11625: &&
1.1172.2.142 raeburn 11626: ($symbparm eq &symbread()) ) {
1.744 albertel 11627: # if we are in the middle of processing the resource the
11628: # get the value we are planning on committing
11629: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11630: return $Apache::lonhomework::results{$qualifierrest};
11631: } else {
11632: return $Apache::lonhomework::history{$qualifierrest};
11633: }
1.335 albertel 11634: } else {
1.359 albertel 11635: my %restored;
1.620 albertel 11636: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11637: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11638: } else {
11639: %restored=&restore($symbparm,$courseid,$udom,$uname);
11640: }
1.335 albertel 11641: return $restored{$qualifierrest};
11642: }
1.48 www 11643: # ----------------------------------------------------------------- user.access
11644: } elsif ($space eq 'access') {
1.218 albertel 11645: # FIXME - not supporting calls for a specific user
1.48 www 11646: return &allowed($qualifier,$rest);
11647: # ------------------------------------------ user.preferences, user.environment
11648: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11649: if (($uname eq $env{'user.name'}) &&
11650: ($udom eq $env{'user.domain'})) {
11651: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11652: } else {
1.359 albertel 11653: my %returnhash;
11654: if (!$publicuser) {
11655: %returnhash=&userenvironment($udom,$uname,
11656: $qualifierrest);
11657: }
1.218 albertel 11658: return $returnhash{$qualifierrest};
11659: }
1.48 www 11660: # ----------------------------------------------------------------- user.course
11661: } elsif ($space eq 'course') {
1.218 albertel 11662: # FIXME - not supporting calls for a specific user
1.620 albertel 11663: return $env{join('.',('request.course',$qualifier))};
1.48 www 11664: # ------------------------------------------------------------------- user.role
11665: } elsif ($space eq 'role') {
1.218 albertel 11666: # FIXME - not supporting calls for a specific user
1.620 albertel 11667: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11668: if ($qualifier eq 'value') {
11669: return $role;
11670: } elsif ($qualifier eq 'extent') {
11671: return $where;
11672: }
11673: # ----------------------------------------------------------------- user.domain
11674: } elsif ($space eq 'domain') {
1.218 albertel 11675: return $udom;
1.48 www 11676: # ------------------------------------------------------------------- user.name
11677: } elsif ($space eq 'name') {
1.218 albertel 11678: return $uname;
1.48 www 11679: # ---------------------------------------------------- Any other user namespace
1.29 www 11680: } else {
1.359 albertel 11681: my %reply;
11682: if (!$publicuser) {
11683: %reply=&get($space,[$qualifierrest],$udom,$uname);
11684: }
11685: return $reply{$qualifierrest};
1.48 www 11686: }
1.236 www 11687: } elsif ($realm eq 'query') {
11688: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11689: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11690: [$spacequalifierrest]);
1.620 albertel 11691: return $env{'form.'.$spacequalifierrest};
1.236 www 11692: } elsif ($realm eq 'request') {
1.48 www 11693: # ------------------------------------------------------------- request.browser
11694: if ($space eq 'browser') {
1.1145 bisitz 11695: return $env{'browser.'.$qualifier};
1.57 www 11696: # ------------------------------------------------------------ request.filename
11697: } else {
1.620 albertel 11698: return $env{'request.'.$spacequalifierrest};
1.29 www 11699: }
1.28 www 11700: } elsif ($realm eq 'course') {
1.48 www 11701: # ---------------------------------------------------------- course.description
1.620 albertel 11702: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11703: } elsif ($realm eq 'resource') {
1.165 www 11704:
1.620 albertel 11705: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11706: if (!$symbparm) { $symbparm=&symbread(); }
11707: }
1.693 albertel 11708:
1.1172.2.30 raeburn 11709: if ($qualifier eq '') {
11710: if ($space eq 'title') {
11711: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11712: return &gettitle($symbparm);
11713: }
1.693 albertel 11714:
1.1172.2.30 raeburn 11715: if ($space eq 'map') {
11716: my ($map) = &decode_symb($symbparm);
11717: return &symbread($map);
11718: }
11719: if ($space eq 'maptitle') {
11720: my ($map) = &decode_symb($symbparm);
11721: return &gettitle($map);
11722: }
11723: if ($space eq 'filename') {
11724: if ($symbparm) {
11725: return &clutter((&decode_symb($symbparm))[2]);
11726: }
11727: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11728: }
1.1172.2.30 raeburn 11729:
11730: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11731: if ($space eq 'visibleparts') {
11732: my $navmap = Apache::lonnavmaps::navmap->new();
11733: my $item;
11734: if (ref($navmap)) {
11735: my $res = $navmap->getBySymb($symbparm);
11736: my $parts = $res->parts();
11737: if (ref($parts) eq 'ARRAY') {
11738: $item = join(',',@{$parts});
11739: }
11740: undef($navmap);
11741: }
11742: return $item;
11743: }
11744: }
11745: }
1.693 albertel 11746:
11747: my ($section, $group, @groups);
1.593 albertel 11748: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11749: if (($courseid eq '') && ($cid)) {
11750: $courseid = $cid;
11751: }
11752: if (($symbparm && $courseid) &&
11753: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11754:
1.218 albertel 11755: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11756:
1.60 www 11757: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11758: my $symbp=$symbparm;
1.735 albertel 11759: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11760:
11761: my $symbparm=$symbp.'.'.$spacequalifierrest;
11762: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11763:
1.620 albertel 11764: if (($env{'user.name'} eq $uname) &&
11765: ($env{'user.domain'} eq $udom)) {
11766: $section=$env{'request.course.sec'};
1.733 raeburn 11767: @groups = split(/:/,$env{'request.course.groups'});
11768: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11769: } else {
1.539 albertel 11770: if (! defined($usection)) {
1.551 albertel 11771: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11772: } else {
11773: $section = $usection;
11774: }
1.733 raeburn 11775: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11776: }
11777:
11778: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11779: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11780: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11781:
1.593 albertel 11782: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11783: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11784: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11785:
1.60 www 11786: # ----------------------------------------------------------- first, check user
1.624 albertel 11787:
11788: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11789: ([$courselevelr,'resource'],
11790: [$courselevelm,'map' ],
11791: [$courselevel, 'course' ]));
1.931 albertel 11792: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11793:
1.594 albertel 11794: # ------------------------------------------------ second, check some of course
1.684 raeburn 11795: my $coursereply;
1.691 raeburn 11796: if (@groups > 0) {
11797: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11798: $mapparm,$spacequalifierrest);
1.927 albertel 11799: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11800: }
1.96 www 11801:
1.684 raeburn 11802: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11803: $env{'course.'.$courseid.'.domain'},
11804: 'course',
11805: ([$seclevelr, 'resource'],
11806: [$seclevelm, 'map' ],
11807: [$seclevel, 'course' ],
11808: [$courselevelr,'resource']));
11809: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11810:
1.60 www 11811: # ------------------------------------------------------ third, check map parms
1.218 albertel 11812: my %parmhash=();
11813: my $thisparm='';
11814: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11815: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11816: &GDBM_READER(),0640)) {
1.218 albertel 11817: $thisparm=$parmhash{$symbparm};
11818: untie(%parmhash);
11819: }
1.927 albertel 11820: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11821: }
1.594 albertel 11822: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11823:
1.218 albertel 11824: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11825: my $filename;
11826: if (!$symbparm) { $symbparm=&symbread(); }
11827: if ($symbparm) {
1.409 www 11828: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11829: } else {
1.620 albertel 11830: $filename=$env{'request.filename'};
1.282 albertel 11831: }
11832: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11833: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11834: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11835: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11836:
1.927 albertel 11837: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11838: if ($symbparm && defined($courseid) &&
1.620 albertel 11839: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11840: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11841: $env{'course.'.$courseid.'.domain'},
11842: 'course',
1.927 albertel 11843: ([$courselevelm,'map' ],
11844: [$courselevel, 'course']));
11845: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11846: }
1.145 www 11847: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11848: unless ($space eq '0') {
1.336 albertel 11849: my @parts=split(/_/,$space);
11850: my $id=pop(@parts);
11851: my $part=join('_',@parts);
11852: if ($part eq '') { $part='0'; }
1.927 albertel 11853: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11854: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11855: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11856: }
1.395 albertel 11857: if ($recurse) { return undef; }
11858: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11859: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11860: # ---------------------------------------------------- Any other user namespace
11861: } elsif ($realm eq 'environment') {
11862: # ----------------------------------------------------------------- environment
1.620 albertel 11863: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11864: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11865: } else {
1.770 albertel 11866: if ($uname eq 'anonymous' && $udom eq '') {
11867: return '';
11868: }
1.219 albertel 11869: my %returnhash=&userenvironment($udom,$uname,
11870: $spacequalifierrest);
11871: return $returnhash{$spacequalifierrest};
11872: }
1.28 www 11873: } elsif ($realm eq 'system') {
1.48 www 11874: # ----------------------------------------------------------------- system.time
11875: if ($space eq 'time') {
11876: return time;
11877: }
1.696 albertel 11878: } elsif ($realm eq 'server') {
11879: # ----------------------------------------------------------------- system.time
11880: if ($space eq 'name') {
11881: return $ENV{'SERVER_NAME'};
11882: }
1.28 www 11883: }
1.48 www 11884: return '';
1.61 www 11885: }
11886:
1.927 albertel 11887: sub get_reply {
11888: my ($reply_value) = @_;
1.940 raeburn 11889: if (ref($reply_value) eq 'ARRAY') {
11890: if (wantarray) {
11891: return @$reply_value;
11892: }
11893: return $reply_value->[0];
11894: } else {
11895: return $reply_value;
1.927 albertel 11896: }
11897: }
11898:
1.691 raeburn 11899: sub check_group_parms {
11900: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11901: my @groupitems = ();
11902: my $resultitem;
1.927 albertel 11903: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11904: foreach my $group (@{$groups}) {
11905: foreach my $level (@levels) {
1.927 albertel 11906: my $item = $courseid.'.['.$group.'].'.$level->[0];
11907: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11908: }
11909: }
11910: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11911: $env{'course.'.$courseid.'.domain'},
11912: 'course',@groupitems);
11913: return $coursereply;
11914: }
11915:
11916: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11917: my ($courseid,@groups) = @_;
11918: @groups = sort(@groups);
1.691 raeburn 11919: return @groups;
11920: }
11921:
1.395 albertel 11922: sub packages_tab_default {
11923: my ($uri,$varname)=@_;
11924: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11925:
11926: my (@extension,@specifics,$do_default);
11927: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11928: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11929: if ($pack_type eq 'default') {
11930: $do_default=1;
11931: } elsif ($pack_type eq 'extension') {
11932: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11933: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11934: # only look at packages defaults for packages that this id is
1.738 albertel 11935: push(@specifics,[$package,$pack_type,$pack_part]);
11936: }
11937: }
11938: # first look for a package that matches the requested part id
11939: foreach my $package (@specifics) {
11940: my (undef,$pack_type,$pack_part)=@{$package};
11941: next if ($pack_part ne $part);
11942: if (defined($packagetab{"$pack_type&$name&default"})) {
11943: return $packagetab{"$pack_type&$name&default"};
11944: }
11945: }
11946: # look for any possible matching non extension_ package
11947: foreach my $package (@specifics) {
11948: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11949: if (defined($packagetab{"$pack_type&$name&default"})) {
11950: return $packagetab{"$pack_type&$name&default"};
11951: }
1.585 albertel 11952: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11953: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11954: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11955: }
11956: }
1.738 albertel 11957: # look for any posible extension_ match
11958: foreach my $package (@extension) {
11959: my ($package,$pack_type)=@{$package};
11960: if (defined($packagetab{"$pack_type&$name&default"})) {
11961: return $packagetab{"$pack_type&$name&default"};
11962: }
11963: if (defined($packagetab{$package."&$name&default"})) {
11964: return $packagetab{$package."&$name&default"};
11965: }
11966: }
11967: # look for a global default setting
11968: if ($do_default && defined($packagetab{"default&$name&default"})) {
11969: return $packagetab{"default&$name&default"};
11970: }
1.395 albertel 11971: return undef;
11972: }
11973:
1.334 albertel 11974: sub add_prefix_and_part {
11975: my ($prefix,$part)=@_;
11976: my $keyroot;
11977: if (defined($prefix) && $prefix !~ /^__/) {
11978: # prefix that has a part already
11979: $keyroot=$prefix;
11980: } elsif (defined($prefix)) {
11981: # prefix that is missing a part
11982: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11983: } else {
11984: # no prefix at all
11985: if (defined($part)) { $keyroot='_'.$part; }
11986: }
11987: return $keyroot;
11988: }
11989:
1.71 www 11990: # ---------------------------------------------------------------- Get metadata
11991:
1.599 albertel 11992: my %metaentry;
1.1070 www 11993: my %importedpartids;
1.1172.2.99 raeburn 11994: my %importedrespids;
1.71 www 11995: sub metadata {
1.176 www 11996: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11997: $uri=&declutter($uri);
1.288 albertel 11998: # if it is a non metadata possible uri return quickly
1.529 albertel 11999: if (($uri eq '') ||
12000: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 12001: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 12002: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12003: return undef;
12004: }
1.1172.2.49 raeburn 12005: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12006: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12007: return undef;
1.288 albertel 12008: }
1.73 www 12009: my $filename=$uri;
12010: $uri=~s/\.meta$//;
1.172 www 12011: #
12012: # Is the metadata already cached?
1.177 www 12013: # Look at timestamp of caching
1.172 www 12014: # Everything is cached by the main uri, libraries are never directly cached
12015: #
1.428 albertel 12016: if (!defined($liburi)) {
1.599 albertel 12017: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12018: if (defined($cached)) { return $result->{':'.$what}; }
12019: }
12020: {
1.1069 www 12021: # Imported parts would go here
1.1172.2.99 raeburn 12022: my @origfiletagids=();
1.1069 www 12023: my $importedparts=0;
1.1172.2.99 raeburn 12024:
12025: # Imported responseids would go here
12026: my $importedresponses=0;
1.172 www 12027: #
12028: # Is this a recursive call for a library?
12029: #
1.599 albertel 12030: # if (! exists($metacache{$uri})) {
12031: # $metacache{$uri}={};
12032: # }
1.924 albertel 12033: my $cachetime = 60*60;
1.171 www 12034: if ($liburi) {
12035: $liburi=&declutter($liburi);
12036: $filename=$liburi;
1.401 bowersj2 12037: } else {
1.599 albertel 12038: &devalidate_cache_new('meta',$uri);
12039: undef(%metaentry);
1.401 bowersj2 12040: }
1.140 www 12041: my %metathesekeys=();
1.73 www 12042: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12043: my $metastring;
1.1140 www 12044: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12045: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12046: $metastring =
1.929 albertel 12047: &Apache::lonnet::ssi_body($which,
1.924 albertel 12048: ('grade_target' => 'meta'));
12049: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12050: } elsif (($uri !~ m -^(editupload)/-) &&
12051: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12052: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12053: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12054: $metastring=&getfile($file);
1.489 albertel 12055: }
1.208 albertel 12056: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12057: my $token;
1.140 www 12058: undef %metathesekeys;
1.71 www 12059: while ($token=$parser->get_token) {
1.339 albertel 12060: if ($token->[0] eq 'S') {
12061: if (defined($token->[2]->{'package'})) {
1.172 www 12062: #
12063: # This is a package - get package info
12064: #
1.339 albertel 12065: my $package=$token->[2]->{'package'};
12066: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12067: if (defined($token->[2]->{'id'})) {
12068: $keyroot.='_'.$token->[2]->{'id'};
12069: }
1.599 albertel 12070: if ($metaentry{':packages'}) {
12071: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12072: } else {
1.599 albertel 12073: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12074: }
1.736 albertel 12075: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12076: my $part=$keyroot;
12077: $part=~s/^\_//;
1.736 albertel 12078: if ($pack_entry=~/^\Q$package\E\&/ ||
12079: $pack_entry=~/^\Q$package\E_0\&/) {
12080: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12081: # ignore package.tab specified default values
12082: # here &package_tab_default() will fetch those
12083: if ($subp eq 'default') { next; }
1.736 albertel 12084: my $value=$packagetab{$pack_entry};
1.432 albertel 12085: my $unikey;
12086: if ($pack =~ /_0$/) {
12087: $unikey='parameter_0_'.$name;
12088: $part=0;
12089: } else {
12090: $unikey='parameter'.$keyroot.'_'.$name;
12091: }
1.339 albertel 12092: if ($subp eq 'display') {
12093: $value.=' [Part: '.$part.']';
12094: }
1.599 albertel 12095: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12096: $metathesekeys{$unikey}=1;
1.599 albertel 12097: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12098: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12099: }
1.599 albertel 12100: if (defined($metaentry{':'.$unikey.'.default'})) {
12101: $metaentry{':'.$unikey}=
12102: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12103: }
1.339 albertel 12104: }
12105: }
12106: } else {
1.172 www 12107: #
12108: # This is not a package - some other kind of start tag
1.339 albertel 12109: #
12110: my $entry=$token->[1];
1.1068 www 12111: my $unikey='';
1.175 www 12112:
1.339 albertel 12113: if ($entry eq 'import') {
1.175 www 12114: #
12115: # Importing a library here
1.339 albertel 12116: #
1.1067 www 12117: my $location=$parser->get_text('/import');
12118: my $dir=$filename;
12119: $dir=~s|[^/]*$||;
12120: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12121:
12122: my $importid=$token->[2]->{'id'};
1.1068 www 12123: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12124: #
12125: # Check metadata for imported file to
12126: # see if it contained response items
12127: #
12128: my %currmetaentry = %metaentry;
12129: my $libresponseorder = &metadata($location,'responseorder');
12130: my $origfile;
12131: if ($libresponseorder ne '') {
12132: if ($#origfiletagids<0) {
12133: undef(%importedrespids);
12134: undef(%importedpartids);
12135: }
12136: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12137: if (@{$importedrespids{$importid}} > 0) {
12138: $importedresponses = 1;
12139: # We need to get the original file and the imported file to get the response order correct
12140: # Load and inspect original file
12141: if ($#origfiletagids<0) {
12142: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12143: $origfile=&getfile($origfilelocation);
12144: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12145: }
12146: }
12147: }
12148: # Do not overwrite contents of %metaentry hash for resource itself with
12149: # hash populated for imported library file
12150: %metaentry = %currmetaentry;
12151: undef(%currmetaentry);
1.1068 www 12152: if ($importmode eq 'problem') {
1.1069 www 12153: # Import as problem/response
1.1068 www 12154: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12155: } elsif ($importmode eq 'part') {
12156: # Import as part(s)
1.1069 www 12157: $importedparts=1;
12158: # We need to get the original file and the imported file to get the part order correct
12159: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12160: # Load and inspect original file if we didn't do that already
12161: if ($#origfiletagids<0) {
12162: undef(%importedrespids);
12163: undef(%importedpartids);
12164: if ($origfile eq '') {
12165: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12166: $origfile=&getfile($origfilelocation);
12167: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12168: }
1.1070 www 12169: }
12170:
1.1069 www 12171: # Load and inspect imported file
12172: my $impfile=&getfile($location);
12173: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12174: if ($#impfilepartids>=0) {
12175: # This problem had parts
1.1070 www 12176: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12177: } else {
12178: # Importing by turning a single problem into a problem part
12179: # It gets the import-tags ID as part-ID
12180: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12181: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12182: }
1.1068 www 12183: } else {
12184: # Normal import
12185: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12186: if (defined($token->[2]->{'id'})) {
12187: $unikey.='_'.$token->[2]->{'id'};
12188: }
1.1067 www 12189: }
12190:
1.339 albertel 12191: if ($depthcount<20) {
1.736 albertel 12192: my $metadata =
12193: &metadata($uri,'keys', $location,$unikey,
12194: $depthcount+1);
12195: foreach my $meta (split(',',$metadata)) {
12196: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12197: $metathesekeys{$meta}=1;
1.339 albertel 12198: }
1.1068 www 12199:
12200: }
1.1067 www 12201: } else {
12202: #
12203: # Not importing, some other kind of non-package, non-library start tag
12204: #
12205: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12206: if (defined($token->[2]->{'id'})) {
12207: $unikey.='_'.$token->[2]->{'id'};
12208: }
1.339 albertel 12209: if (defined($token->[2]->{'name'})) {
12210: $unikey.='_'.$token->[2]->{'name'};
12211: }
12212: $metathesekeys{$unikey}=1;
1.736 albertel 12213: foreach my $param (@{$token->[3]}) {
12214: $metaentry{':'.$unikey.'.'.$param} =
12215: $token->[2]->{$param};
1.339 albertel 12216: }
12217: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12218: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12219: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12220: # only ws inside the tag, and not in default, so use default
12221: # as value
1.599 albertel 12222: $metaentry{':'.$unikey}=$default;
1.908 albertel 12223: } elsif ( $internaltext =~ /\S/ ) {
12224: # something interesting inside the tag
12225: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12226: } else {
1.908 albertel 12227: # no interesting values, don't set a default
1.339 albertel 12228: }
1.172 www 12229: # end of not-a-package not-a-library import
1.339 albertel 12230: }
1.172 www 12231: # end of not-a-package start tag
1.339 albertel 12232: }
1.172 www 12233: # the next is the end of "start tag"
1.339 albertel 12234: }
12235: }
1.483 albertel 12236: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12237: $extension = lc($extension);
12238: if ($extension eq 'htm') { $extension='html'; }
12239:
1.737 albertel 12240: foreach my $key (keys(%packagetab)) {
1.483 albertel 12241: #no specific packages #how's our extension
12242: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12243: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12244: \%metathesekeys);
12245: }
1.883 albertel 12246:
12247: if (!exists($metaentry{':packages'})
12248: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12249: foreach my $key (keys(%packagetab)) {
1.483 albertel 12250: #no specific packages well let's get default then
12251: if ($key!~/^default&/) { next; }
1.488 albertel 12252: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12253: \%metathesekeys);
12254: }
12255: }
1.338 www 12256: # are there custom rights to evaluate
1.599 albertel 12257: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12258:
1.338 www 12259: #
12260: # Importing a rights file here
1.339 albertel 12261: #
12262: unless ($depthcount) {
1.599 albertel 12263: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12264: my $dir=$filename;
12265: $dir=~s|[^/]*$||;
12266: $location=&filelocation($dir,$location);
1.736 albertel 12267: my $rights_metadata =
12268: &metadata($uri,'keys',$location,'_rights',
12269: $depthcount+1);
12270: foreach my $rights (split(',',$rights_metadata)) {
12271: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12272: $metathesekeys{$rights}=1;
1.339 albertel 12273: }
12274: }
12275: }
1.737 albertel 12276: # uniqifiy package listing
12277: my %seen;
12278: my @uniq_packages =
12279: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12280: $metaentry{':packages'} = join(',',@uniq_packages);
12281:
1.1172.2.99 raeburn 12282: if (($importedresponses) || ($importedparts)) {
12283: if ($importedparts) {
1.1070 www 12284: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12285: $metaentry{':partorder'}='';
12286: $metathesekeys{'partorder'}=1;
12287: }
12288: if ($importedresponses) {
12289: # We had imported responses and need to rebuild responseorder
12290: $metaentry{':responseorder'}='';
12291: $metathesekeys{'responseorder'}=1;
12292: }
12293: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12294: my $origid = $origfiletagids[$index+1];
12295: if ($origfiletagids[$index] eq 'part') {
12296: # Original part, part of the problem
12297: if ($importedparts) {
12298: $metaentry{':partorder'}.=','.$origid;
12299: }
12300: } elsif ($origfiletagids[$index] eq 'import') {
12301: if ($importedparts) {
12302: # We have imported parts at this position
12303: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12304: }
12305: if ($importedresponses) {
12306: # We have imported responses at this position
12307: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12308: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12309: }
12310: }
12311: } else {
12312: # Original response item, part of the problem
12313: if ($importedresponses) {
12314: $metaentry{':responseorder'}.=','.$origid;
12315: }
12316: }
12317: }
12318: if ($importedparts) {
12319: $metaentry{':partorder'}=~s/^\,//;
12320: }
12321: if ($importedresponses) {
12322: $metaentry{':responseorder'}=~s/^\,//;
12323: }
1.1070 www 12324: }
12325:
1.737 albertel 12326: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12327: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12328: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12329: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12330: # this is the end of "was not already recently cached
1.71 www 12331: }
1.599 albertel 12332: return $metaentry{':'.$what};
1.261 albertel 12333: }
12334:
1.488 albertel 12335: sub metadata_create_package_def {
1.483 albertel 12336: my ($uri,$key,$package,$metathesekeys)=@_;
12337: my ($pack,$name,$subp)=split(/\&/,$key);
12338: if ($subp eq 'default') { next; }
12339:
1.599 albertel 12340: if (defined($metaentry{':packages'})) {
12341: $metaentry{':packages'}.=','.$package;
1.483 albertel 12342: } else {
1.599 albertel 12343: $metaentry{':packages'}=$package;
1.483 albertel 12344: }
12345: my $value=$packagetab{$key};
12346: my $unikey;
12347: $unikey='parameter_0_'.$name;
1.599 albertel 12348: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12349: $$metathesekeys{$unikey}=1;
1.599 albertel 12350: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12351: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12352: }
1.599 albertel 12353: if (defined($metaentry{':'.$unikey.'.default'})) {
12354: $metaentry{':'.$unikey}=
12355: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12356: }
12357: }
12358:
1.261 albertel 12359: sub metadata_generate_part0 {
12360: my ($metadata,$metacache,$uri) = @_;
12361: my %allnames;
1.737 albertel 12362: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12363: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12364: my $part=$$metacache{':'.$metakey.'.part'};
12365: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12366: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12367: $allnames{$name}=$part;
12368: }
12369: }
12370: }
12371: foreach my $name (keys(%allnames)) {
12372: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12373: my $key=":parameter_0_$name";
1.261 albertel 12374: $$metacache{"$key.part"}='0';
12375: $$metacache{"$key.name"}=$name;
1.428 albertel 12376: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12377: $allnames{$name}.'_'.$name.
12378: '.type'};
1.428 albertel 12379: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12380: '.display'};
1.644 www 12381: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12382: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12383: $$metacache{"$key.display"}=$olddis;
12384: }
1.71 www 12385: }
12386:
1.764 albertel 12387: # ------------------------------------------------------ Devalidate title cache
12388:
12389: sub devalidate_title_cache {
12390: my ($url)=@_;
12391: if (!$env{'request.course.id'}) { return; }
12392: my $symb=&symbread($url);
12393: if (!$symb) { return; }
12394: my $key=$env{'request.course.id'}."\0".$symb;
12395: &devalidate_cache_new('title',$key);
12396: }
12397:
1.1014 droeschl 12398: # ------------------------------------------------- Get the title of a course
12399:
12400: sub current_course_title {
12401: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12402: }
1.301 www 12403: # ------------------------------------------------- Get the title of a resource
12404:
12405: sub gettitle {
12406: my $urlsymb=shift;
12407: my $symb=&symbread($urlsymb);
1.534 albertel 12408: if ($symb) {
1.620 albertel 12409: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12410: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12411: if (defined($cached)) {
12412: return $result;
12413: }
1.534 albertel 12414: my ($map,$resid,$url)=&decode_symb($symb);
12415: my $title='';
1.907 albertel 12416: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12417: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12418: } else {
12419: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12420: &GDBM_READER(),0640)) {
12421: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12422: $title=$bighash{'title_'.$mapid.'.'.$resid};
12423: untie(%bighash);
12424: }
1.534 albertel 12425: }
12426: $title=~s/\&colon\;/\:/gs;
12427: if ($title) {
1.1159 www 12428: # Remember both $symb and $title for dynamic metadata
12429: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12430: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12431: # Cache this title and then return it
1.599 albertel 12432: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12433: }
12434: $urlsymb=$url;
12435: }
12436: my $title=&metadata($urlsymb,'title');
12437: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12438: return $title;
1.301 www 12439: }
1.613 albertel 12440:
1.614 albertel 12441: sub get_slot {
12442: my ($which,$cnum,$cdom)=@_;
12443: if (!$cnum || !$cdom) {
1.790 albertel 12444: (undef,my $courseid)=&whichuser();
1.620 albertel 12445: $cdom=$env{'course.'.$courseid.'.domain'};
12446: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12447: }
1.703 albertel 12448: my $key=join("\0",'slots',$cdom,$cnum,$which);
12449: my %slotinfo;
12450: if (exists($remembered{$key})) {
12451: $slotinfo{$which} = $remembered{$key};
12452: } else {
12453: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12454: &Apache::lonhomework::showhash(%slotinfo);
12455: my ($tmp)=keys(%slotinfo);
12456: if ($tmp=~/^error:/) { return (); }
12457: $remembered{$key} = $slotinfo{$which};
12458: }
1.616 albertel 12459: if (ref($slotinfo{$which}) eq 'HASH') {
12460: return %{$slotinfo{$which}};
12461: }
12462: return $slotinfo{$which};
1.614 albertel 12463: }
1.1150 raeburn 12464:
12465: sub get_reservable_slots {
12466: my ($cnum,$cdom,$uname,$udom) = @_;
12467: my $now = time;
12468: my $reservable_info;
12469: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12470: if (exists($remembered{$key})) {
12471: $reservable_info = $remembered{$key};
12472: } else {
12473: my %resv;
12474: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12475: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12476: $reservable_info = \%resv;
12477: $remembered{$key} = $reservable_info;
12478: }
12479: return $reservable_info;
12480: }
12481:
12482: sub get_course_slots {
12483: my ($cnum,$cdom) = @_;
12484: my $hashid=$cnum.':'.$cdom;
12485: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12486: if (defined($cached)) {
12487: if (ref($result) eq 'HASH') {
12488: return %{$result};
12489: }
12490: } else {
12491: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12492: my ($tmp) = keys(%slots);
12493: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12494: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12495: return %slots;
12496: }
12497: }
12498: return;
12499: }
12500:
12501: sub devalidate_slots_cache {
12502: my ($cnum,$cdom)=@_;
12503: my $hashid=$cnum.':'.$cdom;
12504: &devalidate_cache_new('allslots',$hashid);
12505: }
12506:
1.1172.2.8 raeburn 12507: sub get_coursechange {
12508: my ($cdom,$cnum) = @_;
12509: if ($cdom eq '' || $cnum eq '') {
12510: return unless ($env{'request.course.id'});
12511: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12512: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12513: }
12514: my $hashid=$cdom.'_'.$cnum;
12515: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12516: if ((defined($cached)) && ($change ne '')) {
12517: return $change;
12518: } else {
12519: my %crshash;
12520: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12521: if ($crshash{'internal.contentchange'} eq '') {
12522: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12523: if ($change eq '') {
12524: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12525: $change = $crshash{'internal.created'};
12526: }
12527: } else {
12528: $change = $crshash{'internal.contentchange'};
12529: }
12530: my $cachetime = 600;
12531: &do_cache_new('crschange',$hashid,$change,$cachetime);
12532: }
12533: return $change;
12534: }
12535:
12536: sub devalidate_coursechange_cache {
12537: my ($cnum,$cdom)=@_;
12538: my $hashid=$cnum.':'.$cdom;
12539: &devalidate_cache_new('crschange',$hashid);
12540: }
12541:
1.31 www 12542: # ------------------------------------------------- Update symbolic store links
12543:
12544: sub symblist {
12545: my ($mapname,%newhash)=@_;
1.438 www 12546: $mapname=&deversion(&declutter($mapname));
1.31 www 12547: my %hash;
1.620 albertel 12548: if (($env{'request.course.fn'}) && (%newhash)) {
12549: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12550: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12551: foreach my $url (keys(%newhash)) {
1.711 albertel 12552: next if ($url eq 'last_known'
12553: && $env{'form.no_update_last_known'});
12554: $hash{declutter($url)}=&encode_symb($mapname,
12555: $newhash{$url}->[1],
12556: $newhash{$url}->[0]);
1.191 harris41 12557: }
1.31 www 12558: if (untie(%hash)) {
12559: return 'ok';
12560: }
12561: }
12562: }
12563: return 'error';
1.212 www 12564: }
12565:
12566: # --------------------------------------------------------------- Verify a symb
12567:
12568: sub symbverify {
1.1172.2.11 raeburn 12569: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12570: my $thisfn=$thisurl;
1.439 www 12571: $thisfn=&declutter($thisfn);
1.215 www 12572: # direct jump to resource in page or to a sequence - will construct own symbs
12573: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12574: # check URL part
1.409 www 12575: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12576:
1.431 www 12577: unless ($url eq $thisfn) { return 0; }
1.213 www 12578:
1.216 www 12579: $symb=&symbclean($symb);
1.510 www 12580: $thisurl=&deversion($thisurl);
1.439 www 12581: $thisfn=&deversion($thisfn);
1.213 www 12582:
12583: my %bighash;
12584: my $okay=0;
1.431 www 12585:
1.620 albertel 12586: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12587: &GDBM_READER(),0640)) {
1.1032 raeburn 12588: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12589: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12590: if ($map =~ m{^uploaded/.+\.page$}) {
12591: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12592: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12593: }
12594: }
12595: my $ids;
1.1172.2.122 raeburn 12596: if ($map =~ m{^uploaded/.+\.page$}) {
12597: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12598: } else {
12599: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12600: }
1.1102 raeburn 12601: unless ($ids) {
1.1172.2.13 raeburn 12602: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12603: $ids=$bighash{$idkey};
1.216 www 12604: }
12605: if ($ids) {
12606: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12607: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12608: $symb =~ s/\?.+$//;
12609: }
1.800 albertel 12610: foreach my $id (split(/\,/,$ids)) {
12611: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12612: if (
12613: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12614: eq $symb) {
1.1172.2.11 raeburn 12615: if (ref($encstate)) {
12616: $$encstate = $bighash{'encrypted_'.$id};
12617: }
1.1172.2.13 raeburn 12618: if (($env{'request.role.adv'}) ||
12619: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12620: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12621: $okay=1;
12622: last;
12623: }
12624: }
12625: }
1.216 www 12626: }
1.213 www 12627: untie(%bighash);
12628: }
12629: return $okay;
1.31 www 12630: }
12631:
1.210 www 12632: # --------------------------------------------------------------- Clean-up symb
12633:
12634: sub symbclean {
12635: my $symb=shift;
1.568 albertel 12636: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12637: # remove version from map
12638: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12639:
1.210 www 12640: # remove version from URL
12641: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12642:
1.507 www 12643: # remove wrapper
12644:
1.510 www 12645: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12646: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12647: return $symb;
1.409 www 12648: }
12649:
12650: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12651:
12652: sub encode_symb {
12653: my ($map,$resid,$url)=@_;
12654: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12655: }
1.409 www 12656:
12657: sub decode_symb {
1.568 albertel 12658: my $symb=shift;
12659: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12660: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12661: return (&fixversion($map),$resid,&fixversion($url));
12662: }
12663:
12664: sub fixversion {
12665: my $fn=shift;
1.609 banghart 12666: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12667: my %bighash;
12668: my $uri=&clutter($fn);
1.620 albertel 12669: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12670: # is this cached?
1.599 albertel 12671: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12672: if (defined($cached)) { return $result; }
12673: # unfortunately not cached, or expired
1.620 albertel 12674: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12675: &GDBM_READER(),0640)) {
12676: if ($bighash{'version_'.$uri}) {
12677: my $version=$bighash{'version_'.$uri};
1.444 www 12678: unless (($version eq 'mostrecent') ||
12679: ($version==&getversion($uri))) {
1.440 www 12680: $uri=~s/\.(\w+)$/\.$version\.$1/;
12681: }
12682: }
12683: untie %bighash;
1.413 www 12684: }
1.599 albertel 12685: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12686: }
12687:
12688: sub deversion {
12689: my $url=shift;
12690: $url=~s/\.\d+\.(\w+)$/\.$1/;
12691: return $url;
1.210 www 12692: }
12693:
1.31 www 12694: # ------------------------------------------------------ Return symb list entry
12695:
12696: sub symbread {
1.1172.2.126 raeburn 12697: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12698: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12699: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12700: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12701: unless (ref($possibles) eq 'HASH') {
12702: if ($ignorecachednull) {
12703: return $env{$cache_str} unless ($env{$cache_str} eq '');
12704: } else {
12705: return $env{$cache_str};
12706: }
1.1172.2.66 raeburn 12707: }
12708: }
1.242 www 12709: # no filename provided? try from environment
1.1172.2.54 raeburn 12710: unless ($thisfn) {
1.620 albertel 12711: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12712: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12713: }
12714: $thisfn=$env{'request.filename'};
1.44 www 12715: }
1.569 albertel 12716: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12717: # is that filename actually a symb? Verify, clean, and return
12718: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12719: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12720: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12721: }
1.242 www 12722: }
1.44 www 12723: $thisfn=declutter($thisfn);
1.31 www 12724: my %hash;
1.37 www 12725: my %bighash;
12726: my $syval='';
1.620 albertel 12727: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128 raeburn 12728: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12729: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12730: &GDBM_READER(),0640)) {
1.1172.2.150! raeburn 12731: $syval=$hash{$thisfn};
1.1172.2.126 raeburn 12732: untie(%hash);
12733: }
1.1172.2.128 raeburn 12734: if ($syval && $checkforblock) {
12735: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12736: if (@blockers) {
12737: $syval='';
12738: }
12739: }
1.37 www 12740: }
12741: # ---------------------------------------------------------- There was an entry
12742: if ($syval) {
1.601 albertel 12743: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12744: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12745: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12746: #return $env{$cache_str}='';
1.601 albertel 12747: #}
12748: #$syval.=$1;
12749: #}
1.37 www 12750: } else {
12751: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12752: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12753: &GDBM_READER(),0640)) {
1.37 www 12754: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12755: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12756: unless ($ids) {
12757: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12758: }
12759: unless ($ids) {
12760: # alias?
12761: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12762: }
1.37 www 12763: if ($ids) {
12764: # ------------------------------------------------------------------- Has ID(s)
12765: my @possibilities=split(/\,/,$ids);
1.39 www 12766: if ($#possibilities==0) {
12767: # ----------------------------------------------- There is only one possibility
1.37 www 12768: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12769: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12770: $resid,$thisfn);
1.1172.2.66 raeburn 12771: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12772: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12773: $possibles->{$syval} = 1;
12774: }
1.1172.2.66 raeburn 12775: }
12776: if ($checkforblock) {
1.1172.2.126 raeburn 12777: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12778: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12779: if (@blockers) {
12780: $syval = '';
12781: untie(%bighash);
12782: return $env{$cache_str}='';
12783: }
1.1172.2.66 raeburn 12784: }
12785: }
12786: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12787: # ------------------------------------------ There is more than one possibility
12788: my $realpossible=0;
1.800 albertel 12789: foreach my $id (@possibilities) {
12790: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12791: my $canaccess;
12792: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12793: $canaccess = 1;
12794: } else {
12795: $canaccess = &allowed('bre',$file);
12796: }
12797: if ($canaccess) {
12798: my ($mapid,$resid)=split(/\./,$id);
12799: if ($bighash{'map_type_'.$mapid} ne 'page') {
12800: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12801: $resid,$thisfn);
1.1172.2.126 raeburn 12802: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12803: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12804: if ($checkforblock) {
1.1172.2.127 raeburn 12805: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12806: if (@blockers > 0) {
12807: $syval = '';
12808: } else {
1.1172.2.66 raeburn 12809: $syval = $poss_syval;
12810: $realpossible++;
12811: }
12812: } else {
12813: $syval = $poss_syval;
12814: $realpossible++;
12815: }
1.1172.2.126 raeburn 12816: if ($syval) {
12817: if (ref($possibles) eq 'HASH') {
12818: $possibles->{$syval} = 1;
12819: }
12820: }
1.1172.2.66 raeburn 12821: }
1.39 www 12822: }
1.191 harris41 12823: }
1.39 www 12824: if ($realpossible!=1) { $syval=''; }
1.249 www 12825: } else {
12826: $syval='';
1.37 www 12827: }
12828: }
1.1172.2.66 raeburn 12829: untie(%bighash);
1.481 raeburn 12830: }
1.31 www 12831: }
1.62 www 12832: if ($syval) {
1.1172.2.128 raeburn 12833: return $env{$cache_str}=$syval;
1.62 www 12834: }
1.31 www 12835: }
1.949 raeburn 12836: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12837: return $env{$cache_str}='';
1.31 www 12838: }
12839:
12840: # ---------------------------------------------------------- Return random seed
12841:
1.32 www 12842: sub numval {
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;
1.564 albertel 12851: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12852: return int($txt);
1.368 albertel 12853: }
12854:
1.484 albertel 12855: sub numval2 {
12856: my $txt=shift;
12857: $txt=~tr/A-J/0-9/;
12858: $txt=~tr/a-j/0-9/;
12859: $txt=~tr/K-T/0-9/;
12860: $txt=~tr/k-t/0-9/;
12861: $txt=~tr/U-Z/0-5/;
12862: $txt=~tr/u-z/0-5/;
12863: $txt=~s/\D//g;
12864: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12865: my $total;
12866: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12867: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12868: return int($total);
12869: }
12870:
1.575 albertel 12871: sub numval3 {
12872: use integer;
12873: my $txt=shift;
12874: $txt=~tr/A-J/0-9/;
12875: $txt=~tr/a-j/0-9/;
12876: $txt=~tr/K-T/0-9/;
12877: $txt=~tr/k-t/0-9/;
12878: $txt=~tr/U-Z/0-5/;
12879: $txt=~tr/u-z/0-5/;
12880: $txt=~s/\D//g;
12881: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12882: my $total;
12883: foreach my $val (@txts) { $total+=$val; }
12884: if ($_64bit) { $total=(($total<<32)>>32); }
12885: return $total;
12886: }
12887:
1.675 albertel 12888: sub digest {
12889: my ($data)=@_;
12890: my $digest=&Digest::MD5::md5($data);
12891: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12892: my ($e,$f);
12893: {
12894: use integer;
12895: $e=($a+$b);
12896: $f=($c+$d);
12897: if ($_64bit) {
12898: $e=(($e<<32)>>32);
12899: $f=(($f<<32)>>32);
12900: }
12901: }
12902: if (wantarray) {
12903: return ($e,$f);
12904: } else {
12905: my $g;
12906: {
12907: use integer;
12908: $g=($e+$f);
12909: if ($_64bit) {
12910: $g=(($g<<32)>>32);
12911: }
12912: }
12913: return $g;
12914: }
12915: }
12916:
1.368 albertel 12917: sub latest_rnd_algorithm_id {
1.675 albertel 12918: return '64bit5';
1.366 albertel 12919: }
1.32 www 12920:
1.503 albertel 12921: sub get_rand_alg {
12922: my ($courseid)=@_;
1.790 albertel 12923: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12924: if ($courseid) {
1.620 albertel 12925: return $env{"course.$courseid.rndseed"};
1.503 albertel 12926: }
12927: return &latest_rnd_algorithm_id();
12928: }
12929:
1.562 albertel 12930: sub validCODE {
12931: my ($CODE)=@_;
12932: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12933: return 0;
12934: }
12935:
1.491 albertel 12936: sub getCODE {
1.620 albertel 12937: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12938: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12939: defined($Apache::lonhomework::parsing_a_task) ) &&
12940: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12941: return $Apache::lonhomework::history{'resource.CODE'};
12942: }
12943: return undef;
12944: }
1.1133 foxr 12945: #
12946: # Determines the random seed for a specific context:
12947: #
12948: # parameters:
12949: # symb - in course context the symb for the seed.
12950: # course_id - The course id of the form domain_coursenum.
12951: # domain - Domain for the user.
12952: # course - Course for the user.
12953: # cenv - environment of the course.
12954: #
12955: # NOTE:
12956: # All parameters are picked out of the environment if missing
12957: # or not defined.
12958: # If a symb cannot be determined the current time is used instead.
12959: #
12960: # For a given well defined symb, courside, domain, username,
12961: # and course environment, the seed is reproducible.
12962: #
1.31 www 12963: sub rndseed {
1.1133 foxr 12964: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12965: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12966: if (!defined($symb)) {
1.366 albertel 12967: unless ($symb=$wsymb) { return time; }
12968: }
1.1146 foxr 12969: if (!defined $courseid) {
12970: $courseid=$wcourseid;
12971: }
12972: if (!defined $domain) { $domain=$wdomain; }
12973: if (!defined $username) { $username=$wusername }
1.1133 foxr 12974:
12975: my $which;
12976: if (defined($cenv->{'rndseed'})) {
12977: $which = $cenv->{'rndseed'};
12978: } else {
12979: $which =&get_rand_alg($courseid);
12980: }
1.491 albertel 12981: if (defined(&getCODE())) {
1.675 albertel 12982: if ($which eq '64bit5') {
12983: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12984: } elsif ($which eq '64bit4') {
1.575 albertel 12985: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12986: } else {
12987: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12988: }
1.675 albertel 12989: } elsif ($which eq '64bit5') {
12990: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12991: } elsif ($which eq '64bit4') {
12992: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12993: } elsif ($which eq '64bit3') {
12994: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12995: } elsif ($which eq '64bit2') {
12996: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12997: } elsif ($which eq '64bit') {
12998: return &rndseed_64bit($symb,$courseid,$domain,$username);
12999: }
13000: return &rndseed_32bit($symb,$courseid,$domain,$username);
13001: }
13002:
13003: sub rndseed_32bit {
13004: my ($symb,$courseid,$domain,$username)=@_;
13005: {
13006: use integer;
13007: my $symbchck=unpack("%32C*",$symb) << 27;
13008: my $symbseed=numval($symb) << 22;
13009: my $namechck=unpack("%32C*",$username) << 17;
13010: my $nameseed=numval($username) << 12;
13011: my $domainseed=unpack("%32C*",$domain) << 7;
13012: my $courseseed=unpack("%32C*",$courseid);
13013: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13014: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13015: #&logthis("rndseed :$num:$symb");
1.564 albertel 13016: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13017: return $num;
13018: }
13019: }
13020:
13021: sub rndseed_64bit {
13022: my ($symb,$courseid,$domain,$username)=@_;
13023: {
13024: use integer;
13025: my $symbchck=unpack("%32S*",$symb) << 21;
13026: my $symbseed=numval($symb) << 10;
13027: my $namechck=unpack("%32S*",$username);
13028:
13029: my $nameseed=numval($username) << 21;
13030: my $domainseed=unpack("%32S*",$domain) << 10;
13031: my $courseseed=unpack("%32S*",$courseid);
13032:
13033: my $num1=$symbchck+$symbseed+$namechck;
13034: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13035: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13036: #&logthis("rndseed :$num:$symb");
1.564 albertel 13037: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13038: return "$num1,$num2";
1.155 albertel 13039: }
1.366 albertel 13040: }
13041:
1.443 albertel 13042: sub rndseed_64bit2 {
13043: my ($symb,$courseid,$domain,$username)=@_;
13044: {
13045: use integer;
13046: # strings need to be an even # of cahracters long, it it is odd the
13047: # last characters gets thrown away
13048: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13049: my $symbseed=numval($symb) << 10;
13050: my $namechck=unpack("%32S*",$username.' ');
13051:
13052: my $nameseed=numval($username) << 21;
1.501 albertel 13053: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13054: my $courseseed=unpack("%32S*",$courseid.' ');
13055:
13056: my $num1=$symbchck+$symbseed+$namechck;
13057: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13058: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13059: #&logthis("rndseed :$num:$symb");
1.803 albertel 13060: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13061: return "$num1,$num2";
13062: }
13063: }
13064:
13065: sub rndseed_64bit3 {
13066: my ($symb,$courseid,$domain,$username)=@_;
13067: {
13068: use integer;
13069: # strings need to be an even # of cahracters long, it it is odd the
13070: # last characters gets thrown away
13071: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13072: my $symbseed=numval2($symb) << 10;
13073: my $namechck=unpack("%32S*",$username.' ');
13074:
13075: my $nameseed=numval2($username) << 21;
1.443 albertel 13076: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13077: my $courseseed=unpack("%32S*",$courseid.' ');
13078:
13079: my $num1=$symbchck+$symbseed+$namechck;
13080: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13081: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13082: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13083: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13084:
1.503 albertel 13085: return "$num1:$num2";
1.443 albertel 13086: }
13087: }
13088:
1.575 albertel 13089: sub rndseed_64bit4 {
13090: my ($symb,$courseid,$domain,$username)=@_;
13091: {
13092: use integer;
13093: # strings need to be an even # of cahracters long, it it is odd the
13094: # last characters gets thrown away
13095: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13096: my $symbseed=numval3($symb) << 10;
13097: my $namechck=unpack("%32S*",$username.' ');
13098:
13099: my $nameseed=numval3($username) << 21;
13100: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13101: my $courseseed=unpack("%32S*",$courseid.' ');
13102:
13103: my $num1=$symbchck+$symbseed+$namechck;
13104: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13105: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13106: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13107: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13108:
1.575 albertel 13109: return "$num1:$num2";
13110: }
13111: }
13112:
1.675 albertel 13113: sub rndseed_64bit5 {
13114: my ($symb,$courseid,$domain,$username)=@_;
13115: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13116: return "$num1:$num2";
13117: }
13118:
1.366 albertel 13119: sub rndseed_CODE_64bit {
13120: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13121: {
1.366 albertel 13122: use integer;
1.443 albertel 13123: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13124: my $symbseed=numval2($symb);
1.491 albertel 13125: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13126: my $CODEseed=numval(&getCODE());
1.443 albertel 13127: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13128: my $num1=$symbseed+$CODEchck;
13129: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13130: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13131: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13132: if ($_64bit) { $num1=(($num1<<32)>>32); }
13133: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13134: return "$num1:$num2";
1.366 albertel 13135: }
13136: }
13137:
1.575 albertel 13138: sub rndseed_CODE_64bit4 {
13139: my ($symb,$courseid,$domain,$username)=@_;
13140: {
13141: use integer;
13142: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13143: my $symbseed=numval3($symb);
13144: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13145: my $CODEseed=numval3(&getCODE());
13146: my $courseseed=unpack("%32S*",$courseid.' ');
13147: my $num1=$symbseed+$CODEchck;
13148: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13149: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13150: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13151: if ($_64bit) { $num1=(($num1<<32)>>32); }
13152: if ($_64bit) { $num2=(($num2<<32)>>32); }
13153: return "$num1:$num2";
13154: }
13155: }
13156:
1.675 albertel 13157: sub rndseed_CODE_64bit5 {
13158: my ($symb,$courseid,$domain,$username)=@_;
13159: my $code = &getCODE();
13160: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13161: return "$num1:$num2";
13162: }
13163:
1.366 albertel 13164: sub setup_random_from_rndseed {
13165: my ($rndseed)=@_;
1.503 albertel 13166: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13167: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13168: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13169: &Math::Random::random_set_seed_from_phrase($rndseed);
13170: } else {
13171: &Math::Random::random_set_seed($num1,$num2);
13172: }
1.366 albertel 13173: } else {
13174: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13175: }
1.36 albertel 13176: }
13177:
1.474 albertel 13178: sub latest_receipt_algorithm_id {
1.835 albertel 13179: return 'receipt3';
1.474 albertel 13180: }
13181:
1.480 www 13182: sub recunique {
13183: my $fucourseid=shift;
13184: my $unique;
1.835 albertel 13185: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13186: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13187: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13188: } else {
13189: $unique=$perlvar{'lonReceipt'};
13190: }
13191: return unpack("%32C*",$unique);
13192: }
13193:
13194: sub recprefix {
13195: my $fucourseid=shift;
13196: my $prefix;
1.835 albertel 13197: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13198: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13199: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13200: } else {
13201: $prefix=$perlvar{'lonHostID'};
13202: }
13203: return unpack("%32C*",$prefix);
13204: }
13205:
1.76 www 13206: sub ireceipt {
1.474 albertel 13207: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13208:
13209: my $return =&recprefix($fucourseid).'-';
13210:
13211: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13212: $env{'request.state'} eq 'construct') {
13213: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13214: return $return;
13215: }
13216:
1.76 www 13217: my $cuname=unpack("%32C*",$funame);
13218: my $cudom=unpack("%32C*",$fudom);
13219: my $cucourseid=unpack("%32C*",$fucourseid);
13220: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13221: my $cunique=&recunique($fucourseid);
1.474 albertel 13222: my $cpart=unpack("%32S*",$part);
1.835 albertel 13223: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13224:
1.790 albertel 13225: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13226:
13227: $return.= ($cunique%$cuname+
13228: $cunique%$cudom+
13229: $cusymb%$cuname+
13230: $cusymb%$cudom+
13231: $cucourseid%$cuname+
13232: $cucourseid%$cudom+
13233: $cpart%$cuname+
13234: $cpart%$cudom);
13235: } else {
13236: $return.= ($cunique%$cuname+
13237: $cunique%$cudom+
13238: $cusymb%$cuname+
13239: $cusymb%$cudom+
13240: $cucourseid%$cuname+
13241: $cucourseid%$cudom);
13242: }
13243: return $return;
1.76 www 13244: }
13245:
13246: sub receipt {
1.474 albertel 13247: my ($part)=@_;
1.790 albertel 13248: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13249: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13250: }
1.260 ng 13251:
1.790 albertel 13252: sub whichuser {
13253: my ($passedsymb)=@_;
13254: my ($symb,$courseid,$domain,$name,$publicuser);
13255: if (defined($env{'form.grade_symb'})) {
13256: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13257: my $allowed=&allowed('vgr',$tmp_courseid);
13258: if (!$allowed &&
13259: exists($env{'request.course.sec'}) &&
13260: $env{'request.course.sec'} !~ /^\s*$/) {
13261: $allowed=&allowed('vgr',$tmp_courseid.
13262: '/'.$env{'request.course.sec'});
13263: }
13264: if ($allowed) {
13265: ($symb)=&get_env_multiple('form.grade_symb');
13266: $courseid=$tmp_courseid;
13267: ($domain)=&get_env_multiple('form.grade_domain');
13268: ($name)=&get_env_multiple('form.grade_username');
13269: return ($symb,$courseid,$domain,$name,$publicuser);
13270: }
13271: }
13272: if (!$passedsymb) {
13273: $symb=&symbread();
13274: } else {
13275: $symb=$passedsymb;
13276: }
13277: $courseid=$env{'request.course.id'};
13278: $domain=$env{'user.domain'};
13279: $name=$env{'user.name'};
13280: if ($name eq 'public' && $domain eq 'public') {
13281: if (!defined($env{'form.username'})) {
13282: $env{'form.username'}.=time.rand(10000000);
13283: }
13284: $name.=$env{'form.username'};
13285: }
13286: return ($symb,$courseid,$domain,$name,$publicuser);
13287:
13288: }
13289:
1.36 albertel 13290: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13291: # returns either the contents of the file or
13292: # -1 if the file doesn't exist
1.481 raeburn 13293: #
13294: # if the target is a file that was uploaded via DOCS,
13295: # a check will be made to see if a current copy exists on the local server,
13296: # if it does this will be served, otherwise a copy will be retrieved from
13297: # the home server for the course and stored in /home/httpd/html/userfiles on
13298: # the local server.
1.472 albertel 13299:
1.36 albertel 13300: sub getfile {
1.538 albertel 13301: my ($file) = @_;
1.609 banghart 13302: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13303: &repcopy($file);
13304: return &readfile($file);
13305: }
13306:
13307: sub repcopy_userfile {
13308: my ($file)=@_;
1.1142 raeburn 13309: my $londocroot = $perlvar{'lonDocRoot'};
13310: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13311: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13312: my ($cdom,$cnum,$filename) =
1.811 albertel 13313: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13314: my $uri="/uploaded/$cdom/$cnum/$filename";
13315: if (-e "$file") {
1.828 www 13316: # we already have a local copy, check it out
1.538 albertel 13317: my @fileinfo = stat($file);
1.828 www 13318: my $rtncode;
13319: my $info;
1.538 albertel 13320: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13321: if ($lwpresp ne 'ok') {
1.828 www 13322: # there is no such file anymore, even though we had a local copy
1.482 albertel 13323: if ($rtncode eq '404') {
1.538 albertel 13324: unlink($file);
1.482 albertel 13325: }
13326: return -1;
13327: }
13328: if ($info < $fileinfo[9]) {
1.828 www 13329: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13330: return 'ok';
1.828 www 13331: } else {
13332: # the file is outdated, get rid of it
13333: unlink($file);
1.482 albertel 13334: }
1.828 www 13335: }
13336: # one way or the other, at this point, we don't have the file
13337: # construct the correct path for the file
13338: my @parts = ($cdom,$cnum);
13339: if ($filename =~ m|^(.+)/[^/]+$|) {
13340: push @parts, split(/\//,$1);
13341: }
13342: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13343: foreach my $part (@parts) {
13344: $path .= '/'.$part;
13345: if (!-e $path) {
13346: mkdir($path,0770);
1.482 albertel 13347: }
13348: }
1.828 www 13349: # now the path exists for sure
13350: # get a user agent
13351: my $ua=new LWP::UserAgent;
13352: my $transferfile=$file.'.in.transfer';
13353: # FIXME: this should flock
13354: if (-e $transferfile) { return 'ok'; }
13355: my $request;
13356: $uri=~s/^\///;
1.980 raeburn 13357: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13358: my $hostname = &hostname($homeserver);
1.980 raeburn 13359: my $protocol = $protocol{$homeserver};
13360: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13361: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13362: my $response=$ua->request($request,$transferfile);
13363: # did it work?
13364: if ($response->is_error()) {
13365: unlink($transferfile);
13366: &logthis("Userfile repcopy failed for $uri");
13367: return -1;
13368: }
13369: # worked, rename the transfer file
13370: rename($transferfile,$file);
1.607 raeburn 13371: return 'ok';
1.481 raeburn 13372: }
13373:
1.517 albertel 13374: sub tokenwrapper {
13375: my $uri=shift;
1.980 raeburn 13376: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13377: $uri=~s|^/||;
1.620 albertel 13378: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13379: my $token=$1;
1.552 albertel 13380: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13381: if ($udom && $uname && $file) {
13382: $file=~s|(\?\.*)*$||;
1.949 raeburn 13383: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13384: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13385: my $hostname = &hostname($homeserver);
1.980 raeburn 13386: my $protocol = $protocol{$homeserver};
13387: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13388: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13389: (($uri=~/\?/)?'&':'?').'token='.$token.
13390: '&tokenissued='.$perlvar{'lonHostID'};
13391: } else {
13392: return '/adm/notfound.html';
13393: }
13394: }
13395:
1.828 www 13396: # call with reqtype HEAD: get last modification time
13397: # call with reqtype GET: get the file contents
13398: # Do not call this with reqtype GET for large files! It loads everything into memory
13399: #
1.481 raeburn 13400: sub getuploaded {
13401: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13402: $uri=~s/^\///;
1.980 raeburn 13403: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13404: my $hostname = &hostname($homeserver);
1.980 raeburn 13405: my $protocol = $protocol{$homeserver};
13406: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13407: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13408: my $ua=new LWP::UserAgent;
13409: my $request=new HTTP::Request($reqtype,$uri);
13410: my $response=$ua->request($request);
13411: $$rtncode = $response->code;
1.482 albertel 13412: if (! $response->is_success()) {
13413: return 'failed';
13414: }
13415: if ($reqtype eq 'HEAD') {
1.486 www 13416: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13417: } elsif ($reqtype eq 'GET') {
13418: $$info = $response->content;
1.472 albertel 13419: }
1.482 albertel 13420: return 'ok';
1.36 albertel 13421: }
13422:
1.481 raeburn 13423: sub readfile {
13424: my $file = shift;
13425: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13426: my $fh;
1.1172.2.96 raeburn 13427: open($fh,"<",$file);
1.481 raeburn 13428: my $a='';
1.800 albertel 13429: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13430: return $a;
13431: }
13432:
1.36 albertel 13433: sub filelocation {
1.590 banghart 13434: my ($dir,$file) = @_;
13435: my $location;
13436: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13437:
13438: if ($file =~ m-^/adm/-) {
13439: $file=~s-^/adm/wrapper/-/-;
13440: $file=~s-^/adm/coursedocs/showdoc/-/-;
13441: }
1.882 albertel 13442:
1.1139 www 13443: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13444: $location = $file;
1.609 banghart 13445: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13446: my ($udom,$uname,$filename)=
1.811 albertel 13447: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13448: my $home=&homeserver($uname,$udom);
13449: my $is_me=0;
13450: my @ids=¤t_machine_ids();
13451: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13452: if ($is_me) {
1.1117 foxr 13453: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13454: } else {
13455: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13456: $udom.'/'.$uname.'/'.$filename;
13457: }
1.882 albertel 13458: } elsif ($file =~ m-^/adm/-) {
13459: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13460: } else {
13461: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13462: $file=~s:^/(res|priv)/:/:;
13463: my $space=$1;
1.590 banghart 13464: if ( !( $file =~ m:^/:) ) {
13465: $location = $dir. '/'.$file;
13466: } else {
1.1142 raeburn 13467: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13468: }
1.59 albertel 13469: }
1.590 banghart 13470: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13471: while ($location=~m{/\.\./}) {
13472: if ($location =~ m{/[^/]+/\.\./}) {
13473: $location=~ s{/[^/]+/\.\./}{/}g;
13474: } else {
13475: $location=~ s{/\.\./}{/}g;
13476: }
13477: } #remove dir/..
1.590 banghart 13478: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13479: return $location;
1.46 www 13480: }
1.36 albertel 13481:
1.46 www 13482: sub hreflocation {
13483: my ($dir,$file)=@_;
1.980 raeburn 13484: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13485: $file=filelocation($dir,$file);
1.700 albertel 13486: } elsif ($file=~m-^/adm/-) {
13487: $file=~s-^/adm/wrapper/-/-;
13488: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13489: }
13490: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13491: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13492: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13493: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13494: {/uploaded/$1/$2/}x;
1.46 www 13495: }
1.913 albertel 13496: if ($file=~ m{^/userfiles/}) {
13497: $file =~ s{^/userfiles/}{/uploaded/};
13498: }
1.462 albertel 13499: return $file;
1.465 albertel 13500: }
13501:
1.1139 www 13502:
13503:
13504:
13505:
1.465 albertel 13506: sub current_machine_domains {
1.853 albertel 13507: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13508: }
13509:
13510: sub machine_domains {
13511: my ($hostname) = @_;
1.465 albertel 13512: my @domains;
1.838 albertel 13513: my %hostname = &all_hostnames();
1.465 albertel 13514: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13515: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13516: if ($hostname eq $name) {
1.844 albertel 13517: push(@domains,&host_domain($id));
1.465 albertel 13518: }
13519: }
13520: return @domains;
13521: }
13522:
13523: sub current_machine_ids {
1.853 albertel 13524: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13525: }
13526:
13527: sub machine_ids {
13528: my ($hostname) = @_;
13529: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13530: my @ids;
1.888 albertel 13531: my %name_to_host = &all_names();
1.889 albertel 13532: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13533: return @{ $name_to_host{$hostname} };
13534: }
13535: return;
1.31 www 13536: }
13537:
1.824 raeburn 13538: sub additional_machine_domains {
13539: my @domains;
1.1172.2.142 raeburn 13540: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13541: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13542: while( my $line = <$fh>) {
13543: chomp($line);
13544: $line =~ s/\s//g;
13545: push(@domains,$line);
13546: }
13547: close($fh);
13548: }
1.824 raeburn 13549: }
13550: return @domains;
13551: }
13552:
13553: sub default_login_domain {
13554: my $domain = $perlvar{'lonDefDomain'};
13555: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13556: foreach my $posdom (¤t_machine_domains(),
13557: &additional_machine_domains()) {
13558: if (lc($posdom) eq lc($testdomain)) {
13559: $domain=$posdom;
13560: last;
13561: }
13562: }
13563: return $domain;
13564: }
13565:
1.1172.2.106 raeburn 13566: sub shared_institution {
1.1172.2.136 raeburn 13567: my ($dom,$lonhost) = @_;
13568: if ($lonhost eq '') {
13569: $lonhost = $perlvar{'lonHostID'};
13570: }
1.1172.2.106 raeburn 13571: my $same_intdom;
1.1172.2.136 raeburn 13572: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13573: if ($hostintdom ne '') {
13574: my %iphost = &get_iphost();
13575: my $primary_id = &domain($dom,'primary');
13576: my $primary_ip = &get_host_ip($primary_id);
13577: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13578: foreach my $id (@{$iphost{$primary_ip}}) {
13579: my $intdom = &internet_dom($id);
13580: if ($intdom eq $hostintdom) {
13581: $same_intdom = 1;
13582: last;
13583: }
13584: }
13585: }
13586: }
13587: return $same_intdom;
13588: }
13589:
1.1172.2.120 raeburn 13590: sub uses_sts {
13591: my ($ignore_cache) = @_;
13592: my $lonhost = $perlvar{'lonHostID'};
13593: my $hostname = &hostname($lonhost);
13594: my $sts_on;
13595: if ($protocol{$lonhost} eq 'https') {
13596: my $cachetime = 12*3600;
13597: if (!$ignore_cache) {
13598: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13599: if (defined($cached)) {
13600: return $sts_on;
13601: }
13602: }
1.1172.2.121 raeburn 13603: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13604: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13605: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13606: my $response=$ua->request($request);
1.1172.2.120 raeburn 13607: if ($response->is_success) {
13608: my $has_sts = $response->header('Strict-Transport-Security');
13609: if ($has_sts eq '') {
13610: $sts_on = 0;
13611: } else {
13612: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13613: my $maxage = $1;
13614: if ($maxage) {
13615: $sts_on = 1;
13616: } else {
13617: $sts_on = 0;
13618: }
13619: } else {
13620: $sts_on = 0;
13621: }
13622: }
13623: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13624: }
13625: }
13626: return;
13627: }
13628:
1.1172.2.142 raeburn 13629: sub waf_allssl {
13630: my ($host_name) = @_;
13631: my $alias = &get_proxy_alias();
13632: if ($host_name eq '') {
13633: $host_name = $ENV{'SERVER_NAME'};
13634: }
13635: if (($host_name ne '') && ($alias eq $host_name)) {
13636: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13637: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13638: if ($defdomdefaults{'waf_sslopt'}) {
13639: return $defdomdefaults{'waf_sslopt'};
13640: }
13641: }
13642: return;
13643: }
13644:
1.1172.2.134 raeburn 13645: sub get_requestor_ip {
13646: my ($r,$nolookup,$noproxy) = @_;
13647: my $from_ip;
13648: if (ref($r)) {
1.1172.2.142 raeburn 13649: if ($r->can('useragent_ip')) {
13650: if ($noproxy && $r->can('client_ip')) {
13651: $from_ip = $r->client_ip();
13652: } else {
13653: $from_ip = $r->useragent_ip();
13654: }
13655: } elsif ($r->connection->can('remote_ip')) {
13656: $from_ip = $r->connection->remote_ip();
13657: } else {
13658: $from_ip = $r->get_remote_host($nolookup);
13659: }
1.1172.2.134 raeburn 13660: } else {
13661: $from_ip = $ENV{'REMOTE_ADDR'};
13662: }
1.1172.2.142 raeburn 13663: return $from_ip if ($noproxy);
13664: # Who controls proxy settings for server
13665: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13666: my $proxyinfo = &get_proxy_settings($dom_in_use);
13667: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13668: if ($proxyinfo->{'vpnint'}) {
13669: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13670: return $from_ip;
13671: }
13672: }
13673: if ($proxyinfo->{'trusted'}) {
13674: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13675: my $ipheader = $proxyinfo->{'ipheader'};
13676: my ($ip,$xfor);
13677: if (ref($r)) {
13678: if ($ipheader) {
13679: $ip = $r->headers_in->{$ipheader};
13680: }
13681: $xfor = $r->headers_in->{'X-Forwarded-For'};
13682: } else {
13683: if ($ipheader) {
13684: $ip = $ENV{'HTTP_'.uc($ipheader)};
13685: }
13686: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13687: }
13688: if (($ip eq '') && ($xfor ne '')) {
13689: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13690: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13691: $ip = $poss_ip;
13692: last;
13693: }
13694: }
13695: }
13696: if ($ip ne '') {
13697: return $ip;
13698: }
13699: }
13700: }
13701: }
1.1172.2.134 raeburn 13702: return $from_ip;
13703: }
13704:
1.1172.2.142 raeburn 13705: sub get_proxy_settings {
13706: my ($dom_in_use) = @_;
13707: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13708: my $proxyinfo = {
13709: ipheader => $domdefaults{'waf_ipheader'},
13710: trusted => $domdefaults{'waf_trusted'},
13711: vpnint => $domdefaults{'waf_vpnint'},
13712: vpnext => $domdefaults{'waf_vpnext'},
13713: sslopt => $domdefaults{'waf_sslopt'},
13714: };
13715: return $proxyinfo;
13716: }
13717:
13718: sub ip_match {
13719: my ($ip,$pattern_str) = @_;
13720: $ip=Net::CIDR::cidrvalidate($ip);
13721: if ($ip) {
13722: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13723: }
13724: return;
13725: }
13726:
13727: sub get_proxy_alias {
13728: my ($lonid) = @_;
13729: if ($lonid eq '') {
13730: $lonid = $perlvar{'lonHostID'};
13731: }
13732: if (!defined(&hostname($lonid))) {
13733: return;
13734: }
13735: if ($lonid ne '') {
13736: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13737: if ($cached) {
13738: return $alias;
13739: }
13740: my $dom = &Apache::lonnet::host_domain($lonid);
13741: if ($dom ne '') {
13742: my $cachetime = 60*60*24;
13743: my %domconfig =
13744: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13745: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13746: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13747: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13748: }
13749: }
13750: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13751: }
13752: }
13753: return;
13754: }
13755:
13756: sub use_proxy_alias {
13757: my ($r,$lonid) = @_;
13758: my $alias = &get_proxy_alias($lonid);
13759: if ($alias) {
13760: my $dom = &host_domain($lonid);
13761: if ($dom ne '') {
13762: my $proxyinfo = &get_proxy_settings($dom);
13763: my ($vpnint,$remote_ip);
13764: if (ref($proxyinfo) eq 'HASH') {
13765: $vpnint = $proxyinfo->{'vpnint'};
13766: if ($vpnint) {
13767: $remote_ip = &get_requestor_ip($r,1,1);
13768: }
13769: }
13770: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13771: return $alias;
13772: }
13773: }
13774: }
13775: return;
13776: }
13777:
13778: sub alias_sso {
13779: my ($lonid) = @_;
13780: if ($lonid eq '') {
13781: $lonid = $perlvar{'lonHostID'};
13782: }
13783: if (!defined(&hostname($lonid))) {
13784: return;
13785: }
13786: if ($lonid ne '') {
13787: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13788: if ($cached) {
13789: return $use_alias;
13790: }
13791: my $dom = &Apache::lonnet::host_domain($lonid);
13792: if ($dom ne '') {
13793: my $cachetime = 60*60*24;
13794: my %domconfig =
13795: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13796: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13797: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13798: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13799: }
13800: }
13801: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13802: }
13803: }
13804: return;
13805: }
13806:
13807: sub get_saml_landing {
13808: my ($lonid) = @_;
13809: if ($lonid eq '') {
13810: my $defdom = &default_login_domain();
13811: my @hosts = ¤t_machine_ids();
13812: if (@hosts > 1) {
13813: foreach my $hostid (@hosts) {
13814: if (&host_domain($hostid) eq $defdom) {
13815: $lonid = $hostid;
13816: last;
13817: }
13818: }
13819: } else {
13820: $lonid = $perlvar{'lonHostID'};
13821: }
13822: if ($lonid) {
13823: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13824: return;
13825: }
13826: } else {
13827: return;
13828: }
13829: } elsif (!defined(&hostname($lonid))) {
13830: return;
13831: }
13832: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13833: if ($cached) {
13834: return $landing;
13835: }
13836: my $dom = &Apache::lonnet::host_domain($lonid);
13837: if ($dom ne '') {
13838: my $cachetime = 60*60*24;
13839: my %domconfig =
13840: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13841: if (ref($domconfig{'login'}) eq 'HASH') {
13842: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13843: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13844: $landing = 1;
13845: }
13846: }
13847: }
13848: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13849: }
13850: return;
13851: }
13852:
1.31 www 13853: # ------------------------------------------------------------- Declutters URLs
13854:
13855: sub declutter {
13856: my $thisfn=shift;
1.569 albertel 13857: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13858: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13859: $thisfn=~s{^/home/httpd/html}{};
13860: }
1.31 www 13861: $thisfn=~s/^\///;
1.697 albertel 13862: $thisfn=~s|^adm/wrapper/||;
13863: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13864: $thisfn=~s/^res\///;
1.1172 bisitz 13865: $thisfn=~s/^priv\///;
1.1032 raeburn 13866: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13867: $thisfn=~s/\?.+$//;
13868: }
1.268 www 13869: return $thisfn;
13870: }
13871:
13872: # ------------------------------------------------------------- Clutter up URLs
13873:
13874: sub clutter {
13875: my $thisfn='/'.&declutter(shift);
1.887 albertel 13876: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13877: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13878: $thisfn='/res'.$thisfn;
13879: }
1.1031 raeburn 13880: if ($thisfn !~m|^/adm|) {
13881: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13882: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13883: } else {
13884: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13885: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13886: if ($embstyle eq 'ssi'
13887: || ($embstyle eq 'hdn')
13888: || ($embstyle eq 'rat')
13889: || ($embstyle eq 'prv')
13890: || ($embstyle eq 'ign')) {
13891: #do nothing with these
13892: } elsif (($embstyle eq 'img')
1.695 albertel 13893: || ($embstyle eq 'emb')
13894: || ($embstyle eq 'wrp')) {
13895: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13896: } elsif ($embstyle eq 'unk'
13897: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13898: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13899: } else {
1.718 www 13900: # &logthis("Got a blank emb style");
1.695 albertel 13901: }
1.694 albertel 13902: }
13903: }
1.31 www 13904: return $thisfn;
1.12 www 13905: }
13906:
1.787 albertel 13907: sub clutter_with_no_wrapper {
13908: my $uri = &clutter(shift);
13909: if ($uri =~ m-^/adm/-) {
13910: $uri =~ s-^/adm/wrapper/-/-;
13911: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13912: }
13913: return $uri;
13914: }
13915:
1.557 albertel 13916: sub freeze_escape {
13917: my ($value)=@_;
13918: if (ref($value)) {
13919: $value=&nfreeze($value);
13920: return '__FROZEN__'.&escape($value);
13921: }
13922: return &escape($value);
13923: }
13924:
1.11 www 13925:
1.557 albertel 13926: sub thaw_unescape {
13927: my ($value)=@_;
13928: if ($value =~ /^__FROZEN__/) {
13929: substr($value,0,10,undef);
13930: $value=&unescape($value);
13931: return &thaw($value);
13932: }
13933: return &unescape($value);
13934: }
13935:
1.436 albertel 13936: sub correct_line_ends {
13937: my ($result)=@_;
13938: $$result =~s/\r\n/\n/mg;
13939: $$result =~s/\r/\n/mg;
1.415 albertel 13940: }
1.1 albertel 13941: # ================================================================ Main Program
13942:
1.184 www 13943: sub goodbye {
1.204 albertel 13944: &logthis("Starting Shut down");
1.443 albertel 13945: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13946: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13947: #converted
1.599 albertel 13948: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13949: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13950: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13951: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13952: #1.1 only
1.870 albertel 13953: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13954: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13955: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13956: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13957: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13958: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13959: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13960: &flushcourselogs();
13961: &logthis("Shutting down");
13962: }
13963:
1.852 albertel 13964: sub get_dns {
1.1172.2.17 raeburn 13965: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13966: if (!$ignore_cache) {
13967: my ($content,$cached)=
13968: &Apache::lonnet::is_cached_new('dns',$url);
13969: if ($cached) {
1.1172.2.17 raeburn 13970: &$func($content,$hashref);
1.869 albertel 13971: return;
13972: }
13973: }
13974:
13975: my %alldns;
1.1172.2.96 raeburn 13976: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13977: foreach my $dns (<$config>) {
13978: next if ($dns !~ /^\^(\S*)/x);
13979: my $line = $1;
13980: my ($host,$protocol) = split(/:/,$line);
13981: if ($protocol ne 'https') {
13982: $protocol = 'http';
13983: }
13984: $alldns{$host} = $protocol;
1.979 raeburn 13985: }
1.1172.2.96 raeburn 13986: close($config);
1.869 albertel 13987: }
13988: while (%alldns) {
1.1172.2.52 raeburn 13989: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13990: my @content;
13991: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13992: my $command = (split('/',$url))[3];
13993: my ($dir,$file) = &parse_getdns_url($command,$url);
13994: delete($alldns{$dns});
13995: next if (($dir eq '') || ($file eq ''));
13996: if (open(my $config,'<',"$dir/$file")) {
13997: @content = <$config>;
13998: close($config);
13999: }
14000: } else {
14001: my $ua=new LWP::UserAgent;
14002: $ua->timeout(30);
14003: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14004: my $response=$ua->request($request);
14005: delete($alldns{$dns});
14006: next if ($response->is_error());
14007: @content = split("\n",$response->content);
14008: }
1.1172.2.17 raeburn 14009: unless ($nocache) {
1.1172.2.23 raeburn 14010: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 14011: }
14012: &$func(\@content,$hashref);
1.869 albertel 14013: return;
1.852 albertel 14014: }
1.871 albertel 14015: my $which = (split('/',$url))[3];
14016: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14017: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14018: my @content = <$config>;
14019: &$func(\@content,$hashref);
14020: }
1.1172.2.17 raeburn 14021: return;
14022: }
14023:
14024: # ------------------------------------------------------Get DNS checksums file
14025: sub parse_dns_checksums_tab {
14026: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14027: my $lonhost = $perlvar{'lonHostID'};
14028: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14029: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14030: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14031: my $webconfdir = '/etc/httpd/conf';
14032: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14033: $webconfdir = '/etc/apache2';
14034: } elsif ($distro =~ /^sles(\d+)$/) {
14035: if ($1 >= 10) {
14036: $webconfdir = '/etc/apache2';
14037: }
14038: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14039: if ($1 >= 10.0) {
14040: $webconfdir = '/etc/apache2';
14041: }
14042: }
1.1172.2.17 raeburn 14043: my ($release,$timestamp) = split(/\-/,$loncaparev);
14044: my (%chksum,%revnum);
14045: if (ref($lines) eq 'ARRAY') {
14046: chomp(@{$lines});
1.1172.2.34 raeburn 14047: my $version = shift(@{$lines});
14048: if ($version eq $release) {
1.1172.2.17 raeburn 14049: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14050: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14051: if ($file =~ m{^/etc/httpd/conf}) {
14052: if ($webconfdir eq '/etc/apache2') {
14053: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14054: }
14055: }
1.1172.2.34 raeburn 14056: $chksum{$file} = $shasum;
14057: $revnum{$file} = $version;
1.1172.2.17 raeburn 14058: }
14059: if (ref($hashref) eq 'HASH') {
14060: %{$hashref} = (
14061: sums => \%chksum,
14062: versions => \%revnum,
14063: );
14064: }
14065: }
14066: }
1.869 albertel 14067: return;
1.852 albertel 14068: }
1.1172.2.17 raeburn 14069:
14070: sub fetch_dns_checksums {
14071: my %checksums;
1.1172.2.34 raeburn 14072: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14073: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14074: my ($release,$timestamp) = split(/\-/,$loncaparev);
14075: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14076: \%checksums);
14077: return \%checksums;
14078: }
14079:
1.1172.2.142 raeburn 14080: sub parse_getdns_url {
14081: my ($command,$url) = @_;
14082: my $dir = $perlvar{'lonTabDir'};
14083: my $file;
14084: if ($command eq 'hosts') {
14085: $file = 'dns_hosts.tab';
14086: } elsif ($command eq 'domain') {
14087: $file = 'dns_domain.tab';
14088: } elsif ($command eq 'checksums') {
14089: my $version = (split('/',$url))[4];
14090: $file = "dns_checksums/$version.tab",
14091: }
14092: return ($dir,$file);
14093: }
14094:
1.327 albertel 14095: # ------------------------------------------------------------ Read domain file
14096: {
1.852 albertel 14097: my $loaded;
1.846 albertel 14098: my %domain;
14099:
1.852 albertel 14100: sub parse_domain_tab {
14101: my ($lines) = @_;
14102: foreach my $line (@$lines) {
14103: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14104:
1.846 albertel 14105: chomp($line);
1.852 albertel 14106: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14107: my %this_domain;
14108: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14109: 'lang_def', 'city', 'longi', 'lati',
14110: 'primary') {
14111: $this_domain{$field} = shift(@elements);
14112: }
14113: $domain{$name} = \%this_domain;
1.852 albertel 14114: }
14115: }
1.864 albertel 14116:
14117: sub reset_domain_info {
14118: undef($loaded);
14119: undef(%domain);
14120: }
14121:
1.852 albertel 14122: sub load_domain_tab {
1.1172.2.70 raeburn 14123: my ($ignore_cache,$nocache) = @_;
14124: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14125: my $fh;
1.1172.2.96 raeburn 14126: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14127: my @lines = <$fh>;
14128: &parse_domain_tab(\@lines);
1.448 albertel 14129: }
1.852 albertel 14130: close($fh);
14131: $loaded = 1;
1.327 albertel 14132: }
1.846 albertel 14133:
14134: sub domain {
1.852 albertel 14135: &load_domain_tab() if (!$loaded);
14136:
1.846 albertel 14137: my ($name,$what) = @_;
14138: return if ( !exists($domain{$name}) );
14139:
14140: if (!$what) {
14141: return $domain{$name}{'description'};
14142: }
14143: return $domain{$name}{$what};
14144: }
1.974 raeburn 14145:
14146: sub domain_info {
14147: &load_domain_tab() if (!$loaded);
14148: return %domain;
14149: }
14150:
1.327 albertel 14151: }
14152:
14153:
1.1 albertel 14154: # ------------------------------------------------------------- Read hosts file
14155: {
1.838 albertel 14156: my %hostname;
1.844 albertel 14157: my %hostdom;
1.845 albertel 14158: my %libserv;
1.852 albertel 14159: my $loaded;
1.888 albertel 14160: my %name_to_host;
1.1074 raeburn 14161: my %internetdom;
1.1107 raeburn 14162: my %LC_dns_serv;
1.852 albertel 14163:
14164: sub parse_hosts_tab {
14165: my ($file) = @_;
14166: foreach my $configline (@$file) {
14167: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14168: chomp($configline);
14169: if ($configline =~ /^\^/) {
14170: if ($configline =~ /^\^([\w.\-]+)/) {
14171: $LC_dns_serv{$1} = 1;
14172: }
14173: next;
14174: }
1.1074 raeburn 14175: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14176: $name=~s/\s//g;
14177: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14178: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14179: my $curr = $hostname{$id};
14180: my $skip;
14181: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14182: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14183: $skip = 1;
14184: } else {
14185: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14186: }
14187: }
14188: unless ($skip) {
14189: push(@{$name_to_host{$name}},$id);
14190: }
14191: } else {
14192: push(@{$name_to_host{$name}},$id);
14193: }
1.852 albertel 14194: $hostname{$id}=$name;
14195: $hostdom{$id}=$domain;
14196: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14197: if (defined($protocol)) {
14198: if ($protocol eq 'https') {
14199: $protocol{$id} = $protocol;
14200: } else {
14201: $protocol{$id} = 'http';
14202: }
1.968 raeburn 14203: } else {
1.969 raeburn 14204: $protocol{$id} = 'http';
1.968 raeburn 14205: }
1.1074 raeburn 14206: if (defined($intdom)) {
14207: $internetdom{$id} = $intdom;
14208: }
1.852 albertel 14209: }
14210: }
14211: }
1.864 albertel 14212:
14213: sub reset_hosts_info {
1.897 albertel 14214: &purge_remembered();
1.864 albertel 14215: &reset_domain_info();
14216: &reset_hosts_ip_info();
1.892 albertel 14217: undef(%name_to_host);
1.864 albertel 14218: undef(%hostname);
14219: undef(%hostdom);
14220: undef(%libserv);
14221: undef($loaded);
14222: }
1.1 albertel 14223:
1.852 albertel 14224: sub load_hosts_tab {
1.1172.2.70 raeburn 14225: my ($ignore_cache,$nocache) = @_;
14226: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14227: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14228: my @config = <$config>;
14229: &parse_hosts_tab(\@config);
14230: close($config);
14231: $loaded=1;
1.1 albertel 14232: }
1.852 albertel 14233:
1.838 albertel 14234: sub hostname {
1.852 albertel 14235: &load_hosts_tab() if (!$loaded);
14236:
1.838 albertel 14237: my ($lonid) = @_;
14238: return $hostname{$lonid};
14239: }
1.845 albertel 14240:
1.838 albertel 14241: sub all_hostnames {
1.852 albertel 14242: &load_hosts_tab() if (!$loaded);
14243:
1.838 albertel 14244: return %hostname;
14245: }
1.845 albertel 14246:
1.888 albertel 14247: sub all_names {
1.1172.2.70 raeburn 14248: my ($ignore_cache,$nocache) = @_;
14249: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14250:
14251: return %name_to_host;
14252: }
14253:
1.974 raeburn 14254: sub all_host_domain {
14255: &load_hosts_tab() if (!$loaded);
14256: return %hostdom;
14257: }
14258:
1.845 albertel 14259: sub is_library {
1.852 albertel 14260: &load_hosts_tab() if (!$loaded);
14261:
1.845 albertel 14262: return exists($libserv{$_[0]});
14263: }
14264:
14265: sub all_library {
1.852 albertel 14266: &load_hosts_tab() if (!$loaded);
14267:
1.845 albertel 14268: return %libserv;
14269: }
14270:
1.1062 droeschl 14271: sub unique_library {
14272: #2x reverse removes all hostnames that appear more than once
14273: my %unique = reverse &all_library();
14274: return reverse %unique;
14275: }
14276:
1.841 albertel 14277: sub get_servers {
1.852 albertel 14278: &load_hosts_tab() if (!$loaded);
14279:
1.841 albertel 14280: my ($domain,$type) = @_;
14281: my %possible_hosts = ($type eq 'library') ? %libserv
14282: : %hostname;
14283: my %result;
1.842 albertel 14284: if (ref($domain) eq 'ARRAY') {
14285: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14286: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14287: $result{$host} = $hostname;
14288: }
14289: }
14290: } else {
14291: while ( my ($host,$hostname) = each(%possible_hosts)) {
14292: if ($hostdom{$host} eq $domain) {
14293: $result{$host} = $hostname;
14294: }
1.841 albertel 14295: }
14296: }
14297: return %result;
14298: }
1.845 albertel 14299:
1.1062 droeschl 14300: sub get_unique_servers {
14301: my %unique = reverse &get_servers(@_);
14302: return reverse %unique;
14303: }
14304:
1.844 albertel 14305: sub host_domain {
1.852 albertel 14306: &load_hosts_tab() if (!$loaded);
14307:
1.844 albertel 14308: my ($lonid) = @_;
14309: return $hostdom{$lonid};
14310: }
14311:
1.841 albertel 14312: sub all_domains {
1.852 albertel 14313: &load_hosts_tab() if (!$loaded);
14314:
1.841 albertel 14315: my %seen;
14316: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14317: return @uniq;
14318: }
1.1074 raeburn 14319:
14320: sub internet_dom {
14321: &load_hosts_tab() if (!$loaded);
14322:
14323: my ($lonid) = @_;
14324: return $internetdom{$lonid};
14325: }
1.1107 raeburn 14326:
14327: sub is_LC_dns {
14328: &load_hosts_tab() if (!$loaded);
14329:
14330: my ($hostname) = @_;
14331: return exists($LC_dns_serv{$hostname});
14332: }
14333:
1.1 albertel 14334: }
14335:
1.847 albertel 14336: {
14337: my %iphost;
1.856 albertel 14338: my %name_to_ip;
14339: my %lonid_to_ip;
1.869 albertel 14340:
1.847 albertel 14341: sub get_hosts_from_ip {
14342: my ($ip) = @_;
14343: my %iphosts = &get_iphost();
14344: if (ref($iphosts{$ip})) {
14345: return @{$iphosts{$ip}};
14346: }
14347: return;
1.839 albertel 14348: }
1.864 albertel 14349:
14350: sub reset_hosts_ip_info {
14351: undef(%iphost);
14352: undef(%name_to_ip);
14353: undef(%lonid_to_ip);
14354: }
1.856 albertel 14355:
14356: sub get_host_ip {
14357: my ($lonid) = @_;
14358: if (exists($lonid_to_ip{$lonid})) {
14359: return $lonid_to_ip{$lonid};
14360: }
14361: my $name=&hostname($lonid);
14362: my $ip = gethostbyname($name);
14363: return if (!$ip || length($ip) ne 4);
14364: $ip=inet_ntoa($ip);
14365: $name_to_ip{$name} = $ip;
14366: $lonid_to_ip{$lonid} = $ip;
14367: return $ip;
14368: }
1.847 albertel 14369:
14370: sub get_iphost {
1.1172.2.70 raeburn 14371: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14372:
1.869 albertel 14373: if (!$ignore_cache) {
14374: if (%iphost) {
14375: return %iphost;
14376: }
14377: my ($ip_info,$cached)=
14378: &Apache::lonnet::is_cached_new('iphost','iphost');
14379: if ($cached) {
14380: %iphost = %{$ip_info->[0]};
14381: %name_to_ip = %{$ip_info->[1]};
14382: %lonid_to_ip = %{$ip_info->[2]};
14383: return %iphost;
14384: }
14385: }
1.894 albertel 14386:
14387: # get yesterday's info for fallback
14388: my %old_name_to_ip;
14389: my ($ip_info,$cached)=
14390: &Apache::lonnet::is_cached_new('iphost','iphost');
14391: if ($cached) {
14392: %old_name_to_ip = %{$ip_info->[1]};
14393: }
14394:
1.1172.2.70 raeburn 14395: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14396: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14397: my $ip;
14398: if (!exists($name_to_ip{$name})) {
14399: $ip = gethostbyname($name);
14400: if (!$ip || length($ip) ne 4) {
1.894 albertel 14401: if (defined($old_name_to_ip{$name})) {
14402: $ip = $old_name_to_ip{$name};
14403: &logthis("Can't find $name defaulting to old $ip");
14404: } else {
14405: &logthis("Name $name no IP found");
14406: next;
14407: }
14408: } else {
14409: $ip=inet_ntoa($ip);
1.847 albertel 14410: }
14411: $name_to_ip{$name} = $ip;
14412: } else {
14413: $ip = $name_to_ip{$name};
1.653 albertel 14414: }
1.888 albertel 14415: foreach my $id (@{ $name_to_host{$name} }) {
14416: $lonid_to_ip{$id} = $ip;
14417: }
14418: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14419: }
1.1172.2.70 raeburn 14420: unless ($nocache) {
14421: &do_cache_new('iphost','iphost',
14422: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14423: 48*60*60);
14424: }
1.869 albertel 14425:
1.847 albertel 14426: return %iphost;
1.598 albertel 14427: }
14428:
1.992 raeburn 14429: #
14430: # Given a DNS returns the loncapa host name for that DNS
14431: #
14432: sub host_from_dns {
14433: my ($dns) = @_;
14434: my @hosts;
14435: my $ip;
14436:
1.993 raeburn 14437: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14438: $ip = $name_to_ip{$dns};
14439: }
14440: if (!$ip) {
14441: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14442: if (length($ip) == 4) {
14443: $ip = &IO::Socket::inet_ntoa($ip);
14444: }
14445: }
14446: if ($ip) {
14447: @hosts = get_hosts_from_ip($ip);
14448: return $hosts[0];
14449: }
14450: return undef;
1.986 foxr 14451: }
1.992 raeburn 14452:
1.1074 raeburn 14453: sub get_internet_names {
14454: my ($lonid) = @_;
14455: return if ($lonid eq '');
14456: my ($idnref,$cached)=
14457: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14458: if ($cached) {
14459: return $idnref;
14460: }
14461: my $ip = &get_host_ip($lonid);
14462: my @hosts = &get_hosts_from_ip($ip);
14463: my %iphost = &get_iphost();
14464: my (@idns,%seen);
14465: foreach my $id (@hosts) {
14466: my $dom = &host_domain($id);
14467: my $prim_id = &domain($dom,'primary');
14468: my $prim_ip = &get_host_ip($prim_id);
14469: next if ($seen{$prim_ip});
14470: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14471: foreach my $id (@{$iphost{$prim_ip}}) {
14472: my $intdom = &internet_dom($id);
14473: unless (grep(/^\Q$intdom\E$/,@idns)) {
14474: push(@idns,$intdom);
14475: }
14476: }
14477: }
14478: $seen{$prim_ip} = 1;
14479: }
1.1172.2.23 raeburn 14480: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14481: }
14482:
1.986 foxr 14483: }
14484:
1.1079 raeburn 14485: sub all_loncaparevs {
1.1172.2.39 raeburn 14486: 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 14487: }
14488:
1.1172.2.27 raeburn 14489: # ------------------------------------------------------- Read loncaparev table
14490: {
14491: sub load_loncaparevs {
14492: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14493: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14494: while (my $configline=<$config>) {
14495: chomp($configline);
14496: my ($hostid,$loncaparev)=split(/:/,$configline);
14497: $loncaparevs{$hostid}=$loncaparev;
14498: }
14499: close($config);
14500: }
14501: }
14502: }
14503: }
14504:
14505: # ----------------------------------------------------- Read serverhostID table
14506: {
14507: sub load_serverhomeIDs {
14508: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14509: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14510: while (my $configline=<$config>) {
14511: chomp($configline);
14512: my ($name,$id)=split(/:/,$configline);
14513: $serverhomeIDs{$name}=$id;
14514: }
14515: close($config);
14516: }
14517: }
14518: }
14519: }
14520:
14521:
1.862 albertel 14522: BEGIN {
14523:
14524: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14525: unless ($readit) {
14526: {
14527: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14528: %perlvar = (%perlvar,%{$configvars});
14529: }
14530:
14531:
1.1 albertel 14532: # ------------------------------------------------------ Read spare server file
14533: {
1.1172.2.96 raeburn 14534: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14535:
14536: while (my $configline=<$config>) {
14537: chomp($configline);
1.284 matthew 14538: if ($configline) {
1.784 albertel 14539: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14540: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14541: push(@{ $spareid{$type} }, $host);
1.1 albertel 14542: }
14543: }
1.448 albertel 14544: close($config);
1.1 albertel 14545: }
1.11 www 14546: # ------------------------------------------------------------ Read permissions
14547: {
1.1172.2.96 raeburn 14548: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14549:
14550: while (my $configline=<$config>) {
1.448 albertel 14551: chomp($configline);
14552: if ($configline) {
14553: my ($role,$perm)=split(/ /,$configline);
14554: if ($perm ne '') { $pr{$role}=$perm; }
14555: }
1.11 www 14556: }
1.448 albertel 14557: close($config);
1.11 www 14558: }
14559:
14560: # -------------------------------------------- Read plain texts for permissions
14561: {
1.1172.2.96 raeburn 14562: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14563:
14564: while (my $configline=<$config>) {
1.448 albertel 14565: chomp($configline);
14566: if ($configline) {
1.742 raeburn 14567: my ($short,@plain)=split(/:/,$configline);
14568: %{$prp{$short}} = ();
14569: if (@plain > 0) {
14570: $prp{$short}{'std'} = $plain[0];
14571: for (my $i=1; $i<@plain; $i++) {
14572: $prp{$short}{'alt'.$i} = $plain[$i];
14573: }
14574: }
1.448 albertel 14575: }
1.135 www 14576: }
1.448 albertel 14577: close($config);
1.135 www 14578: }
14579:
14580: # ---------------------------------------------------------- Read package table
14581: {
1.1172.2.96 raeburn 14582: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14583:
14584: while (my $configline=<$config>) {
1.483 albertel 14585: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14586: chomp($configline);
14587: my ($short,$plain)=split(/:/,$configline);
14588: my ($pack,$name)=split(/\&/,$short);
14589: if ($plain ne '') {
14590: $packagetab{$pack.'&'.$name.'&name'}=$name;
14591: $packagetab{$short}=$plain;
14592: }
1.11 www 14593: }
1.448 albertel 14594: close($config);
1.329 matthew 14595: }
14596:
1.1172.2.27 raeburn 14597: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14598:
1.1172.2.27 raeburn 14599: &load_loncaparevs();
14600:
14601: # ------------------------------------------------------- Read serverhostID table
14602:
14603: &load_serverhomeIDs();
1.1074 raeburn 14604:
1.1172.2.27 raeburn 14605: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14606: {
14607: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14608: if (-e $file) {
14609: my $parser = HTML::LCParser->new($file);
14610: while (my $token = $parser->get_token()) {
14611: if ($token->[0] eq 'S') {
14612: my $item = $token->[1];
14613: my $name = $token->[2]{'name'};
14614: my $value = $token->[2]{'value'};
14615: if ($item ne '' && $name ne '' && $value ne '') {
14616: my $release = $parser->get_text();
14617: $release =~ s/(^\s*|\s*$ )//gx;
14618: $needsrelease{$item.':'.$name.':'.$value} = $release;
14619: }
14620: }
14621: }
14622: }
1.1073 raeburn 14623: }
14624:
1.1138 raeburn 14625: # ---------------------------------------------------------- Read managers table
14626: {
14627: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14628: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14629: while (my $configline=<$config>) {
14630: chomp($configline);
14631: next if ($configline =~ /^\#/);
14632: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14633: $managerstab{$configline} = 1;
14634: }
14635: }
14636: close($config);
14637: }
14638: }
14639: }
14640:
1.329 matthew 14641: # ------------- set up temporary directory
14642: {
1.1117 foxr 14643: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14644:
1.11 www 14645: }
14646:
1.1172.2.104 raeburn 14647: # ------------- set default texengine (domain default overrides this)
14648: {
14649: $deftex = LONCAPA::texengine();
14650: }
14651:
1.1172.2.114 raeburn 14652: # ------------- set default minimum length for passwords for internal auth users
14653: {
14654: $passwdmin = LONCAPA::passwd_min();
14655: }
14656:
1.794 albertel 14657: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14658: 'compress_threshold'=> 20_000,
14659: });
1.185 www 14660:
1.281 www 14661: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14662: $dumpcount=0;
1.958 www 14663: $locknum=0;
1.22 www 14664:
1.163 harris41 14665: &logtouch();
1.672 albertel 14666: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14667: $readit=1;
1.564 albertel 14668: {
14669: use integer;
14670: my $test=(2**32)+1;
1.568 albertel 14671: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14672: &logthis(" Detected 64bit platform ($_64bit)");
14673: }
1.195 www 14674: }
1.1 albertel 14675: }
1.179 www 14676:
1.1 albertel 14677: 1;
1.191 harris41 14678: __END__
14679:
1.243 albertel 14680: =pod
14681:
1.191 harris41 14682: =head1 NAME
14683:
1.243 albertel 14684: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14685:
14686: =head1 SYNOPSIS
14687:
1.243 albertel 14688: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14689:
14690: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14691:
1.243 albertel 14692: Common parameters:
14693:
14694: =over 4
14695:
14696: =item *
14697:
14698: $uname : an internal username (if $cname expecting a course Id specifically)
14699:
14700: =item *
14701:
14702: $udom : a domain (if $cdom expecting a course's domain specifically)
14703:
14704: =item *
14705:
14706: $symb : a resource instance identifier
14707:
14708: =item *
14709:
14710: $namespace : the name of a .db file that contains the data needed or
14711: being set.
14712:
14713: =back
14714:
1.394 bowersj2 14715: =head1 OVERVIEW
1.191 harris41 14716:
1.394 bowersj2 14717: lonnet provides subroutines which interact with the
14718: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14719: about classes, users, and resources.
1.243 albertel 14720:
14721: For many of these objects you can also use this to store data about
14722: them or modify them in various ways.
1.191 harris41 14723:
1.394 bowersj2 14724: =head2 Symbs
1.191 harris41 14725:
1.394 bowersj2 14726: To identify a specific instance of a resource, LON-CAPA uses symbols
14727: or "symbs"X<symb>. These identifiers are built from the URL of the
14728: map, the resource number of the resource in the map, and the URL of
14729: the resource itself. The latter is somewhat redundant, but might help
14730: if maps change.
14731:
14732: An example is
14733:
14734: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14735:
14736: The respective map entry is
14737:
14738: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14739: title="Problem 2">
14740: </resource>
14741:
14742: Symbs are used by the random number generator, as well as to store and
14743: restore data specific to a certain instance of for example a problem.
14744:
14745: =head2 Storing And Retrieving Data
14746:
14747: X<store()>X<cstore()>X<restore()>Three of the most important functions
14748: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14749: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14750: is is the non-critical message twin of cstore. These functions are for
14751: handlers to store a perl hash to a user's permanent data space in an
14752: easy manner, and to retrieve it again on another call. It is expected
14753: that a handler would use this once at the beginning to retrieve data,
14754: and then again once at the end to send only the new data back.
14755:
14756: The data is stored in the user's data directory on the user's
14757: homeserver under the ID of the course.
14758:
14759: The hash that is returned by restore will have all of the previous
14760: value for all of the elements of the hash.
14761:
14762: Example:
14763:
14764: #creating a hash
14765: my %hash;
14766: $hash{'foo'}='bar';
14767:
14768: #storing it
14769: &Apache::lonnet::cstore(\%hash);
14770:
14771: #changing a value
14772: $hash{'foo'}='notbar';
14773:
14774: #adding a new value
14775: $hash{'bar'}='foo';
14776: &Apache::lonnet::cstore(\%hash);
14777:
14778: #retrieving the hash
14779: my %history=&Apache::lonnet::restore();
14780:
14781: #print the hash
14782: foreach my $key (sort(keys(%history))) {
14783: print("\%history{$key} = $history{$key}");
14784: }
14785:
14786: Will print out:
1.191 harris41 14787:
1.394 bowersj2 14788: %history{1:foo} = bar
14789: %history{1:keys} = foo:timestamp
14790: %history{1:timestamp} = 990455579
14791: %history{2:bar} = foo
14792: %history{2:foo} = notbar
14793: %history{2:keys} = foo:bar:timestamp
14794: %history{2:timestamp} = 990455580
14795: %history{bar} = foo
14796: %history{foo} = notbar
14797: %history{timestamp} = 990455580
14798: %history{version} = 2
14799:
14800: Note that the special hash entries C<keys>, C<version> and
14801: C<timestamp> were added to the hash. C<version> will be equal to the
14802: total number of versions of the data that have been stored. The
14803: C<timestamp> attribute will be the UNIX time the hash was
14804: stored. C<keys> is available in every historical section to list which
14805: keys were added or changed at a specific historical revision of a
14806: hash.
14807:
14808: B<Warning>: do not store the hash that restore returns directly. This
14809: will cause a mess since it will restore the historical keys as if the
14810: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14811:
1.394 bowersj2 14812: Calling convention:
1.191 harris41 14813:
1.1172.2.27 raeburn 14814: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14815: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14816:
1.394 bowersj2 14817: For more detailed information, see lonnet specific documentation.
1.191 harris41 14818:
1.394 bowersj2 14819: =head1 RETURN MESSAGES
1.191 harris41 14820:
1.394 bowersj2 14821: =over 4
1.191 harris41 14822:
1.394 bowersj2 14823: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14824:
1.394 bowersj2 14825: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14826: when the connection is brought back up
1.191 harris41 14827:
1.394 bowersj2 14828: =item * B<con_failed>: unable to contact remote host and unable to save message
14829: for later delivery
1.191 harris41 14830:
1.967 bisitz 14831: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14832:
1.394 bowersj2 14833: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14834: that was requested
1.191 harris41 14835:
1.243 albertel 14836: =back
1.191 harris41 14837:
1.243 albertel 14838: =head1 PUBLIC SUBROUTINES
1.191 harris41 14839:
1.243 albertel 14840: =head2 Session Environment Functions
1.191 harris41 14841:
1.243 albertel 14842: =over 4
1.191 harris41 14843:
1.394 bowersj2 14844: =item *
14845: X<appenv()>
1.949 raeburn 14846: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14847: the user envirnoment file, and will be restored for each access this
1.620 albertel 14848: user makes during this session, also modifies the %env for the current
1.949 raeburn 14849: process. Optional rolesarrayref - if defined contains a reference to an array
14850: of roles which are exempt from the restriction on modifying user.role entries
14851: in the user's environment.db and in %env.
1.191 harris41 14852:
14853: =item *
1.394 bowersj2 14854: X<delenv()>
1.987 raeburn 14855: B<delenv($delthis,$regexp)>: removes all items from the session
14856: environment file that begin with $delthis. If the
14857: optional second arg - $regexp - is true, $delthis is treated as a
14858: regular expression, otherwise \Q$delthis\E is used.
14859: The values are also deleted from the current processes %env.
1.191 harris41 14860:
1.795 albertel 14861: =item * get_env_multiple($name)
14862:
14863: gets $name from the %env hash, it seemlessly handles the cases where multiple
14864: values may be defined and end up as an array ref.
14865:
14866: returns an array of values
14867:
1.243 albertel 14868: =back
14869:
14870: =head2 User Information
1.191 harris41 14871:
1.243 albertel 14872: =over 4
1.191 harris41 14873:
14874: =item *
1.394 bowersj2 14875: X<queryauthenticate()>
14876: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14877: authentication scheme
14878:
14879: =item *
1.394 bowersj2 14880: X<authenticate()>
1.1073 raeburn 14881: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14882: authenticate user from domain's lib servers (first use the current
14883: one). C<$upass> should be the users password.
1.1073 raeburn 14884: $checkdefauth is optional (value is 1 if a check should be made to
14885: authenticate user using default authentication method, and allow
14886: account creation if username does not have account in the domain).
14887: $clientcancheckhost is optional (value is 1 if checking whether the
14888: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14889:
14890: =item *
1.394 bowersj2 14891: X<homeserver()>
14892: B<homeserver($uname,$udom)>: find the server which has
14893: the user's directory and files (there must be only one), this caches
14894: the answer, and also caches if there is a borken connection.
1.191 harris41 14895:
14896: =item *
1.394 bowersj2 14897: X<idget()>
14898: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14899: (IDs are a unique resource in a domain, there must be only 1 ID per
14900: username, and only 1 username per ID in a specific domain) (returns
14901: hash: id=>name,id=>name)
1.191 harris41 14902:
14903: =item *
1.394 bowersj2 14904: X<idrget()>
14905: B<idrget($udom,@unames)>: find the IDs behind a list of
14906: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14907:
14908: =item *
1.394 bowersj2 14909: X<idput()>
14910: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14911:
14912: =item *
1.394 bowersj2 14913: X<rolesinit()>
1.1169 droeschl 14914: B<rolesinit($udom,$username)>: get user privileges.
14915: returns user role, first access and timer interval hashes
1.243 albertel 14916:
14917: =item *
1.1171 droeschl 14918: X<privileged()>
14919: B<privileged($username,$domain)>: returns a true if user has a
14920: privileged and active role (i.e. su or dc), false otherwise.
14921:
14922: =item *
1.551 albertel 14923: X<getsection()>
14924: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14925: course $cname, return section name/number or '' for "not in course"
14926: and '-1' for "no section"
14927:
14928: =item *
1.394 bowersj2 14929: X<userenvironment()>
14930: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14931: passed in @what from the requested user's environment, returns a hash
14932:
1.858 raeburn 14933: =item *
14934: X<userlog_query()>
1.859 albertel 14935: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14936: activity.log file. %filters defines filters applied when parsing the
14937: log file. These can be start or end timestamps, or the type of action
14938: - log to look for Login or Logout events, check for Checkin or
14939: Checkout, role for role selection. The response is in the form
14940: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14941: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14942:
1.243 albertel 14943: =back
14944:
14945: =head2 User Roles
14946:
14947: =over 4
14948:
14949: =item *
14950:
1.1172.2.65 raeburn 14951: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14952: returns codes for allowed actions.
14953:
14954: The first argument is required, all others are optional.
14955:
14956: $priv is the privilege being checked.
14957: $uri contains additional information about what is being checked for access (e.g.,
14958: URL, course ID etc.).
14959: $symb is the unique resource instance identifier in a course; if needed,
14960: but not provided, it will be retrieved via a call to &symbread().
14961: $role is the role for which a priv is being checked (only used if priv is evb).
14962: $clientip is the user's IP address (only used when checking for access to portfolio
14963: files).
14964: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14965: prevents recursive calls to &allowed.
14966:
1.243 albertel 14967: F: full access
14968: U,I,K: authentication modes (cxx only)
14969: '': forbidden
14970: 1: user needs to choose course
14971: 2: browse allowed
1.766 albertel 14972: A: passphrase authentication needed
1.1172.2.65 raeburn 14973: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14974:
14975: =item *
14976:
1.1172.2.13 raeburn 14977: constructaccess($url,$setpriv) : check for access to construction space URL
14978:
14979: See if the owner domain and name in the URL match those in the
14980: expected environment. If so, return three element list
14981: ($ownername,$ownerdomain,$ownerhome).
14982:
14983: Otherwise return the null string.
14984:
14985: If second argument 'setpriv' is true, it assigns the privileges,
14986: and returns the same three element list, unless the owner has
14987: blocked "ad hoc" Domain Coordinator access to the Author Space,
14988: in which case the null string is returned.
14989:
14990: =item *
14991:
1.1172.2.84 raeburn 14992: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14993: define a custom role rolename set privileges in format of lonTabs/roles.tab
14994: for system, domain, and course level. $uname and $udom are optional (current
14995: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14996:
14997: =item *
14998:
1.988 raeburn 14999: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15000: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15001: $type is Course (default) or Community.
1.988 raeburn 15002: If $forcedefault evaluates to true, text returned will be default
15003: text for $type. Otherwise, if this is a course, the text returned
15004: will be a custom name for the role (if defined in the course's
15005: environment). If no custom name is defined the default is returned.
15006:
1.832 raeburn 15007: =item *
15008:
1.1172.2.23 raeburn 15009: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15010: All arguments are optional. Returns a hash of a roles, either for
15011: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15012: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15013: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15014: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15015: For each key, value is set to colon-separated start and end times for
15016: the role. If no username and domain are specified, will default to
1.934 raeburn 15017: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15018: of role statuses (active, future or previous), roles
15019: (e.g., cc,in, st etc.) and domains of the roles which can be used
15020: to restrict the list of roles reported. If no array ref is
15021: provided for types, will default to return only active roles.
1.834 albertel 15022:
1.1172.2.13 raeburn 15023: =item *
15024:
15025: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15026: user: $uname:$udom has a role in the course: $cdom_$cnum.
15027:
15028: Additional optional arguments are: $type (if role checking is to be restricted
15029: to certain user status types -- previous (expired roles), active (currently
15030: available roles) or future (roles available in the future), and
15031: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15032: have active Domain Coordinator role in course's domain or in additional
15033: domains (specified in 'Domains to check for privileged users' in course
15034: environment -- set via: Course Settings -> Classlists and staff listing).
15035:
15036: =item *
15037:
15038: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15039: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15040: $possdomains and $possroles are optional array refs -- to domains to check and
15041: roles to check. If $possdomains is not specified, a dump will be done of the
15042: users' roles.db to check for a dc or su role in any domain. This can be
15043: time consuming if &privileged is called repeatedly (e.g., when displaying a
15044: classlist), so in such cases, supplying a $possdomains array is preferred, as
15045: this then allows &privileged_by_domain() to be used, which caches the identity
15046: of privileged users, eliminating the need for repeated calls to &dump().
15047:
15048: =item *
15049:
15050: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15051: where the outer hash keys are domains specified in the $possdomains array ref,
15052: next inner hash keys are privileged roles specified in the $roles array ref,
15053: and the innermost hash contains key = value pairs for username:domain = end:start
15054: for active or future "privileged" users with that role in that domain. To avoid
15055: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15056: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15057:
1.243 albertel 15058: =back
15059:
15060: =head2 User Modification
15061:
15062: =over 4
15063:
15064: =item *
15065:
1.957 raeburn 15066: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15067: user for the level given by URL. Optional start and end dates (leave empty
15068: string or zero for "no date")
1.191 harris41 15069:
15070: =item *
15071:
1.243 albertel 15072: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15073: change a users, password, possible return values are: ok,
15074: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15075: refused
1.191 harris41 15076:
15077: =item *
15078:
1.243 albertel 15079: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15080:
15081: =item *
15082:
1.1058 raeburn 15083: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15084: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15085:
15086: will update user information (firstname,middlename,lastname,generation,
15087: permanentemail), and if forceid is true, student/employee ID also.
15088: A user's institutional affiliation(s) can also be updated.
15089: User information fields will not be overwritten with empty entries
15090: unless the field is included in the $candelete array reference.
15091: This array is included when a single user is modified via "Manage Users",
15092: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15093:
15094: =item *
15095:
1.286 matthew 15096: modifystudent
15097:
1.957 raeburn 15098: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15099: The course id is resolved based on the current user's environment.
15100: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15101: associated with a course.
15102:
1.297 matthew 15103: This call is essentially a wrapper for lonnet::modifyuser and
15104: lonnet::modify_student_enrollment
1.286 matthew 15105:
15106: Inputs:
15107:
15108: =over 4
15109:
1.957 raeburn 15110: =item B<$udom> Student's loncapa domain
1.286 matthew 15111:
1.957 raeburn 15112: =item B<$uname> Student's loncapa login name
1.286 matthew 15113:
1.964 bisitz 15114: =item B<$uid> Student/Employee ID
1.286 matthew 15115:
1.957 raeburn 15116: =item B<$umode> Student's authentication mode
1.286 matthew 15117:
1.957 raeburn 15118: =item B<$upass> Student's password
1.286 matthew 15119:
1.957 raeburn 15120: =item B<$first> Student's first name
1.286 matthew 15121:
1.957 raeburn 15122: =item B<$middle> Student's middle name
1.286 matthew 15123:
1.957 raeburn 15124: =item B<$last> Student's last name
1.286 matthew 15125:
1.957 raeburn 15126: =item B<$gene> Student's generation
1.286 matthew 15127:
1.957 raeburn 15128: =item B<$usec> Student's section in course
1.286 matthew 15129:
15130: =item B<$end> Unix time of the roles expiration
15131:
15132: =item B<$start> Unix time of the roles start date
15133:
15134: =item B<$forceid> If defined, allow $uid to be changed
15135:
15136: =item B<$desiredhome> server to use as home server for student
15137:
1.957 raeburn 15138: =item B<$email> Student's permanent e-mail address
15139:
15140: =item B<$type> Type of enrollment (auto or manual)
15141:
1.963 raeburn 15142: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15143:
15144: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15145:
1.963 raeburn 15146: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15147:
1.963 raeburn 15148: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15149:
1.1172.2.19 raeburn 15150: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15151:
15152: =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 15153:
1.286 matthew 15154: =back
1.297 matthew 15155:
15156: =item *
15157:
15158: modify_student_enrollment
15159:
1.1172.2.31 raeburn 15160: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15161: 'role.request.course' must be defined for this function to proceed.
15162:
15163: Inputs:
15164:
15165: =over 4
15166:
1.1172.2.31 raeburn 15167: =item $udom, student's domain
1.297 matthew 15168:
1.1172.2.31 raeburn 15169: =item $uname, student's name
1.297 matthew 15170:
1.1172.2.31 raeburn 15171: =item $uid, student's user id
1.297 matthew 15172:
1.1172.2.31 raeburn 15173: =item $first, student's first name
1.297 matthew 15174:
15175: =item $middle
15176:
15177: =item $last
15178:
15179: =item $gene
15180:
15181: =item $usec
15182:
15183: =item $end
15184:
15185: =item $start
15186:
1.957 raeburn 15187: =item $type
15188:
15189: =item $locktype
15190:
15191: =item $cid
15192:
15193: =item $selfenroll
15194:
15195: =item $context
15196:
1.1172.2.19 raeburn 15197: =item $credits, number of credits student will earn from this class
15198:
1.1172.2.76 raeburn 15199: =item $instsec, institutional course section code for student
15200:
1.297 matthew 15201: =back
15202:
1.191 harris41 15203:
15204: =item *
15205:
1.243 albertel 15206: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15207: custom role; give a custom role to a user for the level given by URL. Specify
15208: name and domain of role author, and role name
1.191 harris41 15209:
15210: =item *
15211:
1.243 albertel 15212: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15213:
15214: =item *
15215:
1.243 albertel 15216: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15217:
15218: =back
15219:
15220: =head2 Course Infomation
15221:
15222: =over 4
1.191 harris41 15223:
15224: =item *
15225:
1.1118 foxr 15226: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15227: specified course id, including all environment settings for the
15228: course, the description of the course will be in the hash under the
15229: key 'description'
1.191 harris41 15230:
1.1118 foxr 15231: $options is an optional parameter that if supplied is a hash reference that controls
15232: what how this function works. It has the following key/values:
15233:
15234: =over 4
15235:
15236: =item freshen_cache
15237:
15238: If defined, and the environment cache for the course is valid, it is
15239: returned in the returned hash.
15240:
15241: =item one_time
15242:
15243: If defined, the last cache time is set to _now_
15244:
15245: =item user
15246:
15247: If defined, the supplied username is used instead of the current user.
15248:
15249:
15250: =back
15251:
1.191 harris41 15252: =item *
15253:
1.624 albertel 15254: resdata($name,$domain,$type,@which) : request for current parameter
15255: setting for a specific $type, where $type is either 'course' or 'user',
15256: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15257: answers for 10 minutes.
1.243 albertel 15258:
1.877 foxr 15259: =item *
15260:
15261: get_courseresdata($courseid, $domain) : dump the entire course resource
15262: data base, returning a hash that is keyed by the resource name and has
15263: values that are the resource value. I believe that the timestamps and
15264: versions are also returned.
15265:
1.1172.2.31 raeburn 15266: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15267: supplemental content area. This routine caches the number of files for
15268: 10 minutes.
15269:
1.243 albertel 15270: =back
15271:
15272: =head2 Course Modification
15273:
15274: =over 4
1.191 harris41 15275:
15276: =item *
15277:
1.243 albertel 15278: writecoursepref($courseid,%prefs) : write preferences (environment
15279: database) for a course
1.191 harris41 15280:
15281: =item *
15282:
1.1011 raeburn 15283: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15284:
15285: =item *
15286:
1.1038 raeburn 15287: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15288:
1.1167 droeschl 15289: =item *
15290:
15291: is_course($courseid), is_course($cdom, $cnum)
15292:
15293: Accepts either a combined $courseid (in the form of domain_courseid) or the
15294: two component version $cdom, $cnum. It checks if the specified course exists.
15295:
15296: Returns:
15297: undef if the course doesn't exist, otherwise
15298: in scalar context the combined courseid.
15299: in list context the two components of the course identifier, domain and
15300: courseid.
15301:
1.243 albertel 15302: =back
15303:
1.1172.2.109 raeburn 15304: =head2 Bubblesheet Configuration
15305:
15306: =over 4
15307:
15308: =item *
15309:
15310: get_scantron_config($which)
15311:
15312: $which - the name of the configuration to parse from the file.
15313:
15314: Parses and returns the bubblesheet configuration line selected as a
15315: hash of configuration file fields.
15316:
15317:
15318: Returns:
15319: If the named configuration is not in the file, an empty
15320: hash is returned.
15321:
15322: a hash with the fields
15323: name - internal name for the this configuration setup
15324: description - text to display to operator that describes this config
15325: CODElocation - if 0 or the string 'none'
15326: - no CODE exists for this config
15327: if -1 || the string 'letter'
15328: - a CODE exists for this config and is
15329: a string of letters
15330: Unsupported value (but planned for future support)
15331: if a positive integer
15332: - The CODE exists as the first n items from
15333: the question section of the form
15334: if the string 'number'
15335: - The CODE exists for this config and is
15336: a string of numbers
15337: CODEstart - (only matter if a CODE exists) column in the line where
15338: the CODE starts
15339: CODElength - length of the CODE
15340: IDstart - column where the student/employee ID starts
15341: IDlength - length of the student/employee ID info
15342: Qstart - column where the information from the bubbled
15343: 'questions' start
15344: Qlength - number of columns comprising a single bubble line from
15345: the sheet. (usually either 1 or 10)
15346: Qon - either a single character representing the character used
15347: to signal a bubble was chosen in the positional setup, or
15348: the string 'letter' if the letter of the chosen bubble is
15349: in the final, or 'number' if a number representing the
15350: chosen bubble is in the file (1->A 0->J)
15351: Qoff - the character used to represent that a bubble was
15352: left blank
15353: PaperID - if the scanning process generates a unique number for each
15354: sheet scanned the column that this ID number starts in
15355: PaperIDlength - number of columns that comprise the unique ID number
15356: for the sheet of paper
15357: FirstName - column that the first name starts in
15358: FirstNameLength - number of columns that the first name spans
15359: LastName - column that the last name starts in
15360: LastNameLength - number of columns that the last name spans
15361: BubblesPerRow - number of bubbles available in each row used to
15362: bubble an answer. (If not specified, 10 assumed).
15363:
15364:
15365: =item *
15366:
15367: get_scantronformat_file($cdom)
15368:
15369: $cdom - the course's domain (optional); if not supplied, uses
15370: domain for current $env{'request.course.id'}.
15371:
15372: Returns an array containing lines from the scantron format file for
15373: the domain of the course.
15374:
15375: If a url for a custom.tab file is listed in domain's configuration.db,
15376: lines are from this file.
15377:
15378: Otherwise, if a default.tab has been published in RES space by the
15379: domainconfig user, lines are from this file.
15380:
15381: Otherwise, fall back to getting lines from the legacy file on the
15382: local server: /home/httpd/lonTabs/default_scantronformat.tab
15383:
15384: =back
15385:
1.243 albertel 15386: =head2 Resource Subroutines
15387:
15388: =over 4
1.191 harris41 15389:
15390: =item *
15391:
1.243 albertel 15392: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15393:
15394: =item *
15395:
1.243 albertel 15396: repcopy($filename) : subscribes to the requested file, and attempts to
15397: replicate from the owning library server, Might return
1.607 raeburn 15398: 'unavailable', 'not_found', 'forbidden', 'ok', or
15399: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15400: resource. Expects the local filesystem pathname
15401: (/home/httpd/html/res/....)
15402:
15403: =back
15404:
15405: =head2 Resource Information
15406:
15407: =over 4
1.191 harris41 15408:
15409: =item *
15410:
1.1172.2.28 raeburn 15411: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15412: and returns the value of a variety of different possible values,
15413: $varname should be a request string, and the other parameters can be
15414: used to specify who and what one is asking about. Ordinarily, $cid
15415: does not need to be specified, as it is retrived from
15416: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15417: within lonuserstate::loadmap() when initializing a course, before
15418: $env{'request.course.id'} has been set, so it needs to be provided
15419: in that one case.
1.243 albertel 15420:
15421: Possible values for $varname are environment.lastname (or other item
15422: from the envirnment hash), user.name (or someother aspect about the
15423: user), resource.0.maxtries (or some other part and parameter of a
15424: resource)
1.204 albertel 15425:
15426: =item *
15427:
1.243 albertel 15428: directcondval($number) : get current value of a condition; reads from a state
15429: string
1.204 albertel 15430:
15431: =item *
15432:
1.243 albertel 15433: condval($condidx) : value of condition index based on state
1.204 albertel 15434:
15435: =item *
15436:
1.243 albertel 15437: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15438: resource's metadata, $what should be either a specific key, or either
15439: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15440: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15441:
15442: this function automatically caches all requests
1.191 harris41 15443:
15444: =item *
15445:
1.243 albertel 15446: metadata_query($query,$custom,$customshow) : make a metadata query against the
15447: network of library servers; returns file handle of where SQL and regex results
15448: will be stored for query
1.191 harris41 15449:
15450: =item *
15451:
1.1172.2.66 raeburn 15452: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15453: return symbolic list entry (all arguments optional).
15454:
15455: Args: filename is the filename (including path) for the file for which a symb
15456: is required; donotrecurse, if true will prevent calls to allowed() being made
15457: to check access status if more than one resource was found in the bighash
15458: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15459: a randompick); ignorecachednull, if true will prevent a symb of '' being
15460: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15461: cause possible symbs to be checked to determine if they are subject to content
15462: blocking, if so they will not be included as possible symbs; possibles is a
15463: ref to a hash, which, as a side effect, will be populated with all possible
15464: symbs (content blocking not tested).
15465:
1.243 albertel 15466: returns the data handle
1.191 harris41 15467:
15468: =item *
15469:
1.1172.2.17 raeburn 15470: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15471: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15472: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15473: on failure, user must be in a course, as it assumes the existence of
15474: the course initial hash, and uses $env('request.course.id'}. The third
15475: arg is an optional reference to a scalar. If this arg is passed in the
15476: call to symbverify, it will be set to 1 if the symb has been set to be
15477: encrypted; otherwise it will be null.
1.243 albertel 15478:
1.191 harris41 15479: =item *
15480:
1.243 albertel 15481: symbclean($symb) : removes versions numbers from a symb, returns the
15482: cleaned symb
1.191 harris41 15483:
15484: =item *
15485:
1.243 albertel 15486: is_on_map($uri) : checks if the $uri is somewhere on the current
15487: course map, user must be in a course for it to work.
1.191 harris41 15488:
15489: =item *
15490:
1.243 albertel 15491: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15492:
15493: =item *
15494:
1.243 albertel 15495: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15496: a random seed, all arguments are optional, if they aren't sent it uses the
15497: environment to derive them. Note: if symb isn't sent and it can't get one
15498: from &symbread it will use the current time as its return value
1.191 harris41 15499:
15500: =item *
15501:
1.243 albertel 15502: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15503: unfakeable, receipt
1.191 harris41 15504:
15505: =item *
15506:
1.620 albertel 15507: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15508:
15509: =item *
15510:
1.243 albertel 15511: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15512:
15513: =item *
15514:
1.243 albertel 15515: 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 15516:
15517: =item *
15518:
1.243 albertel 15519: 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 15520:
15521: =item *
15522:
1.243 albertel 15523: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15524:
15525: =item *
15526:
1.243 albertel 15527: devalidate($symb) : devalidate temporary spreadsheet calculations,
15528: forcing spreadsheet to reevaluate the resource scores next time.
15529:
1.1172.2.13 raeburn 15530: =item *
15531:
15532: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15533: when viewing in course context.
15534:
15535: input: six args -- filename (decluttered), course number, course domain,
15536: url, symb (if registered) and group (if this is a
15537: group item -- e.g., bulletin board, group page etc.).
15538:
15539: output: array of five scalars --
15540: $cfile -- url for file editing if editable on current server
15541: $home -- homeserver of resource (i.e., for author if published,
15542: or course if uploaded.).
15543: $switchserver -- 1 if server switch will be needed.
15544: $forceedit -- 1 if icon/link should be to go to edit mode
15545: $forceview -- 1 if icon/link should be to go to view mode
15546:
15547: =item *
15548:
15549: is_course_upload($file,$cnum,$cdom)
15550:
15551: Used in course context to determine if current file was uploaded to
15552: the course (i.e., would be found in /userfiles/docs on the course's
15553: homeserver.
15554:
15555: input: 3 args -- filename (decluttered), course number and course domain.
15556: output: boolean -- 1 if file was uploaded.
15557:
1.243 albertel 15558: =back
15559:
15560: =head2 Storing/Retreiving Data
15561:
15562: =over 4
1.191 harris41 15563:
15564: =item *
15565:
1.1172.2.64 raeburn 15566: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15567: permanently for this url; hashref needs to be given and should be a \%hashname;
15568: the remaining args aren't required and if they aren't passed or are '' they will
15569: be derived from the env (with the exception of $laststore, which is an
15570: optional arg used when a user's submission is stored in grading).
15571: $laststore is $version=$timestamp, where $version is the most recent version
15572: number retrieved for the corresponding $symb in the $namespace db file, and
15573: $timestamp is the timestamp for that transaction (UNIX time).
15574: $laststore is currently only passed when cstore() is called by
15575: structuretags::finalize_storage().
1.191 harris41 15576:
15577: =item *
15578:
1.1172.2.64 raeburn 15579: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15580: but uses critical subroutine
1.191 harris41 15581:
15582: =item *
15583:
1.243 albertel 15584: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15585: all args are optional
1.191 harris41 15586:
15587: =item *
15588:
1.717 albertel 15589: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15590: dumps the complete (or key matching regexp) namespace into a hash
15591: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15592: normally &store()ed into
15593:
15594: $range should be either an integer '100' (give me the first 100
15595: matching records)
15596: or be two integers sperated by a - with no spaces
15597: '30-50' (give me the 30th through the 50th matching
15598: records)
15599:
15600:
15601: =item *
15602:
1.1172.2.59 raeburn 15603: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15604: replaces a &store() version of data with a replacement set of data
15605: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15606: reference. If $tolog is true, the transaction is logged in the courselog
15607: with an action=PUTSTORE.
1.717 albertel 15608:
15609: =item *
15610:
1.243 albertel 15611: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15612: works very similar to store/cstore, but all data is stored in a
15613: temporary location and can be reset using tmpreset, $storehash should
15614: be a hash reference, returns nothing on success
1.191 harris41 15615:
15616: =item *
15617:
1.243 albertel 15618: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15619: similar to restore, but all data is stored in a temporary location and
15620: can be reset using tmpreset. Returns a hash of values on success,
15621: error string otherwise.
1.191 harris41 15622:
15623: =item *
15624:
1.243 albertel 15625: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15626: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15627:
15628: =item *
15629:
1.243 albertel 15630: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15631: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15632:
15633: =item *
15634:
1.243 albertel 15635: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15636: namesp ($udom and $uname are optional)
1.191 harris41 15637:
15638: =item *
15639:
1.702 albertel 15640: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15641: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15642: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15643:
1.702 albertel 15644: $range should be either an integer '100' (give me the first 100
15645: matching records)
15646: or be two integers sperated by a - with no spaces
15647: '30-50' (give me the 30th through the 50th matching
15648: records)
1.449 matthew 15649: =item *
15650:
15651: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15652: $store can be a scalar, an array reference, or if the amount to be
15653: incremented is > 1, a hash reference.
15654:
15655: ($udom and $uname are optional)
1.191 harris41 15656:
15657: =item *
15658:
1.243 albertel 15659: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15660: ($udom and $uname are optional)
1.191 harris41 15661:
15662: =item *
15663:
1.243 albertel 15664: cput($namespace,$storehash,$udom,$uname) : critical put
15665: ($udom and $uname are optional)
1.191 harris41 15666:
15667: =item *
15668:
1.748 albertel 15669: newput($namespace,$storehash,$udom,$uname) :
15670:
15671: Attempts to store the items in the $storehash, but only if they don't
15672: currently exist, if this succeeds you can be certain that you have
15673: successfully created a new key value pair in the $namespace db.
15674:
15675:
15676: Args:
15677: $namespace: name of database to store values to
15678: $storehash: hashref to store to the db
15679: $udom: (optional) domain of user containing the db
15680: $uname: (optional) name of user caontaining the db
15681:
15682: Returns:
15683: 'ok' -> succeeded in storing all keys of $storehash
15684: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15685: least <key> already existed in the db (other
15686: requested keys may also already exist)
1.967 bisitz 15687: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15688: 'con_lost' -> unable to contact request server
15689: 'refused' -> action was not allowed by remote machine
15690:
15691:
15692: =item *
15693:
1.243 albertel 15694: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15695: reference filled in from namesp (encrypts the return communication)
15696: ($udom and $uname are optional)
1.191 harris41 15697:
15698: =item *
15699:
1.243 albertel 15700: log($udom,$name,$home,$message) : write to permanent log for user; use
15701: critical subroutine
15702:
1.806 raeburn 15703: =item *
15704:
1.860 raeburn 15705: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15706: array reference filled in from namespace found in domain level on either
15707: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15708:
15709: =item *
15710:
1.860 raeburn 15711: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15712: domain level either on specified domain server ($uhome) or primary domain
15713: server ($udom and $uhome are optional)
1.806 raeburn 15714:
1.943 raeburn 15715: =item *
15716:
1.1172.2.35 raeburn 15717: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15718: for: authentication, language, quotas, timezone, date locale, and portal URL in
15719: the target domain.
15720:
15721: May also include additional key => value pairs for the following groups:
15722:
15723: =over
15724:
15725: =item
15726: disk quotas (MB allocated by default to portfolios and authoring spaces).
15727:
15728: =over
15729:
15730: =item defaultquota, authorquota
15731:
15732: =back
15733:
15734: =item
15735: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15736: portfolio for users).
15737:
15738: =over
15739:
15740: =item
15741: aboutme, blog, webdav, portfolio
15742:
15743: =back
15744:
15745: =item
15746: requestcourses: ability to request courses, and how requests are processed.
15747:
15748: =over
15749:
15750: =item
1.1172.2.37 raeburn 15751: official, unofficial, community, textbook
1.1172.2.35 raeburn 15752:
15753: =back
15754:
15755: =item
15756: inststatus: types of institutional affiliation, and order in which they are displayed.
15757:
15758: =over
15759:
15760: =item
1.1172.2.44 raeburn 15761: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15762:
15763: =back
15764:
15765: =item
15766: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15767: for course's uploaded content.
15768:
15769: =over
15770:
15771: =item
1.1172.2.68 raeburn 15772: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15773: communityquota, textbookquota
1.1172.2.35 raeburn 15774:
15775: =back
15776:
15777: =item
15778: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15779: on your servers.
15780:
15781: =over
15782:
15783: =item
15784: remotesessions, hostedsessions
15785:
15786: =back
15787:
15788: =back
15789:
15790: In cases where a domain coordinator has never used the "Set Domain Configuration"
15791: utility to create a configuration.db file on a domain's primary library server
15792: only the following domain defaults: auth_def, auth_arg_def, lang_def
15793: -- corresponding values are authentication type (internal, krb4, krb5,
15794: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15795: will be available. Values are retrieved from cache (if current), unless the
15796: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15797: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15798:
15799: Typical usage:
1.943 raeburn 15800:
1.1172.2.35 raeburn 15801: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15802:
1.243 albertel 15803: =back
15804:
15805: =head2 Network Status Functions
15806:
15807: =over 4
1.191 harris41 15808:
15809: =item *
15810:
1.1137 raeburn 15811: dirlist() : return directory list based on URI (first arg).
15812:
15813: Inputs: 1 required, 5 optional.
15814:
15815: =over
15816:
15817: =item
15818: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15819:
15820: =item
15821: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15822:
15823: =item
15824: $username - username of user/course to be listed. Extracted from $uri if absent.
15825:
15826: =item
15827: $getpropath - boolean: 1 if prepend path using &propath().
15828:
15829: =item
15830: $getuserdir - boolean: 1 if prepend path for "userfiles".
15831:
15832: =item
15833: $alternateRoot - path to prepend in place of path from $uri.
15834:
15835: =back
15836:
15837: Returns: Array of up to two items.
15838:
15839: =over
15840:
15841: a reference to an array of files/subdirectories
15842:
15843: =over
15844:
15845: Each element in the array of files/subdirectories is a & separated list of
15846: item name and the result of running stat on the item. If dirlist was requested
15847: for a file instead of a directory, the item name will be ''. For a directory
15848: listing, if the item is a metadata file, the element will end &N&M
15849: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15850: default copyright set (1).
15851:
15852: =back
15853:
15854: a scalar containing error condition (if encountered).
15855:
15856: =over
15857:
15858: =item
15859: no_host (no homeserver identified for $username:$domain).
15860:
15861: =item
15862: no_such_host (server contacted for listing not identified as valid host).
15863:
15864: =item
15865: con_lost (connection to remote server failed).
15866:
15867: =item
15868: refused (invalid $username:$domain received on lond side).
15869:
15870: =item
15871: no_such_dir (directory at specified path on lond side does not exist).
15872:
15873: =item
15874: empty (directory at specified path on lond side is empty).
15875:
15876: =over
15877:
15878: This is currently not encountered because the &ls3, &ls2,
15879: &ls (_handler) routines on the lond side do not filter out
15880: . and .. from a directory listing.
15881:
15882: =back
15883:
15884: =back
15885:
15886: =back
1.191 harris41 15887:
15888: =item *
15889:
1.243 albertel 15890: spareserver() : find server with least workload from spare.tab
15891:
1.986 foxr 15892:
15893: =item *
15894:
15895: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15896: if there is no corresponding loncapa host.
15897:
1.243 albertel 15898: =back
15899:
1.986 foxr 15900:
1.243 albertel 15901: =head2 Apache Request
15902:
15903: =over 4
1.191 harris41 15904:
15905: =item *
15906:
1.243 albertel 15907: ssi($url,%hash) : server side include, does a complete request cycle on url to
15908: localhost, posts hash
15909:
15910: =back
15911:
15912: =head2 Data to String to Data
15913:
15914: =over 4
1.191 harris41 15915:
15916: =item *
15917:
1.243 albertel 15918: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15919: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15920:
15921: =item *
15922:
1.243 albertel 15923: hashref2str($hashref) : convert a hashref into a string complete with
15924: escaping and '=' and '&' separators, supports elements that are
15925: arrayrefs and hashrefs
1.191 harris41 15926:
15927: =item *
15928:
1.243 albertel 15929: arrayref2str($arrayref) : convert an arrayref into a string complete
15930: with escaping and '&' separators, supports elements that are arrayrefs
15931: and hashrefs
1.191 harris41 15932:
15933: =item *
15934:
1.243 albertel 15935: str2hash($string) : convert string to hash using unescaping and
15936: splitting on '=' and '&', supports elements that are arrayrefs and
15937: hashrefs
1.191 harris41 15938:
15939: =item *
15940:
1.243 albertel 15941: str2array($string) : convert string to hash using unescaping and
15942: splitting on '&', supports elements that are arrayrefs and hashrefs
15943:
15944: =back
15945:
15946: =head2 Logging Routines
15947:
15948:
15949: These routines allow one to make log messages in the lonnet.log and
15950: lonnet.perm logfiles.
1.191 harris41 15951:
1.1119 foxr 15952: =over 4
15953:
1.191 harris41 15954: =item *
15955:
1.243 albertel 15956: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15957:
15958: =item *
15959:
1.243 albertel 15960: logthis() : append message to the normal lonnet.log file, it gets
15961: preiodically rolled over and deleted.
1.191 harris41 15962:
15963: =item *
15964:
1.243 albertel 15965: logperm() : append a permanent message to lonnet.perm.log, this log
15966: file never gets deleted by any automated portion of the system, only
15967: messages of critical importance should go in here.
15968:
1.1119 foxr 15969:
1.243 albertel 15970: =back
15971:
15972: =head2 General File Helper Routines
15973:
15974: =over 4
1.191 harris41 15975:
15976: =item *
15977:
1.481 raeburn 15978: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15979: (a) files in /uploaded
15980: (i) If a local copy of the file exists -
15981: compares modification date of local copy with last-modified date for
15982: definitive version stored on home server for course. If local copy is
15983: stale, requests a new version from the home server and stores it.
15984: If the original has been removed from the home server, then local copy
15985: is unlinked.
15986: (ii) If local copy does not exist -
15987: requests the file from the home server and stores it.
15988:
15989: If $caller is 'uploadrep':
15990: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15991: for request for files originally uploaded via DOCS.
15992: - returns 'ok' if fresh local copy now available, -1 otherwise.
15993:
15994: Otherwise:
15995: This indicates a call from the content generation phase of the request.
15996: - returns the entire contents of the file or -1.
15997:
15998: (b) files in /res
15999: - returns the entire contents of a file or -1;
16000: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16001:
1.712 albertel 16002:
16003: =item *
16004:
16005: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16006: reference
16007:
16008: returns either a stat() list of data about the file or an empty list
16009: if the file doesn't exist or couldn't find out about it (connection
16010: problems or user unknown)
16011:
1.191 harris41 16012: =item *
16013:
1.243 albertel 16014: filelocation($dir,$file) : returns file system location of a file
16015: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16016: directory that relative $file lookups are to looked in ($dir of /a/dir
16017: and a file of ../bob will become /a/bob)
1.191 harris41 16018:
16019: =item *
16020:
16021: hreflocation($dir,$file) : returns file system location or a URL; same as
16022: filelocation except for hrefs
16023:
16024: =item *
16025:
1.1172.2.49 raeburn 16026: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16027: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16028:
1.243 albertel 16029: =back
16030:
1.608 albertel 16031: =head2 Usererfile file routines (/uploaded*)
16032:
16033: =over 4
16034:
16035: =item *
16036:
16037: userfileupload(): main rotine for putting a file in a user or course's
16038: filespace, arguments are,
16039:
1.620 albertel 16040: formname - required - this is the name of the element in $env where the
1.608 albertel 16041: filename, and the contents of the file to create/modifed exist
1.620 albertel 16042: the filename is in $env{'form.'.$formname.'.filename'} and the
16043: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16044: context - if coursedoc, store the file in the course of the active role
16045: of the current user;
16046: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16047: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16048: subdir - required - subdirectory to put the file in under ../userfiles/
16049: if undefined, it will be placed in "unknown"
16050:
16051: (This routine calls clean_filename() to remove any dangerous
16052: characters from the filename, and then calls finuserfileupload() to
16053: complete the transaction)
16054:
16055: returns either the url of the uploaded file (/uploaded/....) if successful
16056: and /adm/notfound.html if unsuccessful
16057:
16058: =item *
16059:
16060: clean_filename(): routine for cleaing a filename up for storage in
16061: userfile space, argument is:
16062:
16063: filename - proposed filename
16064:
16065: returns: the new clean filename
16066:
16067: =item *
16068:
1.1090 raeburn 16069: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16070: userspace, probably shouldn't be called directly
16071:
16072: docuname: username or courseid of destination for the file
16073: docudom: domain of user/course of destination for the file
16074: formname: same as for userfileupload()
1.1090 raeburn 16075: fname: filename (including subdirectories) for the file
16076: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16077: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16078: allfiles: reference to hash used to store objects found by parser
16079: codebase: reference to hash used for codebases of java objects found by parser
16080: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16081: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16082: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16083: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16084: context: if 'overwrite', will move the uploaded file from its temporary location to
16085: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16086: mimetype: reference to scalar to accommodate mime type determined
16087: from File::MMagic if $parser = parse.
1.608 albertel 16088:
16089: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16090: and /adm/notfound.html if unsuccessful (or an error message if context
16091: was 'overwrite').
16092:
1.608 albertel 16093:
16094: =item *
16095:
16096: renameuserfile(): renames an existing userfile to a new name
16097:
16098: Args:
16099: docuname: username or courseid of destination for the file
16100: docudom: domain of user/course of destination for the file
16101: old: current file name (including any subdirs under userfiles)
16102: new: desired file name (including any subdirs under userfiles)
16103:
16104: =item *
16105:
16106: mkdiruserfile(): creates a directory is a userfiles dir
16107:
16108: Args:
16109: docuname: username or courseid of destination for the file
16110: docudom: domain of user/course of destination for the file
16111: dir: dir to create (including any subdirs under userfiles)
16112:
16113: =item *
16114:
16115: removeuserfile(): removes a file that exists in userfiles
16116:
16117: Args:
16118: docuname: username or courseid of destination for the file
16119: docudom: domain of user/course of destination for the file
16120: fname: filname to delete (including any subdirs under userfiles)
16121:
16122: =item *
16123:
16124: removeuploadedurl(): convience function for removeuserfile()
16125:
16126: Args:
16127: url: a full /uploaded/... url to delete
16128:
1.747 albertel 16129: =item *
16130:
16131: get_portfile_permissions():
16132: Args:
16133: domain: domain of user or course contain the portfolio files
16134: user: name of user or num of course contain the portfolio files
16135: Returns:
16136: hashref of a dump of the proper file_permissions.db
16137:
16138:
16139: =item *
16140:
16141: get_access_controls():
16142:
16143: Args:
16144: current_permissions: the hash ref returned from get_portfile_permissions()
16145: group: (optional) the group you want the files associated with
16146: file: (optional) the file you want access info on
16147:
16148: Returns:
1.749 raeburn 16149: a hash (keys are file names) of hashes containing
16150: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16151: values are XML containing access control settings (see below)
1.747 albertel 16152:
16153: Internal notes:
16154:
1.749 raeburn 16155: access controls are stored in file_permissions.db as key=value pairs.
16156: key -> path to file/file_name\0uniqueID:scope_end_start
16157: where scope -> public,guest,course,group,domains or users.
16158: end -> UNIX time for end of access (0 -> no end date)
16159: start -> UNIX time for start of access
16160:
16161: value -> XML description of access control
16162: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16163: <start></start>
16164: <end></end>
16165:
16166: <password></password> for scope type = guest
16167:
16168: <domain></domain> for scope type = course or group
16169: <number></number>
16170: <roles id="">
16171: <role></role>
16172: <access></access>
16173: <section></section>
16174: <group></group>
16175: </roles>
16176:
16177: <dom></dom> for scope type = domains
16178:
16179: <users> for scope type = users
16180: <user>
16181: <uname></uname>
16182: <udom></udom>
16183: </user>
16184: </users>
16185: </scope>
16186:
16187: Access data is also aggregated for each file in an additional key=value pair:
16188: key -> path to file/file_name\0accesscontrol
16189: value -> reference to hash
16190: hash contains key = value pairs
16191: where key = uniqueID:scope_end_start
16192: value = UNIX time record was last updated
16193:
16194: Used to improve speed of look-ups of access controls for each file.
16195:
16196: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16197:
1.1172.2.13 raeburn 16198: =item *
16199:
1.749 raeburn 16200: modify_access_controls():
16201:
16202: Modifies access controls for a portfolio file
16203: Args
16204: 1. file name
16205: 2. reference to hash of required changes,
16206: 3. domain
16207: 4. username
16208: where domain,username are the domain of the portfolio owner
16209: (either a user or a course)
16210:
16211: Returns:
16212: 1. result of additions or updates ('ok' or 'error', with error message).
16213: 2. result of deletions ('ok' or 'error', with error message).
16214: 3. reference to hash of any new or updated access controls.
16215: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16216: key = integer (inbound ID)
1.1172.2.13 raeburn 16217: value = uniqueID
16218:
16219: =item *
16220:
16221: get_timebased_id():
16222:
16223: Attempts to get a unique timestamp-based suffix for use with items added to a
16224: course via the Course Editor (e.g., folders, composite pages,
16225: group bulletin boards).
16226:
16227: Args: (first three required; six others optional)
16228:
16229: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16230: docssequence, or name of group
16231:
16232: 2. keyid (alphanumeric): name of temporary locking key in hash,
16233: e.g., num, boardids
16234:
16235: 3. namespace: name of gdbm file used to store suffixes already assigned;
16236: file will be named nohist_namespace.db
16237:
16238: 4. cdom: domain of course; default is current course domain from %env
16239:
16240: 5. cnum: course number; default is current course number from %env
16241:
16242: 6. idtype: set to concat if an additional digit is to be appended to the
16243: unix timestamp to form the suffix, if the plain timestamp is already
16244: in use. Default is to not do this, but simply increment the unix
16245: timestamp by 1 until a unique key is obtained.
16246:
16247: 7. who: holder of locking key; defaults to user:domain for user.
16248:
16249: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16250: retrying); default is 3.
16251:
16252: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16253:
16254: Returns:
16255:
16256: 1. suffix obtained (numeric)
16257:
16258: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16259:
16260: 3. error: contains (localized) error message if an error occurred.
16261:
1.747 albertel 16262:
1.608 albertel 16263: =back
16264:
1.243 albertel 16265: =head2 HTTP Helper Routines
16266:
16267: =over 4
16268:
1.191 harris41 16269: =item *
16270:
16271: escape() : unpack non-word characters into CGI-compatible hex codes
16272:
16273: =item *
16274:
16275: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16276:
1.243 albertel 16277: =back
16278:
16279: =head1 PRIVATE SUBROUTINES
16280:
16281: =head2 Underlying communication routines (Shouldn't call)
16282:
16283: =over 4
16284:
16285: =item *
16286:
16287: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16288:
16289: =item *
16290:
16291: reply() : uses subreply to send a message to remote machine, logs all failures
16292:
16293: =item *
16294:
16295: critical() : passes a critical message to another server; if cannot
16296: get through then place message in connection buffer directory and
16297: returns con_delayed, if incapable of saving message, returns
16298: con_failed
16299:
16300: =item *
16301:
16302: reconlonc() : tries to reconnect lonc client processes.
16303:
16304: =back
16305:
16306: =head2 Resource Access Logging
16307:
16308: =over 4
16309:
16310: =item *
16311:
16312: flushcourselogs() : flush (save) buffer logs and access logs
16313:
16314: =item *
16315:
16316: courselog($what) : save message for course in hash
16317:
16318: =item *
16319:
16320: courseacclog($what) : save message for course using &courselog(). Perform
16321: special processing for specific resource types (problems, exams, quizzes, etc).
16322:
1.191 harris41 16323: =item *
16324:
16325: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16326: as a PerlChildExitHandler
1.243 albertel 16327:
16328: =back
16329:
16330: =head2 Other
16331:
16332: =over 4
16333:
16334: =item *
16335:
16336: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16337:
16338: =back
16339:
16340: =cut
1.877 foxr 16341:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>