Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.149
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.149! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.148 2024/07/01 23:30:15 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: }
4554: }
4555: return @lines;
4556: }
4557:
1.493 albertel 4558: sub removeuploadedurl {
1.984 neumanie 4559: my ($url)=@_;
4560: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4561: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4562: }
4563:
4564: sub removeuserfile {
4565: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4566: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4567: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4568: if ($result eq 'ok') {
1.798 raeburn 4569: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4570: my $metafile = $fname.'.meta';
4571: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4572: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4573: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4574: my $sqlresult =
1.823 albertel 4575: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4576: 'portfolio_metadata',$group,
4577: 'delete');
1.798 raeburn 4578: }
4579: }
4580: return $result;
1.257 www 4581: }
1.15 www 4582:
1.530 albertel 4583: sub mkdiruserfile {
4584: my ($docuname,$docudom,$dir)=@_;
4585: my $home=&homeserver($docuname,$docudom);
4586: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4587: }
4588:
1.531 albertel 4589: sub renameuserfile {
4590: my ($docuname,$docudom,$old,$new)=@_;
4591: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4592: my $result = &reply("renameuserfile:$docudom:$docuname:".
4593: &escape("$old").':'.&escape("$new"),$home);
4594: if ($result eq 'ok') {
4595: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4596: my $oldmeta = $old.'.meta';
4597: my $newmeta = $new.'.meta';
4598: my $metaresult =
4599: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4600: my $url = "/uploaded/$docudom/$docuname/$old";
4601: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4602: my $sqlresult =
1.823 albertel 4603: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4604: 'portfolio_metadata',$group,
4605: 'delete');
1.798 raeburn 4606: }
4607: }
4608: return $result;
1.531 albertel 4609: }
4610:
1.14 www 4611: # ------------------------------------------------------------------------- Log
4612:
4613: sub log {
4614: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4615: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4616: }
4617:
4618: # ------------------------------------------------------------------ Course Log
1.352 www 4619: #
4620: # This routine flushes several buffers of non-mission-critical nature
4621: #
1.157 www 4622:
4623: sub flushcourselogs {
1.352 www 4624: &logthis('Flushing log buffers');
4625: #
4626: # course logs
4627: # This is a log of all transactions in a course, which can be used
4628: # for data mining purposes
4629: #
4630: # It also collects the courseid database, which lists last transaction
4631: # times and course titles for all courseids
4632: #
4633: my %courseidbuffer=();
1.921 raeburn 4634: foreach my $crsid (keys(%courselogs)) {
1.352 www 4635: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4636: &escape($courselogs{$crsid}),
4637: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4638: delete $courselogs{$crsid};
4639: } else {
4640: &logthis('Failed to flush log buffer for '.$crsid);
4641: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4642: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4643: " exceeded maximum size, deleting.</font>");
4644: delete $courselogs{$crsid};
4645: }
1.352 www 4646: }
1.920 raeburn 4647: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4648: 'description' => $coursedescrbuf{$crsid},
4649: 'inst_code' => $courseinstcodebuf{$crsid},
4650: 'type' => $coursetypebuf{$crsid},
4651: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4652: };
1.191 harris41 4653: }
1.352 www 4654: #
4655: # Write course id database (reverse lookup) to homeserver of courses
4656: # Is used in pickcourse
4657: #
1.840 albertel 4658: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4659: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4660: $courseidbuffer{$crs_home},
4661: $crs_home,'timeonly');
1.352 www 4662: }
4663: #
4664: # File accesses
4665: # Writes to the dynamic metadata of resources to get hit counts, etc.
4666: #
1.449 matthew 4667: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4668: if ($entry =~ /___count$/) {
4669: my ($dom,$name);
1.807 albertel 4670: ($dom,$name,undef)=
1.811 albertel 4671: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4672: if (! defined($dom) || $dom eq '' ||
4673: ! defined($name) || $name eq '') {
1.620 albertel 4674: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4675: #
4676: # FIXME 11/29/2021
4677: # Typo in rev. 1.458 (2003/12/09)??
4678: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4679: #
4680: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4681: # $dom and $name will always be null, so the &inc() call will default to storing this data
4682: # in a nohist_accesscount.db file for the user rather than the course.
4683: #
4684: # That said there is a lot of noise in the data being stored.
4685: # So counts for prtspool/ and adm/ etc. are recorded.
4686: #
4687: # A review of which items ending '___count' are written to %accesshash should likely be
4688: # made before deciding whether to set these to 'course.' instead of 'request.'
4689: #
4690: # Under the current scheme each user receives a nohist_accesscount.db file listing
4691: # accesses for things which are not published resources, regardless of course, and
4692: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4693: # anyone in the course for things which are not published resources.
4694: #
4695: # For an author, nohist_accesscount.db ends up having records for other items
4696: # mixed up with the legitimate access counts for the author's published resources.
4697: #
1.620 albertel 4698: $dom = $env{'request.'.$cid.'.domain'};
4699: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4700: }
1.450 matthew 4701: my $value = $accesshash{$entry};
4702: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4703: my %temphash=($url => $value);
1.449 matthew 4704: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4705: if ($result eq 'ok') {
4706: delete $accesshash{$entry};
4707: }
4708: } else {
1.811 albertel 4709: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4710: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4711: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4712: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4713: delete $accesshash{$entry};
4714: }
1.185 www 4715: }
1.191 harris41 4716: }
1.352 www 4717: #
4718: # Roles
4719: # Reverse lookup of user roles for course faculty/staff and co-authorship
4720: #
1.800 albertel 4721: foreach my $entry (keys(%userrolehash)) {
1.351 www 4722: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4723: split(/\:/,$entry);
4724: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4725: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4726: $rudom,$runame) eq 'ok') {
4727: delete $userrolehash{$entry};
4728: }
4729: }
1.662 raeburn 4730: #
1.1172.2.90 raeburn 4731: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4732: #
4733: my %domrolebuffer = ();
1.1000 raeburn 4734: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4735: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4736: if ($domrolebuffer{$rudom}) {
4737: $domrolebuffer{$rudom}.='&'.&escape($entry).
4738: '='.&escape($domainrolehash{$entry});
4739: } else {
4740: $domrolebuffer{$rudom}.=&escape($entry).
4741: '='.&escape($domainrolehash{$entry});
4742: }
4743: delete $domainrolehash{$entry};
4744: }
4745: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4746: my %servers;
4747: if (defined(&domain($dom,'primary'))) {
4748: my $primary=&domain($dom,'primary');
4749: my $hostname=&hostname($primary);
4750: $servers{$primary} = $hostname;
4751: } else {
4752: %servers = &get_servers($dom,'library');
4753: }
1.841 albertel 4754: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4755: if (&reply('domroleput:'.$dom.':'.
4756: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4757: last;
4758: } else {
1.841 albertel 4759: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4760: }
1.662 raeburn 4761: }
4762: }
1.186 www 4763: $dumpcount++;
1.157 www 4764: }
4765:
4766: sub courselog {
4767: my $what=shift;
1.158 www 4768: $what=time.':'.$what;
1.620 albertel 4769: unless ($env{'request.course.id'}) { return ''; }
4770: $coursedombuf{$env{'request.course.id'}}=
4771: $env{'course.'.$env{'request.course.id'}.'.domain'};
4772: $coursenumbuf{$env{'request.course.id'}}=
4773: $env{'course.'.$env{'request.course.id'}.'.num'};
4774: $coursehombuf{$env{'request.course.id'}}=
4775: $env{'course.'.$env{'request.course.id'}.'.home'};
4776: $coursedescrbuf{$env{'request.course.id'}}=
4777: $env{'course.'.$env{'request.course.id'}.'.description'};
4778: $courseinstcodebuf{$env{'request.course.id'}}=
4779: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4780: $courseownerbuf{$env{'request.course.id'}}=
4781: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4782: $coursetypebuf{$env{'request.course.id'}}=
4783: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4784: if (defined $courselogs{$env{'request.course.id'}}) {
4785: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4786: } else {
1.620 albertel 4787: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4788: }
1.620 albertel 4789: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4790: &flushcourselogs();
4791: }
1.158 www 4792: }
4793:
4794: sub courseacclog {
4795: my $fnsymb=shift;
1.620 albertel 4796: unless ($env{'request.course.id'}) { return ''; }
4797: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4798: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4799: $what.=':POST';
1.583 matthew 4800: # FIXME: Probably ought to escape things....
1.800 albertel 4801: foreach my $key (keys(%env)) {
4802: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4803: my $formitem = $1;
4804: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4805: $what.=':'.$formitem.'='.$env{$key};
4806: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4807: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4808: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4809: } else {
4810: $what.=':'.$formitem.'='.$env{$key};
4811: }
1.975 raeburn 4812: }
1.158 www 4813: }
1.191 harris41 4814: }
1.583 matthew 4815: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4816: # FIXME: We should not be depending on a form parameter that someone
4817: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4818: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4819: $what.= ':POST';
4820: # FIXME: Probably ought to escape things....
4821: foreach my $element ('courseexp','crsfulltext','crsrelated',
4822: 'crsdiscuss') {
1.620 albertel 4823: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4824: }
4825: }
1.158 www 4826: }
4827: &courselog($what);
1.149 www 4828: }
4829:
1.185 www 4830: sub countacc {
4831: my $url=&declutter(shift);
1.458 matthew 4832: return if (! defined($url) || $url eq '');
1.620 albertel 4833: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4834: #
4835: # Mark that this url was used in this course
4836: #
1.620 albertel 4837: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4838: #
4839: # Increase the access count for this resource in this child process
4840: #
1.281 www 4841: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4842: $accesshash{$key}++;
1.185 www 4843: }
1.349 www 4844:
1.361 www 4845: sub linklog {
4846: my ($from,$to)=@_;
4847: $from=&declutter($from);
4848: $to=&declutter($to);
4849: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4850: $accesshash{$to.'___'.$from.'___goto'}=1;
4851: }
1.1160 www 4852:
4853: sub statslog {
4854: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4855: if ($users<2) { return; }
4856: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4857: 'course' => $env{'request.course.id'},
4858: 'sections' => '"all"',
4859: 'num_students' => $users,
4860: 'part' => $part,
4861: 'symb' => $symb,
4862: 'mean_tries' => $av_attempts,
4863: 'deg_of_diff' => $degdiff});
4864: foreach my $key (keys(%dynstore)) {
4865: $accesshash{$key}=$dynstore{$key};
4866: }
4867: }
1.361 www 4868:
1.349 www 4869: sub userrolelog {
4870: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4871: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4872: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4873: $userrolehash
4874: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4875: =$tend.':'.$tstart;
1.662 raeburn 4876: }
1.1169 droeschl 4877: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4878: $userrolehash
4879: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4880: =$tend.':'.$tstart;
4881: }
1.1172.2.90 raeburn 4882: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4883: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4884: $domainrolehash
4885: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4886: = $tend.':'.$tstart;
4887: }
1.351 www 4888: }
4889:
1.957 raeburn 4890: sub courserolelog {
4891: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4892: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4893: my $cdom = $1;
4894: my $cnum = $2;
4895: my $sec = $3;
4896: my $namespace = 'rolelog';
4897: my %storehash = (
4898: role => $trole,
4899: start => $tstart,
4900: end => $tend,
4901: selfenroll => $selfenroll,
4902: context => $context,
4903: );
4904: if ($trole eq 'gr') {
4905: $namespace = 'groupslog';
4906: $storehash{'group'} = $sec;
4907: } else {
4908: $storehash{'section'} = $sec;
4909: }
4910: &write_log('course',$namespace,\%storehash,$delflag,$username,
4911: $domain,$cnum,$cdom);
4912: if (($trole ne 'st') || ($sec ne '')) {
4913: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4914: }
4915: }
4916: return;
4917: }
4918:
1.1172.2.9 raeburn 4919: sub domainrolelog {
4920: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4921: if ($area =~ m{^/($match_domain)/$}) {
4922: my $cdom = $1;
4923: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4924: my $namespace = 'rolelog';
4925: my %storehash = (
4926: role => $trole,
4927: start => $tstart,
4928: end => $tend,
4929: context => $context,
4930: );
4931: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4932: $domain,$domconfiguser,$cdom);
4933: }
4934: return;
4935:
4936: }
4937:
4938: sub coauthorrolelog {
4939: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4940: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4941: my $audom = $1;
4942: my $auname = $2;
4943: my $namespace = 'rolelog';
4944: my %storehash = (
4945: role => $trole,
4946: start => $tstart,
4947: end => $tend,
4948: context => $context,
4949: );
4950: &write_log('author',$namespace,\%storehash,$delflag,$username,
4951: $domain,$auname,$audom);
4952: }
4953: return;
4954: }
4955:
1.351 www 4956: sub get_course_adv_roles {
1.948 raeburn 4957: my ($cid,$codes) = @_;
1.620 albertel 4958: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4959: my %coursehash=&coursedescription($cid);
1.988 raeburn 4960: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4961: my %nothide=();
1.800 albertel 4962: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4963: if ($user !~ /:/) {
4964: $nothide{join(':',split(/[\@]/,$user))}=1;
4965: } else {
4966: $nothide{$user}=1;
4967: }
1.470 www 4968: }
1.1172.2.23 raeburn 4969: my @possdoms = ($coursehash{'domain'});
4970: if ($coursehash{'checkforpriv'}) {
4971: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4972: }
1.351 www 4973: my %returnhash=();
4974: my %dumphash=
4975: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4976: my $now=time;
1.997 raeburn 4977: my %privileged;
1.1000 raeburn 4978: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4979: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4980: if (($tstart) && ($tstart<0)) { next; }
4981: if (($tend) && ($tend<$now)) { next; }
4982: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4983: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4984: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4985: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4986: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4987: if ($role eq 'cr') { next; }
1.948 raeburn 4988: if ($codes) {
4989: if ($section) { $role .= ':'.$section; }
4990: if ($returnhash{$role}) {
4991: $returnhash{$role}.=','.$username.':'.$domain;
4992: } else {
4993: $returnhash{$role}=$username.':'.$domain;
4994: }
1.351 www 4995: } else {
1.988 raeburn 4996: my $key=&plaintext($role,$crstype);
1.973 bisitz 4997: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4998: if ($returnhash{$key}) {
4999: $returnhash{$key}.=','.$username.':'.$domain;
5000: } else {
5001: $returnhash{$key}=$username.':'.$domain;
5002: }
1.351 www 5003: }
1.948 raeburn 5004: }
1.400 www 5005: return %returnhash;
5006: }
5007:
5008: sub get_my_roles {
1.937 raeburn 5009: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5010: unless (defined($uname)) { $uname=$env{'user.name'}; }
5011: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5012: my (%dumphash,%nothide);
1.1086 raeburn 5013: if ($context eq 'userroles') {
1.1166 raeburn 5014: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5015: } else {
1.1172.2.23 raeburn 5016: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5017: if ($hidepriv) {
5018: my %coursehash=&coursedescription($udom.'_'.$uname);
5019: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5020: if ($user !~ /:/) {
5021: $nothide{join(':',split(/[\@]/,$user))} = 1;
5022: } else {
5023: $nothide{$user} = 1;
5024: }
5025: }
5026: }
1.858 raeburn 5027: }
1.400 www 5028: my %returnhash=();
5029: my $now=time;
1.999 raeburn 5030: my %privileged;
1.800 albertel 5031: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5032: my ($role,$tend,$tstart);
5033: if ($context eq 'userroles') {
1.1149 raeburn 5034: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5035: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5036: } else {
5037: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5038: }
1.400 www 5039: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5040: my $status = 'active';
1.939 raeburn 5041: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5042: $status = 'previous';
5043: }
5044: if (($tstart) && ($now<$tstart)) {
5045: $status = 'future';
5046: }
5047: if (ref($types) eq 'ARRAY') {
5048: if (!grep(/^\Q$status\E$/,@{$types})) {
5049: next;
5050: }
5051: } else {
5052: if ($status ne 'active') {
5053: next;
5054: }
5055: }
1.867 raeburn 5056: my ($rolecode,$username,$domain,$section,$area);
5057: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5058: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5059: (undef,$domain,$username,$section) = split(/\//,$area);
5060: } else {
5061: ($role,$username,$domain,$section) = split(/\:/,$entry);
5062: }
1.832 raeburn 5063: if (ref($roledoms) eq 'ARRAY') {
5064: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5065: next;
5066: }
5067: }
5068: if (ref($roles) eq 'ARRAY') {
5069: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5070: if ($role =~ /^cr\//) {
5071: if (!grep(/^cr$/,@{$roles})) {
5072: next;
5073: }
1.1104 raeburn 5074: } elsif ($role =~ /^gr\//) {
5075: if (!grep(/^gr$/,@{$roles})) {
5076: next;
5077: }
1.922 raeburn 5078: } else {
5079: next;
5080: }
1.832 raeburn 5081: }
1.867 raeburn 5082: }
1.937 raeburn 5083: if ($hidepriv) {
1.1172.2.23 raeburn 5084: my @privroles = ('dc','su');
1.999 raeburn 5085: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5086: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5087: } else {
1.1172.2.23 raeburn 5088: my $possdoms = [$domain];
5089: if (ref($roledoms) eq 'ARRAY') {
5090: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5091: }
1.1172.2.23 raeburn 5092: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5093: if (!$nothide{$username.':'.$domain}) {
5094: next;
5095: }
5096: }
1.937 raeburn 5097: }
5098: }
1.933 raeburn 5099: if ($withsec) {
5100: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5101: $tstart.':'.$tend;
5102: } else {
5103: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5104: }
1.832 raeburn 5105: }
1.373 www 5106: return %returnhash;
1.399 www 5107: }
5108:
1.1172.2.89 raeburn 5109: sub get_all_adhocroles {
5110: my ($dom) = @_;
5111: my @roles_by_num = ();
5112: my %domdefaults = &get_domain_defaults($dom);
5113: my (%description,%access_in_dom,%access_info);
5114: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5115: my $count = 0;
5116: my %domcurrent = %{$domdefaults{'adhocroles'}};
5117: my %ordered;
5118: foreach my $role (sort(keys(%domcurrent))) {
5119: my ($order,$desc,$access_in_dom);
5120: if (ref($domcurrent{$role}) eq 'HASH') {
5121: $order = $domcurrent{$role}{'order'};
5122: $desc = $domcurrent{$role}{'desc'};
5123: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5124: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5125: }
5126: if ($order eq '') {
5127: $order = $count;
5128: }
5129: $ordered{$order} = $role;
5130: if ($desc ne '') {
5131: $description{$role} = $desc;
5132: } else {
5133: $description{$role}= $role;
5134: }
5135: $count++;
5136: }
5137: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5138: push(@roles_by_num,$ordered{$item});
5139: }
5140: }
5141: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5142: }
5143:
5144: sub get_my_adhocroles {
5145: my ($cid,$checkreg) = @_;
5146: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5147: if ($env{'request.course.id'} eq $cid) {
5148: $cdom = $env{'course.'.$cid.'.domain'};
5149: $cnum = $env{'course.'.$cid.'.num'};
5150: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5151: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5152: $cdom = $1;
5153: $cnum = $2;
5154: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5155: $cdom,$cnum);
5156: }
5157: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5158: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5159: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5160: if ($rosterhash{$user} ne '') {
5161: my $type = (split(/:/,$rosterhash{$user}))[5];
5162: return ([],{}) if ($type eq 'auto');
5163: }
5164: }
5165: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5166: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5167: my $then=$env{'user.login.time'};
5168: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5169: if (!$update) {
5170: $update = $then;
5171: }
5172: my @liveroles;
5173: foreach my $role ('dh','da') {
5174: if ($env{"user.role.$role./$cdom/"}) {
5175: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5176: my $limit = $update;
5177: if ($env{'request.role'} eq "$role./$cdom/") {
5178: $limit = $then;
5179: }
5180: my $activerole = 1;
5181: if ($tstart && $tstart>$limit) { $activerole = 0; }
5182: if ($tend && $tend <$limit) { $activerole = 0; }
5183: if ($activerole) {
5184: push(@liveroles,$role);
5185: }
5186: }
5187: }
5188: if (@liveroles) {
1.1172.2.89 raeburn 5189: if (&homeserver($cnum,$cdom) ne 'no_host') {
5190: my ($accessref,$accessinfo,%access_in_dom);
5191: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5192: if (ref($roles_by_num) eq 'ARRAY') {
5193: if (@{$roles_by_num}) {
5194: my %settings;
5195: if ($env{'request.course.id'} eq $cid) {
5196: foreach my $envkey (keys(%env)) {
5197: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5198: $settings{$1} = $env{$envkey};
5199: }
5200: }
5201: } else {
5202: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5203: }
5204: my %setincrs;
5205: if ($settings{'internal.adhocaccess'}) {
5206: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5207: }
5208: my @statuses;
5209: if ($env{'environment.inststatus'}) {
5210: @statuses = split(/,/,$env{'environment.inststatus'});
5211: }
5212: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5213: if (ref($accessref) eq 'HASH') {
5214: %access_in_dom = %{$accessref};
5215: }
5216: foreach my $role (@{$roles_by_num}) {
5217: my ($curraccess,@okstatus,@personnel);
5218: if ($setincrs{$role}) {
5219: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5220: if ($curraccess eq 'status') {
5221: @okstatus = split(/\&/,$rest);
5222: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5223: @personnel = split(/\&/,$rest);
5224: }
5225: } else {
5226: $curraccess = $access_in_dom{$role};
5227: if (ref($accessinfo) eq 'HASH') {
5228: if ($curraccess eq 'status') {
5229: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5230: @okstatus = @{$accessinfo->{$role}};
5231: }
5232: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5233: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5234: @personnel = @{$accessinfo->{$role}};
5235: }
5236: }
5237: }
5238: }
5239: if ($curraccess eq 'none') {
5240: next;
5241: } elsif ($curraccess eq 'all') {
5242: push(@possroles,$role);
1.1172.2.90 raeburn 5243: } elsif ($curraccess eq 'dh') {
5244: if (grep(/^dh$/,@liveroles)) {
5245: push(@possroles,$role);
5246: } else {
5247: next;
5248: }
5249: } elsif ($curraccess eq 'da') {
5250: if (grep(/^da$/,@liveroles)) {
5251: push(@possroles,$role);
5252: } else {
5253: next;
5254: }
1.1172.2.89 raeburn 5255: } elsif ($curraccess eq 'status') {
5256: if (@okstatus) {
5257: if (!@statuses) {
5258: if (grep(/^default$/,@okstatus)) {
5259: push(@possroles,$role);
5260: }
5261: } else {
5262: foreach my $status (@okstatus) {
5263: if (grep(/^\Q$status\E$/,@statuses)) {
5264: push(@possroles,$role);
5265: last;
5266: }
5267: }
5268: }
5269: }
5270: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5271: if (grep(/^\Q$user\E$/,@personnel)) {
5272: if ($curraccess eq 'exc') {
5273: push(@possroles,$role);
5274: }
5275: } elsif ($curraccess eq 'inc') {
5276: push(@possroles,$role);
5277: }
5278: }
5279: }
5280: }
5281: }
5282: }
5283: }
5284: }
5285: }
5286: unless (ref($description) eq 'HASH') {
5287: if (ref($roles_by_num) eq 'ARRAY') {
5288: my %desc;
5289: map { $desc{$_} = $_; } (@{$roles_by_num});
5290: $description = \%desc;
5291: } else {
5292: $description = {};
5293: }
5294: }
5295: return (\@possroles,$description);
5296: }
5297:
1.399 www 5298: # ----------------------------------------------------- Frontpage Announcements
5299: #
5300: #
5301:
5302: sub postannounce {
5303: my ($server,$text)=@_;
1.844 albertel 5304: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5305: unless ($text=~/\w/) { $text=''; }
5306: return &reply('setannounce:'.&escape($text),$server);
5307: }
5308:
5309: sub getannounce {
1.448 albertel 5310:
1.1172.2.96 raeburn 5311: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5312: my $announcement='';
1.800 albertel 5313: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5314: close($fh);
1.399 www 5315: if ($announcement=~/\w/) {
5316: return
5317: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5318: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5319: } else {
5320: return '';
5321: }
5322: } else {
5323: return '';
5324: }
1.351 www 5325: }
1.353 www 5326:
5327: # ---------------------------------------------------------- Course ID routines
5328: # Deal with domain's nohist_courseid.db files
5329: #
5330:
5331: sub courseidput {
1.921 raeburn 5332: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5333: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5334: my $outcome;
5335: if ($caller eq 'timeonly') {
5336: my $cids = '';
5337: foreach my $item (keys(%$storehash)) {
5338: $cids.=&escape($item).'&';
5339: }
5340: $cids=~s/\&$//;
5341: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5342: $coursehome);
5343: } else {
5344: my $items = '';
5345: foreach my $item (keys(%$storehash)) {
5346: $items.= &escape($item).'='.
5347: &freeze_escape($$storehash{$item}).'&';
5348: }
5349: $items=~s/\&$//;
5350: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5351: $coursehome);
1.918 raeburn 5352: }
5353: if ($outcome eq 'unknown_cmd') {
5354: my $what;
5355: foreach my $cid (keys(%$storehash)) {
5356: $what .= &escape($cid).'=';
1.921 raeburn 5357: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5358: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5359: }
5360: $what =~ s/\:$/&/;
5361: }
5362: $what =~ s/\&$//;
5363: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5364: } else {
5365: return $outcome;
5366: }
1.353 www 5367: }
5368:
5369: sub courseiddump {
1.921 raeburn 5370: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5371: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5372: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5373: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5374: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5375: my $as_hash = 1;
5376: my %returnhash;
5377: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5378: my %libserv = &all_library();
5379: foreach my $tryserver (keys(%libserv)) {
5380: if ( ( $hostidflag == 1
5381: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5382: || (!defined($hostidflag)) ) {
5383:
1.918 raeburn 5384: if (($domfilter eq '') ||
5385: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5386: my $rep;
5387: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5388: $rep = &LONCAPA::Lond::dump_course_id_handler(
5389: join(":", (&host_domain($tryserver), $sincefilter,
5390: &escape($descfilter), &escape($instcodefilter),
5391: &escape($ownerfilter), &escape($coursefilter),
5392: &escape($typefilter), &escape($regexp_ok),
5393: $as_hash, &escape($selfenrollonly),
5394: &escape($catfilter), $showhidden, $caller,
5395: &escape($cloner), &escape($cc_clone), $cloneonly,
5396: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5397: &escape($creationcontext),$domcloner,$hasuniquecode,
5398: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5399: } else {
5400: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5401: $sincefilter.':'.&escape($descfilter).':'.
5402: &escape($instcodefilter).':'.&escape($ownerfilter).
5403: ':'.&escape($coursefilter).':'.&escape($typefilter).
5404: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5405: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5406: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5407: &escape($cc_clone).':'.$cloneonly.':'.
5408: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5409: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5410: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5411: }
5412:
1.918 raeburn 5413: my @pairs=split(/\&/,$rep);
5414: foreach my $item (@pairs) {
5415: my ($key,$value)=split(/\=/,$item,2);
5416: $key = &unescape($key);
5417: next if ($key =~ /^error: 2 /);
5418: my $result = &thaw_unescape($value);
5419: if (ref($result) eq 'HASH') {
5420: $returnhash{$key}=$result;
5421: } else {
1.921 raeburn 5422: my @responses = split(/:/,$value);
5423: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5424: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5425: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5426: }
1.1008 raeburn 5427: }
1.353 www 5428: }
5429: }
5430: }
5431: }
5432: return %returnhash;
5433: }
5434:
1.1055 raeburn 5435: sub courselastaccess {
5436: my ($cdom,$cnum,$hostidref) = @_;
5437: my %returnhash;
5438: if ($cdom && $cnum) {
5439: my $chome = &homeserver($cnum,$cdom);
5440: if ($chome ne 'no_host') {
5441: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5442: &extract_lastaccess(\%returnhash,$rep);
5443: }
5444: } else {
5445: if (!$cdom) { $cdom=''; }
5446: my %libserv = &all_library();
5447: foreach my $tryserver (keys(%libserv)) {
5448: if (ref($hostidref) eq 'ARRAY') {
5449: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5450: }
5451: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5452: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5453: &extract_lastaccess(\%returnhash,$rep);
5454: }
5455: }
5456: }
5457: return %returnhash;
5458: }
5459:
5460: sub extract_lastaccess {
5461: my ($returnhash,$rep) = @_;
5462: if (ref($returnhash) eq 'HASH') {
5463: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5464: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5465: $rep eq '') {
5466: my @pairs=split(/\&/,$rep);
5467: foreach my $item (@pairs) {
5468: my ($key,$value)=split(/\=/,$item,2);
5469: $key = &unescape($key);
5470: next if ($key =~ /^error: 2 /);
5471: $returnhash->{$key} = &thaw_unescape($value);
5472: }
5473: }
5474: }
5475: return;
5476: }
5477:
1.658 raeburn 5478: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5479:
5480: sub dcmailput {
1.685 raeburn 5481: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5482: my $status = &Apache::lonnet::critical(
1.740 www 5483: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5484: &escape($message),$server);
1.662 raeburn 5485: return $status;
5486: }
5487:
1.658 raeburn 5488: sub dcmaildump {
5489: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5490: my %returnhash=();
1.846 albertel 5491:
5492: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5493: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5494: &escape($enddate).':';
5495: my @esc_senders=map { &escape($_)} @$senders;
5496: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5497: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5498: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5499: if (($key) && ($value)) {
5500: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5501: }
5502: }
5503: }
5504: return %returnhash;
5505: }
1.662 raeburn 5506: # ---------------------------------------------------------- Domain roles
5507:
5508: sub get_domain_roles {
5509: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5510: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5511: $startdate = '.';
5512: }
1.1018 raeburn 5513: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5514: $enddate = '.';
5515: }
1.922 raeburn 5516: my $rolelist;
5517: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5518: $rolelist = join('&',@{$roles});
1.922 raeburn 5519: }
1.662 raeburn 5520: my %personnel = ();
1.841 albertel 5521:
5522: my %servers = &get_servers($dom,'library');
5523: foreach my $tryserver (keys(%servers)) {
5524: %{$personnel{$tryserver}}=();
5525: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5526: &escape($startdate).':'.
5527: &escape($enddate).':'.
5528: &escape($rolelist), $tryserver))) {
5529: my ($key,$value) = split(/\=/,$line,2);
5530: if (($key) && ($value)) {
5531: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5532: }
5533: }
1.662 raeburn 5534: }
5535: return %personnel;
5536: }
1.658 raeburn 5537:
1.1172.2.89 raeburn 5538: sub get_active_domroles {
5539: my ($dom,$roles) = @_;
5540: return () unless (ref($roles) eq 'ARRAY');
5541: my $now = time;
5542: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5543: my %domroles;
5544: foreach my $server (keys(%dompersonnel)) {
5545: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5546: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5547: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5548: }
5549: }
5550: return %domroles;
5551: }
5552:
1.1057 www 5553: # ----------------------------------------------------------- Interval timing
1.149 www 5554:
1.1153 www 5555: {
5556: # Caches needed for speedup of navmaps
5557: # We don't want to cache this for very long at all (5 seconds at most)
5558: #
5559: # The user for whom we cache
5560: my $cachedkey='';
5561: # The cached times for this user
5562: my %cachedtimes=();
5563: # When this was last done
1.1172.2.66 raeburn 5564: my $cachedtime='';
1.1153 www 5565:
5566: sub load_all_first_access {
1.1154 raeburn 5567: my ($uname,$udom)=@_;
1.1156 www 5568: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5569: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5570: return;
5571: }
5572: $cachedtime=time;
5573: $cachedkey=$uname.':'.$udom;
5574: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5575: }
5576:
1.504 albertel 5577: sub get_first_access {
1.1162 raeburn 5578: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5579: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5580: if ($argsymb) { $symb=$argsymb; }
5581: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5582: if ($argmap) { $map = $argmap; }
1.926 albertel 5583: if ($type eq 'course') {
5584: $res='course';
5585: } elsif ($type eq 'map') {
1.588 albertel 5586: $res=&symbread($map);
5587: } else {
5588: $res=$symb;
5589: }
1.1153 www 5590: &load_all_first_access($uname,$udom);
5591: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5592: }
5593:
5594: sub set_first_access {
1.1162 raeburn 5595: my ($type,$interval)=@_;
1.790 albertel 5596: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5597: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5598: if ($type eq 'course') {
5599: $res='course';
5600: } elsif ($type eq 'map') {
1.588 albertel 5601: $res=&symbread($map);
5602: } else {
5603: $res=$symb;
5604: }
1.1153 www 5605: $cachedkey='';
1.1162 raeburn 5606: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5607: if ($firstaccess) {
5608: &logthis("First access time already set ($firstaccess) when attempting ".
5609: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5610: "in $courseid");
5611: return 'already_set';
5612: } else {
1.1162 raeburn 5613: my $start = time;
5614: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5615: $udom,$uname);
5616: if ($putres eq 'ok') {
5617: &put('timerinterval',{"$courseid\0$res"=>$interval},
5618: $udom,$uname);
5619: &appenv(
5620: {
5621: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5622: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5623: }
5624: );
1.1172.2.97 raeburn 5625: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5626: $cachedtimes{"$courseid\0$res"} = $start;
5627: }
1.1172.2.102 raeburn 5628: } elsif ($putres ne 'refused') {
5629: &logthis("Result: $putres when attempting to set first access time ".
5630: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5631: }
5632: return $putres;
1.505 albertel 5633: }
5634: return 'already_set';
1.504 albertel 5635: }
1.1153 www 5636: }
1.1172.2.32 raeburn 5637:
5638: sub checkout {
5639: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5640: my $now=time;
5641: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5642: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5643: my $infostr=&escape(
5644: 'CHECKOUTTOKEN&'.
5645: $tuname.'&'.
5646: $tudom.'&'.
5647: $tcrsid.'&'.
5648: $symb.'&'.
1.1172.2.134 raeburn 5649: $now.'&'.$ip);
1.1172.2.32 raeburn 5650: my $token=&reply('tmpput:'.$infostr,$lonhost);
5651: if ($token=~/^error\:/) {
5652: &logthis("<font color=\"blue\">WARNING: ".
5653: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5654: "</font>");
5655: return '';
5656: }
5657:
5658: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5659: $token=~tr/a-z/A-Z/;
5660:
5661: my %infohash=('resource.0.outtoken' => $token,
5662: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5663: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5664:
5665: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5666: return '';
5667: } else {
5668: &logthis("<font color=\"blue\">WARNING: ".
5669: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5670: "</font>");
5671: }
5672:
5673: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5674: &escape('Checkout '.$infostr.' - '.
5675: $token)) ne 'ok') {
5676: return '';
5677: } else {
5678: &logthis("<font color=\"blue\">WARNING: ".
5679: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5680: "</font>");
5681: }
5682: return $token;
5683: }
5684:
5685: # ------------------------------------------------------------ Check in an item
5686:
5687: sub checkin {
5688: my $token=shift;
5689: my $now=time;
5690: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5691: $lonhost=~tr/A-Z/a-z/;
5692: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5693: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5694: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5695: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5696: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5697:
5698: unless (($tuname) && ($tudom)) {
5699: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5700: return '';
5701: }
5702:
5703: unless (&allowed('mgr',$tcrsid)) {
5704: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5705: $env{'user.name'}.' - '.$env{'user.domain'});
5706: return '';
5707: }
5708:
5709: my %infohash=('resource.0.intoken' => $token,
5710: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5711: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5712:
5713: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5714: return '';
5715: }
5716:
5717: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5718: &escape('Checkin - '.$token)) ne 'ok') {
5719: return '';
5720: }
5721:
5722: return ($symb,$tuname,$tudom,$tcrsid);
5723: }
5724:
1.110 www 5725: # --------------------------------------------- Set Expire Date for Spreadsheet
5726:
5727: sub expirespread {
5728: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5729: my $cid=$env{'request.course.id'};
1.110 www 5730: if ($cid) {
5731: my $now=time;
5732: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5733: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5734: $env{'course.'.$cid.'.num'}.
1.110 www 5735: ':nohist_expirationdates:'.
5736: &escape($key).'='.$now,
1.620 albertel 5737: $env{'course.'.$cid.'.home'})
1.110 www 5738: }
5739: return 'ok';
1.14 www 5740: }
5741:
1.109 www 5742: # ----------------------------------------------------- Devalidate Spreadsheets
5743:
5744: sub devalidate {
1.325 www 5745: my ($symb,$uname,$udom)=@_;
1.620 albertel 5746: my $cid=$env{'request.course.id'};
1.109 www 5747: if ($cid) {
1.391 matthew 5748: # delete the stored spreadsheets for
5749: # - the student level sheet of this user in course's homespace
5750: # - the assessment level sheet for this resource
5751: # for this user in user's homespace
1.553 albertel 5752: # - current conditional state info
1.325 www 5753: my $key=$uname.':'.$udom.':';
1.109 www 5754: my $status=
1.299 matthew 5755: &del('nohist_calculatedsheets',
1.391 matthew 5756: [$key.'studentcalc:'],
1.620 albertel 5757: $env{'course.'.$cid.'.domain'},
5758: $env{'course.'.$cid.'.num'})
1.133 albertel 5759: .' '.
5760: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5761: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5762: unless ($status eq 'ok ok') {
5763: &logthis('Could not devalidate spreadsheet '.
1.325 www 5764: $uname.' at '.$udom.' for '.
1.109 www 5765: $symb.': '.$status);
1.133 albertel 5766: }
1.553 albertel 5767: &delenv('user.state.'.$cid);
1.109 www 5768: }
5769: }
5770:
1.265 albertel 5771: sub get_scalar {
5772: my ($string,$end) = @_;
5773: my $value;
5774: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5775: $value = $1;
5776: } elsif ($$string =~ s/^([^&]*?)&//) {
5777: $value = $1;
5778: }
5779: return &unescape($value);
5780: }
5781:
5782: sub array2str {
5783: my (@array) = @_;
5784: my $result=&arrayref2str(\@array);
5785: $result=~s/^__ARRAY_REF__//;
5786: $result=~s/__END_ARRAY_REF__$//;
5787: return $result;
5788: }
5789:
1.204 albertel 5790: sub arrayref2str {
5791: my ($arrayref) = @_;
1.265 albertel 5792: my $result='__ARRAY_REF__';
1.204 albertel 5793: foreach my $elem (@$arrayref) {
1.265 albertel 5794: if(ref($elem) eq 'ARRAY') {
5795: $result.=&arrayref2str($elem).'&';
5796: } elsif(ref($elem) eq 'HASH') {
5797: $result.=&hashref2str($elem).'&';
5798: } elsif(ref($elem)) {
5799: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5800: } else {
5801: $result.=&escape($elem).'&';
5802: }
5803: }
5804: $result=~s/\&$//;
1.265 albertel 5805: $result .= '__END_ARRAY_REF__';
1.204 albertel 5806: return $result;
5807: }
5808:
1.168 albertel 5809: sub hash2str {
1.204 albertel 5810: my (%hash) = @_;
5811: my $result=&hashref2str(\%hash);
1.265 albertel 5812: $result=~s/^__HASH_REF__//;
5813: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5814: return $result;
5815: }
5816:
5817: sub hashref2str {
5818: my ($hashref)=@_;
1.265 albertel 5819: my $result='__HASH_REF__';
1.800 albertel 5820: foreach my $key (sort(keys(%$hashref))) {
5821: if (ref($key) eq 'ARRAY') {
5822: $result.=&arrayref2str($key).'=';
5823: } elsif (ref($key) eq 'HASH') {
5824: $result.=&hashref2str($key).'=';
5825: } elsif (ref($key)) {
1.265 albertel 5826: $result.='=';
1.800 albertel 5827: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5828: } else {
1.1132 raeburn 5829: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5830: }
5831:
1.800 albertel 5832: if(ref($hashref->{$key}) eq 'ARRAY') {
5833: $result.=&arrayref2str($hashref->{$key}).'&';
5834: } elsif(ref($hashref->{$key}) eq 'HASH') {
5835: $result.=&hashref2str($hashref->{$key}).'&';
5836: } elsif(ref($hashref->{$key})) {
1.265 albertel 5837: $result.='&';
1.800 albertel 5838: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5839: } else {
1.800 albertel 5840: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5841: }
5842: }
1.168 albertel 5843: $result=~s/\&$//;
1.265 albertel 5844: $result .= '__END_HASH_REF__';
1.168 albertel 5845: return $result;
5846: }
5847:
5848: sub str2hash {
1.265 albertel 5849: my ($string)=@_;
5850: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5851: return %$hash;
5852: }
5853:
5854: sub str2hashref {
1.168 albertel 5855: my ($string) = @_;
1.265 albertel 5856:
5857: my %hash;
5858:
5859: if($string !~ /^__HASH_REF__/) {
5860: if (! ($string eq '' || !defined($string))) {
5861: $hash{'error'}='Not hash reference';
5862: }
5863: return (\%hash, $string);
5864: }
5865:
5866: $string =~ s/^__HASH_REF__//;
5867:
5868: while($string !~ /^__END_HASH_REF__/) {
5869: #key
5870: my $key='';
5871: if($string =~ /^__HASH_REF__/) {
5872: ($key, $string)=&str2hashref($string);
5873: if(defined($key->{'error'})) {
5874: $hash{'error'}='Bad data';
5875: return (\%hash, $string);
5876: }
5877: } elsif($string =~ /^__ARRAY_REF__/) {
5878: ($key, $string)=&str2arrayref($string);
5879: if($key->[0] eq 'Array reference error') {
5880: $hash{'error'}='Bad data';
5881: return (\%hash, $string);
5882: }
5883: } else {
5884: $string =~ s/^(.*?)=//;
1.267 albertel 5885: $key=&unescape($1);
1.265 albertel 5886: }
5887: $string =~ s/^=//;
5888:
5889: #value
5890: my $value='';
5891: if($string =~ /^__HASH_REF__/) {
5892: ($value, $string)=&str2hashref($string);
5893: if(defined($value->{'error'})) {
5894: $hash{'error'}='Bad data';
5895: return (\%hash, $string);
5896: }
5897: } elsif($string =~ /^__ARRAY_REF__/) {
5898: ($value, $string)=&str2arrayref($string);
5899: if($value->[0] eq 'Array reference error') {
5900: $hash{'error'}='Bad data';
5901: return (\%hash, $string);
5902: }
5903: } else {
5904: $value=&get_scalar(\$string,'__END_HASH_REF__');
5905: }
5906: $string =~ s/^&//;
5907:
5908: $hash{$key}=$value;
1.204 albertel 5909: }
1.265 albertel 5910:
5911: $string =~ s/^__END_HASH_REF__//;
5912:
5913: return (\%hash, $string);
1.204 albertel 5914: }
5915:
5916: sub str2array {
1.265 albertel 5917: my ($string)=@_;
5918: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5919: return @$array;
5920: }
5921:
5922: sub str2arrayref {
1.204 albertel 5923: my ($string) = @_;
1.265 albertel 5924: my @array;
5925:
5926: if($string !~ /^__ARRAY_REF__/) {
5927: if (! ($string eq '' || !defined($string))) {
5928: $array[0]='Array reference error';
5929: }
5930: return (\@array, $string);
5931: }
5932:
5933: $string =~ s/^__ARRAY_REF__//;
5934:
5935: while($string !~ /^__END_ARRAY_REF__/) {
5936: my $value='';
5937: if($string =~ /^__HASH_REF__/) {
5938: ($value, $string)=&str2hashref($string);
5939: if(defined($value->{'error'})) {
5940: $array[0] ='Array reference error';
5941: return (\@array, $string);
5942: }
5943: } elsif($string =~ /^__ARRAY_REF__/) {
5944: ($value, $string)=&str2arrayref($string);
5945: if($value->[0] eq 'Array reference error') {
5946: $array[0] ='Array reference error';
5947: return (\@array, $string);
5948: }
5949: } else {
5950: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5951: }
5952: $string =~ s/^&//;
5953:
5954: push(@array, $value);
1.191 harris41 5955: }
1.265 albertel 5956:
5957: $string =~ s/^__END_ARRAY_REF__//;
5958:
5959: return (\@array, $string);
1.168 albertel 5960: }
5961:
1.167 albertel 5962: # -------------------------------------------------------------------Temp Store
5963:
1.168 albertel 5964: sub tmpreset {
5965: my ($symb,$namespace,$domain,$stuname) = @_;
5966: if (!$symb) {
5967: $symb=&symbread();
1.620 albertel 5968: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5969: }
5970: $symb=escape($symb);
5971:
1.620 albertel 5972: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5973: $namespace=~s/\//\_/g;
5974: $namespace=~s/\W//g;
5975:
1.620 albertel 5976: if (!$domain) { $domain=$env{'user.domain'}; }
5977: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5978: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5979: $stuname=&get_requestor_ip();
1.591 albertel 5980: }
1.1117 foxr 5981: my $path=LONCAPA::tempdir();
1.168 albertel 5982: my %hash;
5983: if (tie(%hash,'GDBM_File',
5984: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5985: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5986: foreach my $key (keys(%hash)) {
1.180 albertel 5987: if ($key=~ /:$symb/) {
1.168 albertel 5988: delete($hash{$key});
5989: }
5990: }
5991: }
5992: }
5993:
1.167 albertel 5994: sub tmpstore {
1.168 albertel 5995: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5996:
5997: if (!$symb) {
5998: $symb=&symbread();
1.620 albertel 5999: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6000: }
6001: $symb=escape($symb);
6002:
6003: if (!$namespace) {
6004: # I don't think we would ever want to store this for a course.
6005: # it seems this will only be used if we don't have a course.
1.620 albertel 6006: #$namespace=$env{'request.course.id'};
1.168 albertel 6007: #if (!$namespace) {
1.620 albertel 6008: $namespace=$env{'request.state'};
1.168 albertel 6009: #}
6010: }
6011: $namespace=~s/\//\_/g;
6012: $namespace=~s/\W//g;
1.620 albertel 6013: if (!$domain) { $domain=$env{'user.domain'}; }
6014: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6015: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6016: $stuname=&get_requestor_ip();
1.591 albertel 6017: }
1.168 albertel 6018: my $now=time;
6019: my %hash;
1.1117 foxr 6020: my $path=LONCAPA::tempdir();
1.168 albertel 6021: if (tie(%hash,'GDBM_File',
6022: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6023: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6024: $hash{"version:$symb"}++;
6025: my $version=$hash{"version:$symb"};
6026: my $allkeys='';
6027: foreach my $key (keys(%$storehash)) {
6028: $allkeys.=$key.':';
1.591 albertel 6029: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6030: }
6031: $hash{"$version:$symb:timestamp"}=$now;
6032: $allkeys.='timestamp';
6033: $hash{"$version:keys:$symb"}=$allkeys;
6034: if (untie(%hash)) {
6035: return 'ok';
6036: } else {
6037: return "error:$!";
6038: }
6039: } else {
6040: return "error:$!";
6041: }
6042: }
1.167 albertel 6043:
1.168 albertel 6044: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6045:
1.168 albertel 6046: sub tmprestore {
6047: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6048:
1.168 albertel 6049: if (!$symb) {
6050: $symb=&symbread();
1.620 albertel 6051: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6052: }
6053: $symb=escape($symb);
6054:
1.620 albertel 6055: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6056:
1.620 albertel 6057: if (!$domain) { $domain=$env{'user.domain'}; }
6058: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6059: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6060: $stuname=&get_requestor_ip();
1.591 albertel 6061: }
1.168 albertel 6062: my %returnhash;
6063: $namespace=~s/\//\_/g;
6064: $namespace=~s/\W//g;
6065: my %hash;
1.1117 foxr 6066: my $path=LONCAPA::tempdir();
1.168 albertel 6067: if (tie(%hash,'GDBM_File',
6068: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6069: &GDBM_READER(),0640)) {
1.168 albertel 6070: my $version=$hash{"version:$symb"};
6071: $returnhash{'version'}=$version;
6072: my $scope;
6073: for ($scope=1;$scope<=$version;$scope++) {
6074: my $vkeys=$hash{"$scope:keys:$symb"};
6075: my @keys=split(/:/,$vkeys);
6076: my $key;
6077: $returnhash{"$scope:keys"}=$vkeys;
6078: foreach $key (@keys) {
1.591 albertel 6079: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6080: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6081: }
6082: }
1.168 albertel 6083: if (!(untie(%hash))) {
6084: return "error:$!";
6085: }
6086: } else {
6087: return "error:$!";
6088: }
6089: return %returnhash;
1.167 albertel 6090: }
6091:
1.9 www 6092: # ----------------------------------------------------------------------- Store
6093:
6094: sub store {
1.1172.2.64 raeburn 6095: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6096: my $home='';
6097:
1.168 albertel 6098: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6099:
1.213 www 6100: $symb=&symbclean($symb);
1.122 albertel 6101: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6102:
1.620 albertel 6103: if (!$domain) { $domain=$env{'user.domain'}; }
6104: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6105:
6106: &devalidate($symb,$stuname,$domain);
1.109 www 6107:
6108: $symb=escape($symb);
1.187 www 6109: if (!$namespace) {
1.620 albertel 6110: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6111: return '';
6112: }
6113: }
1.620 albertel 6114: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6115:
1.1172.2.138 raeburn 6116: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6117: $$storehash{'host'}=$perlvar{'lonHostID'};
6118:
1.12 www 6119: my $namevalue='';
1.800 albertel 6120: foreach my $key (keys(%$storehash)) {
6121: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6122: }
1.12 www 6123: $namevalue=~s/\&$//;
1.187 www 6124: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6125: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6126: }
6127:
1.47 www 6128: # -------------------------------------------------------------- Critical Store
6129:
6130: sub cstore {
1.1172.2.64 raeburn 6131: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6132: my $home='';
6133:
1.168 albertel 6134: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6135:
1.213 www 6136: $symb=&symbclean($symb);
1.122 albertel 6137: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6138:
1.620 albertel 6139: if (!$domain) { $domain=$env{'user.domain'}; }
6140: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6141:
6142: &devalidate($symb,$stuname,$domain);
1.109 www 6143:
6144: $symb=escape($symb);
1.187 www 6145: if (!$namespace) {
1.620 albertel 6146: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6147: return '';
6148: }
6149: }
1.620 albertel 6150: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6151:
1.1172.2.138 raeburn 6152: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6153: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6154:
1.47 www 6155: my $namevalue='';
1.800 albertel 6156: foreach my $key (keys(%$storehash)) {
6157: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6158: }
1.47 www 6159: $namevalue=~s/\&$//;
1.187 www 6160: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6161: return critical
1.1172.2.64 raeburn 6162: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6163: }
6164:
1.9 www 6165: # --------------------------------------------------------------------- Restore
6166:
6167: sub restore {
1.124 www 6168: my ($symb,$namespace,$domain,$stuname) = @_;
6169: my $home='';
6170:
1.168 albertel 6171: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6172:
1.122 albertel 6173: if (!$symb) {
1.1172.2.26 raeburn 6174: return if ($namespace eq 'courserequests');
6175: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6176: } else {
1.1172.2.26 raeburn 6177: unless ($namespace eq 'courserequests') {
6178: $symb=&escape(&symbclean($symb));
6179: }
1.122 albertel 6180: }
1.188 www 6181: if (!$namespace) {
1.620 albertel 6182: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6183: return '';
6184: }
6185: }
1.620 albertel 6186: if (!$domain) { $domain=$env{'user.domain'}; }
6187: if (!$stuname) { $stuname=$env{'user.name'}; }
6188: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6189: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6190:
1.12 www 6191: my %returnhash=();
1.800 albertel 6192: foreach my $line (split(/\&/,$answer)) {
6193: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6194: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6195: }
1.75 www 6196: my $version;
6197: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6198: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6199: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6200: }
1.75 www 6201: }
1.13 www 6202: return %returnhash;
1.34 www 6203: }
6204:
6205: # ---------------------------------------------------------- Course Description
1.1118 foxr 6206: #
6207: #
1.34 www 6208:
6209: sub coursedescription {
1.731 albertel 6210: my ($courseid,$args)=@_;
1.34 www 6211: $courseid=~s/^\///;
1.49 www 6212: $courseid=~s/\_/\//g;
1.34 www 6213: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6214: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6215: my $normalid=$cdomain.'_'.$cnum;
6216: # need to always cache even if we get errors otherwise we keep
6217: # trying and trying and trying to get the course description.
6218: my %envhash=();
6219: my %returnhash=();
1.731 albertel 6220:
6221: my $expiretime=600;
6222: if ($env{'request.course.id'} eq $normalid) {
6223: $expiretime=120;
6224: }
6225:
6226: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6227: if (!$args->{'freshen_cache'}
6228: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6229: foreach my $key (keys(%env)) {
6230: next if ($key !~ /^\Q$prefix\E(.*)/);
6231: my ($setting) = $1;
6232: $returnhash{$setting} = $env{$key};
6233: }
6234: return %returnhash;
6235: }
6236:
1.1118 foxr 6237: # get the data again
6238:
1.731 albertel 6239: if (!$args->{'one_time'}) {
6240: $envhash{'course.'.$normalid.'.last_cache'}=time;
6241: }
1.811 albertel 6242:
1.34 www 6243: if ($chome ne 'no_host') {
1.302 albertel 6244: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6245: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6246: my $username = $env{'user.name'}; # Defult username
6247: if(defined $args->{'user'}) {
6248: $username = $args->{'user'};
6249: }
1.129 albertel 6250: $returnhash{'home'}= $chome;
6251: $returnhash{'domain'} = $cdomain;
6252: $returnhash{'num'} = $cnum;
1.741 raeburn 6253: if (!defined($returnhash{'type'})) {
6254: $returnhash{'type'} = 'Course';
6255: }
1.130 albertel 6256: while (my ($name,$value) = each %returnhash) {
1.53 www 6257: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6258: }
1.270 www 6259: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6260: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6261: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6262: $envhash{'course.'.$normalid.'.home'}=$chome;
6263: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6264: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6265: }
6266: }
1.731 albertel 6267: if (!$args->{'one_time'}) {
1.949 raeburn 6268: &appenv(\%envhash);
1.731 albertel 6269: }
1.302 albertel 6270: return %returnhash;
1.461 www 6271: }
6272:
1.1080 raeburn 6273: sub update_released_required {
6274: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6275: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6276: $cid = $env{'request.course.id'};
6277: $cdom = $env{'course.'.$cid.'.domain'};
6278: $cnum = $env{'course.'.$cid.'.num'};
6279: $chome = $env{'course.'.$cid.'.home'};
6280: }
6281: if ($needsrelease) {
6282: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6283: my $needsupdate;
6284: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6285: $needsupdate = 1;
6286: } else {
6287: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6288: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6289: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6290: $needsupdate = 1;
6291: }
6292: }
6293: if ($needsupdate) {
6294: my %needshash = (
6295: 'internal.releaserequired' => $needsrelease,
6296: );
6297: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6298: if ($putresult eq 'ok') {
6299: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6300: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6301: if (ref($crsinfo{$cid}) eq 'HASH') {
6302: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6303: &courseidput($cdom,\%crsinfo,$chome,'notime');
6304: }
6305: }
6306: }
6307: }
6308: return;
6309: }
6310:
1.461 www 6311: # -------------------------------------------------See if a user is privileged
6312:
6313: sub privileged {
1.1172.2.23 raeburn 6314: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6315: my $now = time;
1.1172.2.23 raeburn 6316: my $roles;
6317: if (ref($possroles) eq 'ARRAY') {
6318: $roles = $possroles;
6319: } else {
6320: $roles = ['dc','su'];
6321: }
6322: if (ref($possdomains) eq 'ARRAY') {
6323: my %privileged = &privileged_by_domain($possdomains,$roles);
6324: foreach my $dom (@{$possdomains}) {
6325: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6326: (ref($privileged{$dom}) eq 'HASH')) {
6327: foreach my $role (@{$roles}) {
6328: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6329: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6330: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6331: return 1 unless (($end && $end < $now) ||
6332: ($start && $start > $now));
6333: }
6334: }
6335: }
6336: }
6337: }
6338: } else {
6339: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6340: my $now = time;
1.1170 droeschl 6341:
1.1172.2.58 raeburn 6342: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6343: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6344: if (grep(/^\Q$trole\E$/,@{$roles})) {
6345: return 1 unless ($tend && $tend < $now)
6346: or ($tstart && $tstart > $now);
1.1170 droeschl 6347: }
1.1172.2.23 raeburn 6348: }
6349: }
1.461 www 6350: return 0;
1.9 www 6351: }
1.1 albertel 6352:
1.1172.2.23 raeburn 6353: sub privileged_by_domain {
6354: my ($domains,$roles) = @_;
6355: my %privileged = ();
6356: my $cachetime = 60*60*24;
6357: my $now = time;
6358: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6359: return %privileged;
6360: }
6361: foreach my $dom (@{$domains}) {
6362: next if (ref($privileged{$dom}) eq 'HASH');
6363: my $needroles;
6364: foreach my $role (@{$roles}) {
6365: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6366: if (defined($cached)) {
6367: if (ref($result) eq 'HASH') {
6368: $privileged{$dom}{$role} = $result;
6369: }
6370: } else {
6371: $needroles = 1;
6372: }
6373: }
6374: if ($needroles) {
6375: my %dompersonnel = &get_domain_roles($dom,$roles);
6376: $privileged{$dom} = {};
6377: foreach my $server (keys(%dompersonnel)) {
6378: if (ref($dompersonnel{$server}) eq 'HASH') {
6379: foreach my $item (keys(%{$dompersonnel{$server}})) {
6380: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6381: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6382: next if ($end && $end < $now);
6383: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6384: $dompersonnel{$server}{$item};
6385: }
6386: }
6387: }
6388: if (ref($privileged{$dom}) eq 'HASH') {
6389: foreach my $role (@{$roles}) {
6390: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6391: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6392: } else {
6393: my %hash = ();
6394: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6395: }
6396: }
6397: }
6398: }
6399: }
6400: return %privileged;
6401: }
6402:
1.103 harris41 6403: # -------------------------------------------------------- Get user privileges
1.11 www 6404:
6405: sub rolesinit {
1.1169 droeschl 6406: my ($domain, $username) = @_;
6407: my %userroles = ('user.login.time' => time);
6408: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6409:
6410: # firstaccess and timerinterval are related to timed maps/resources.
6411: # also, blocking can be triggered by an activating timer
6412: # it's saved in the user's %env.
6413: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6414: my %timerinterval = &dump('timerinterval', $domain, $username);
6415: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6416: %timerintchk, %timerintenv);
6417:
1.1162 raeburn 6418: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6419: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6420: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6421: }
1.1169 droeschl 6422:
1.1162 raeburn 6423: foreach my $key (keys(%timerinterval)) {
6424: my ($cid,$rest) = split(/\0/,$key);
6425: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6426: }
1.1169 droeschl 6427:
1.11 www 6428: my %allroles=();
1.1162 raeburn 6429: my %allgroups=();
1.11 www 6430:
1.1172.2.58 raeburn 6431: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6432: my $role = $rolesdump{$area};
6433: $area =~ s/\_\w\w$//;
6434:
6435: my ($trole, $tend, $tstart, $group_privs);
6436:
6437: if ($role =~ /^cr/) {
6438: # Custom role, defined by a user
6439: # e.g., user.role.cr/msu/smith/mynewrole
6440: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6441: $trole = $1;
6442: ($tend, $tstart) = split('_', $2);
6443: } else {
6444: $trole = $role;
6445: }
6446: } elsif ($role =~ m|^gr/|) {
6447: # Role of member in a group, defined within a course/community
6448: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6449: ($trole, $tend, $tstart) = split(/_/, $role);
6450: next if $tstart eq '-1';
6451: ($trole, $group_privs) = split(/\//, $trole);
6452: $group_privs = &unescape($group_privs);
6453: } else {
6454: # Just a normal role, defined in roles.tab
6455: ($trole, $tend, $tstart) = split(/_/,$role);
6456: }
6457:
6458: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6459: $username);
6460: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6461:
6462: # role expired or not available yet?
6463: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6464: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6465:
6466: next if $area eq '' or $trole eq '';
6467:
6468: my $spec = "$trole.$area";
6469: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6470:
6471: if ($trole =~ /^cr\//) {
6472: # Custom role, defined by a user
6473: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6474: } elsif ($trole eq 'gr') {
6475: # Role of a member in a group, defined within a course/community
6476: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6477: next;
6478: } else {
6479: # Normal role, defined in roles.tab
6480: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6481: }
6482:
6483: my $cid = $tdomain.'_'.$trest;
6484: unless ($firstaccchk{$cid}) {
6485: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6486: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6487: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6488: $coursetimerstarts{$cid}{$item};
6489: }
6490: }
6491: $firstaccchk{$cid} = 1;
6492: }
6493: unless ($timerintchk{$cid}) {
6494: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6495: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6496: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6497: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6498: }
1.12 www 6499: }
1.1169 droeschl 6500: $timerintchk{$cid} = 1;
1.191 harris41 6501: }
1.11 www 6502: }
1.1169 droeschl 6503:
1.1172.2.91 raeburn 6504: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6505: \%allroles, \%allgroups);
1.1169 droeschl 6506: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6507: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6508:
1.1162 raeburn 6509: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6510: }
6511:
1.567 raeburn 6512: sub set_arearole {
1.1172.2.19 raeburn 6513: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6514: unless ($nolog) {
1.567 raeburn 6515: # log the associated role with the area
1.1172.2.19 raeburn 6516: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6517: }
1.743 albertel 6518: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6519: }
6520:
6521: sub custom_roleprivs {
6522: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6523: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6524: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6525: if (&hostname($homsvr) ne '') {
1.567 raeburn 6526: my ($rdummy,$roledef)=
6527: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6528: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6529: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6530: if (defined($syspriv)) {
1.1043 raeburn 6531: if ($trest =~ /^$match_community$/) {
6532: $syspriv =~ s/bre\&S//;
6533: }
1.567 raeburn 6534: $$allroles{'cm./'}.=':'.$syspriv;
6535: $$allroles{$spec.'./'}.=':'.$syspriv;
6536: }
6537: if ($tdomain ne '') {
6538: if (defined($dompriv)) {
6539: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6540: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6541: }
6542: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6543: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6544: my $rolename = $1;
6545: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6546: }
1.567 raeburn 6547: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6548: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6549: }
6550: }
6551: }
6552: }
6553: }
6554:
1.1172.2.89 raeburn 6555: sub course_adhocrole_privs {
6556: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6557: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6558: if ($overrides{"internal.adhocpriv.$rolename"}) {
6559: my (%currprivs,%storeprivs);
6560: foreach my $item (split(/:/,$coursepriv)) {
6561: my ($priv,$restrict) = split(/\&/,$item);
6562: $currprivs{$priv} = $restrict;
6563: }
6564: my (%possadd,%possremove,%full);
6565: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6566: my ($priv,$restrict)=split(/\&/,$item);
6567: $full{$priv} = $restrict;
6568: }
6569: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6570: next if ($item eq '');
6571: my ($rule,$rest) = split(/=/,$item);
6572: next unless (($rule eq 'off') || ($rule eq 'on'));
6573: foreach my $priv (split(/:/,$rest)) {
6574: if ($priv ne '') {
6575: if ($rule eq 'off') {
6576: $possremove{$priv} = 1;
6577: } else {
6578: $possadd{$priv} = 1;
6579: }
6580: }
6581: }
6582: }
6583: foreach my $priv (sort(keys(%full))) {
6584: if (exists($currprivs{$priv})) {
6585: unless (exists($possremove{$priv})) {
6586: $storeprivs{$priv} = $currprivs{$priv};
6587: }
6588: } elsif (exists($possadd{$priv})) {
6589: $storeprivs{$priv} = $full{$priv};
6590: }
6591: }
6592: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6593: }
6594: return $coursepriv;
6595: }
6596:
1.678 raeburn 6597: sub group_roleprivs {
6598: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6599: my $access = 1;
6600: my $now = time;
6601: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6602: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6603: if ($access) {
1.811 albertel 6604: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6605: $$allgroups{$course}{$group} .=':'.$group_privs;
6606: }
6607: }
1.567 raeburn 6608:
6609: sub standard_roleprivs {
6610: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6611: if (defined($pr{$trole.':s'})) {
6612: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6613: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6614: }
6615: if ($tdomain ne '') {
6616: if (defined($pr{$trole.':d'})) {
6617: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6618: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6619: }
6620: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6621: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6622: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6623: }
6624: }
6625: }
6626:
6627: sub set_userprivs {
1.1064 raeburn 6628: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6629: my $author=0;
6630: my $adv=0;
1.1172.2.91 raeburn 6631: my $rar=0;
1.678 raeburn 6632: my %grouproles = ();
6633: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6634: my @groupkeys;
1.1000 raeburn 6635: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6636: push(@groupkeys,$role);
6637: }
6638: if (ref($groups_roles) eq 'HASH') {
6639: foreach my $key (keys(%{$groups_roles})) {
6640: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6641: push(@groupkeys,$key);
6642: }
6643: }
6644: }
6645: if (@groupkeys > 0) {
6646: foreach my $role (@groupkeys) {
6647: my ($trole,$area,$sec,$extendedarea);
6648: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6649: $trole = $1;
6650: $area = $2;
6651: $sec = $3;
6652: $extendedarea = $area.$sec;
6653: if (exists($$allgroups{$area})) {
6654: foreach my $group (keys(%{$$allgroups{$area}})) {
6655: my $spec = $trole.'.'.$extendedarea;
6656: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6657: $$allgroups{$area}{$group};
1.1064 raeburn 6658: }
1.678 raeburn 6659: }
6660: }
6661: }
6662: }
6663: }
1.800 albertel 6664: foreach my $group (keys(%grouproles)) {
6665: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6666: }
1.800 albertel 6667: foreach my $role (keys(%{$allroles})) {
6668: my %thesepriv;
1.941 raeburn 6669: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6670: foreach my $item (split(/:/,$$allroles{$role})) {
6671: if ($item ne '') {
6672: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6673: if ($restrictions eq '') {
6674: $thesepriv{$privilege}='F';
6675: } elsif ($thesepriv{$privilege} ne 'F') {
6676: $thesepriv{$privilege}.=$restrictions;
6677: }
6678: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6679: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6680: }
6681: }
6682: my $thesestr='';
1.1104 raeburn 6683: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6684: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6685: }
6686: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6687: }
1.1172.2.91 raeburn 6688: return ($author,$adv,$rar);
1.567 raeburn 6689: }
6690:
1.994 raeburn 6691: sub role_status {
1.1104 raeburn 6692: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6693: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6694: my ($one,$two) = split(m{\./},$rolekey,2);
6695: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6696: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6697: $$where = '/'.$two;
1.994 raeburn 6698: $$trolecode=$$role.'.'.$$where;
6699: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6700: $$tstatus='is';
1.1104 raeburn 6701: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6702: $$tstatus='future';
1.1034 raeburn 6703: if ($$tstart<$now) {
6704: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6705: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6706: my (%allroles,%allgroups,$group_privs,
6707: %groups_roles,@rolecodes);
1.1002 raeburn 6708: my %userroles = (
6709: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6710: );
1.1064 raeburn 6711: @rolecodes = ('cm');
1.1002 raeburn 6712: my $spec=$$role.'.'.$$where;
6713: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6714: if ($$role =~ /^cr\//) {
6715: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6716: push(@rolecodes,'cr');
1.1002 raeburn 6717: } elsif ($$role eq 'gr') {
1.1064 raeburn 6718: push(@rolecodes,$$role);
1.1002 raeburn 6719: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6720: $env{'user.name'});
1.1064 raeburn 6721: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6722: (undef,my $group_privs) = split(/\//,$trole);
6723: $group_privs = &unescape($group_privs);
6724: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6725: 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 6726: &get_groups_roles($tdomain,$trest,
6727: \%course_roles,\@rolecodes,
6728: \%groups_roles);
1.1002 raeburn 6729: } else {
1.1064 raeburn 6730: push(@rolecodes,$$role);
1.1002 raeburn 6731: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6732: }
1.1172.2.91 raeburn 6733: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6734: \%groups_roles);
1.1064 raeburn 6735: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6737: }
6738: }
1.1034 raeburn 6739: $$tstatus = 'is';
1.1002 raeburn 6740: }
1.994 raeburn 6741: }
6742: if ($$tend) {
1.1104 raeburn 6743: if ($$tend<$update) {
1.994 raeburn 6744: $$tstatus='expired';
6745: } elsif ($$tend<$now) {
6746: $$tstatus='will_not';
6747: }
6748: }
6749: }
6750: }
6751: }
6752:
1.1104 raeburn 6753: sub get_groups_roles {
6754: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6755: return unless((ref($cdom_courseroles) eq 'HASH') &&
6756: (ref($rolecodes) eq 'ARRAY') &&
6757: (ref($groups_roles) eq 'HASH'));
6758: if (keys(%{$cdom_courseroles}) > 0) {
6759: my ($cnum) = ($rest =~ /^($match_courseid)/);
6760: if ($cdom ne '' && $cnum ne '') {
6761: foreach my $key (keys(%{$cdom_courseroles})) {
6762: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6763: my $crsrole = $1;
6764: my $crssec = $2;
6765: if ($crsrole =~ /^cr/) {
6766: unless (grep(/^cr$/,@{$rolecodes})) {
6767: push(@{$rolecodes},'cr');
6768: }
6769: } else {
6770: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6771: push(@{$rolecodes},$crsrole);
6772: }
6773: }
6774: my $rolekey = "$crsrole./$cdom/$cnum";
6775: if ($crssec ne '') {
6776: $rolekey .= "/$crssec";
6777: }
6778: $rolekey .= './';
6779: $groups_roles->{$rolekey} = $rolecodes;
6780: }
6781: }
6782: }
6783: }
6784: return;
6785: }
6786:
6787: sub delete_env_groupprivs {
6788: my ($where,$courseroles,$possroles) = @_;
6789: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6790: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6791: unless (ref($courseroles->{$udom}) eq 'HASH') {
6792: %{$courseroles->{$udom}} =
6793: &get_my_roles('','','userroles',['active'],
6794: $possroles,[$udom],1);
6795: }
6796: if (ref($courseroles->{$udom}) eq 'HASH') {
6797: foreach my $item (keys(%{$courseroles->{$udom}})) {
6798: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6799: my $area = '/'.$cdom.'/'.$cnum;
6800: my $privkey = "user.priv.$crsrole.$area";
6801: if ($crssec ne '') {
6802: $privkey .= '/'.$crssec;
6803: }
6804: $privkey .= ".$area/$group";
6805: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6806: }
6807: }
6808: return;
6809: }
6810:
1.994 raeburn 6811: sub check_adhoc_privs {
1.1172.2.86 raeburn 6812: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6813: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6814: if ($sec) {
6815: $cckey .= '/'.$sec;
6816: }
1.1172.2.9 raeburn 6817: my $setprivs;
1.994 raeburn 6818: if ($env{$cckey}) {
6819: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6820: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6821: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6822: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6823: $setprivs = 1;
1.994 raeburn 6824: }
6825: } else {
1.1172.2.87 raeburn 6826: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6827: $setprivs = 1;
1.994 raeburn 6828: }
1.1172.2.9 raeburn 6829: return $setprivs;
1.994 raeburn 6830: }
6831:
6832: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6833: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6834: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6835: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6836: if ($sec ne '') {
6837: $area .= '/'.$sec;
6838: }
1.994 raeburn 6839: my $spec = $role.'.'.$area;
6840: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6841: $env{'user.name'},1);
1.1172.2.84 raeburn 6842: my %rolehash = ();
1.1172.2.89 raeburn 6843: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6844: my $rolename = $1;
1.1172.2.84 raeburn 6845: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6846: my %domdef = &get_domain_defaults($dcdom);
6847: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6848: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6849: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6850: }
6851: }
1.1172.2.84 raeburn 6852: } else {
6853: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6854: }
1.1172.2.91 raeburn 6855: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6856: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6857: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6858: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6859: &appenv( {'request.role' => $spec,
6860: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6861: 'request.course.sec' => $sec,
1.1088 raeburn 6862: }
6863: );
6864: my $tadv=0;
6865: if (&allowed('adv') eq 'F') { $tadv=1; }
6866: &appenv({'request.role.adv' => $tadv});
6867: }
1.994 raeburn 6868: }
6869:
1.12 www 6870: # --------------------------------------------------------------- get interface
6871:
6872: sub get {
1.131 albertel 6873: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6874: my $items='';
1.800 albertel 6875: foreach my $item (@$storearr) {
6876: $items.=&escape($item).'&';
1.191 harris41 6877: }
1.12 www 6878: $items=~s/\&$//;
1.620 albertel 6879: if (!$udomain) { $udomain=$env{'user.domain'}; }
6880: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6881: my $uhome=&homeserver($uname,$udomain);
6882:
1.133 albertel 6883: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6884: my @pairs=split(/\&/,$rep);
1.273 albertel 6885: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6886: return @pairs;
6887: }
1.15 www 6888: my %returnhash=();
1.42 www 6889: my $i=0;
1.800 albertel 6890: foreach my $item (@$storearr) {
6891: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6892: $i++;
1.191 harris41 6893: }
1.15 www 6894: return %returnhash;
1.27 www 6895: }
6896:
6897: # --------------------------------------------------------------- del interface
6898:
6899: sub del {
1.133 albertel 6900: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6901: my $items='';
1.800 albertel 6902: foreach my $item (@$storearr) {
6903: $items.=&escape($item).'&';
1.191 harris41 6904: }
1.984 neumanie 6905:
1.27 www 6906: $items=~s/\&$//;
1.620 albertel 6907: if (!$udomain) { $udomain=$env{'user.domain'}; }
6908: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6909: my $uhome=&homeserver($uname,$udomain);
6910: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6911: }
6912:
6913: # -------------------------------------------------------------- dump interface
6914:
1.1172.2.22 raeburn 6915: sub unserialize {
6916: my ($rep, $escapedkeys) = @_;
6917:
6918: return {} if $rep =~ /^error/;
6919:
6920: my %returnhash=();
6921: foreach my $item (split(/\&/,$rep)) {
6922: my ($key, $value) = split(/=/, $item, 2);
6923: $key = unescape($key) unless $escapedkeys;
6924: next if $key =~ /^error: 2 /;
6925: $returnhash{$key} = &thaw_unescape($value);
6926: }
6927: return \%returnhash;
6928: }
6929:
6930: # see Lond::dump_with_regexp
6931: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6932: sub dump {
1.1172.2.22 raeburn 6933: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6934: if (!$udomain) { $udomain=$env{'user.domain'}; }
6935: if (!$uname) { $uname=$env{'user.name'}; }
6936: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6937:
1.1172.2.55 raeburn 6938: if ($regexp) {
6939: $regexp=&escape($regexp);
6940: } else {
6941: $regexp='.';
6942: }
1.1172.2.22 raeburn 6943: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6944: # user is hosted on this machine
1.1172.2.55 raeburn 6945: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6946: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6947: return %{&unserialize($reply, $escapedkeys)};
6948: }
1.1166 raeburn 6949: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6950: my @pairs=split(/\&/,$rep);
6951: my %returnhash=();
1.1098 foxr 6952: if (!($rep =~ /^error/ )) {
6953: foreach my $item (@pairs) {
6954: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6955: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6956: next if ($key =~ /^error: 2 /);
6957: $returnhash{$key}=&thaw_unescape($value);
6958: }
1.755 albertel 6959: }
6960: return %returnhash;
1.407 www 6961: }
6962:
1.1098 foxr 6963:
1.717 albertel 6964: # --------------------------------------------------------- dumpstore interface
6965:
6966: sub dumpstore {
6967: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6968: # same as dump but keys must be escaped. They may contain colon separated
6969: # lists of values that may themself contain colons (e.g. symbs).
6970: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6971: }
6972:
1.407 www 6973: # -------------------------------------------------------------- keys interface
6974:
6975: sub getkeys {
6976: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6977: if (!$udomain) { $udomain=$env{'user.domain'}; }
6978: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6979: my $uhome=&homeserver($uname,$udomain);
6980: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6981: my @keyarray=();
1.800 albertel 6982: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6983: next if ($key =~ /^error: 2 /);
1.800 albertel 6984: push(@keyarray,&unescape($key));
1.407 www 6985: }
6986: return @keyarray;
1.318 matthew 6987: }
6988:
1.319 matthew 6989: # --------------------------------------------------------------- currentdump
6990: sub currentdump {
1.328 matthew 6991: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6992: $courseid = $env{'request.course.id'} if (! defined($courseid));
6993: $sdom = $env{'user.domain'} if (! defined($sdom));
6994: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6995: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6996: my $rep;
6997:
6998: if (grep { $_ eq $uhome } current_machine_ids()) {
6999: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7000: $courseid)));
7001: } else {
7002: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7003: }
7004:
1.318 matthew 7005: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7006: #
1.318 matthew 7007: my %returnhash=();
1.319 matthew 7008: #
7009: if ($rep eq "unknown_cmd") {
7010: # an old lond will not know currentdump
7011: # Do a dump and make it look like a currentdump
1.822 albertel 7012: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7013: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7014: my %hash = @tmp;
7015: @tmp=();
1.424 matthew 7016: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7017: } else {
7018: my @pairs=split(/\&/,$rep);
1.800 albertel 7019: foreach my $pair (@pairs) {
7020: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7021: my ($symb,$param) = split(/:/,$key);
7022: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7023: &thaw_unescape($value);
1.319 matthew 7024: }
1.191 harris41 7025: }
1.12 www 7026: return %returnhash;
1.424 matthew 7027: }
7028:
7029: sub convert_dump_to_currentdump{
7030: my %hash = %{shift()};
7031: my %returnhash;
7032: # Code ripped from lond, essentially. The only difference
7033: # here is the unescaping done by lonnet::dump(). Conceivably
7034: # we might run in to problems with parameter names =~ /^v\./
7035: while (my ($key,$value) = each(%hash)) {
7036: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7037: $symb = &unescape($symb);
7038: $param = &unescape($param);
1.424 matthew 7039: next if ($v eq 'version' || $symb eq 'keys');
7040: next if (exists($returnhash{$symb}) &&
7041: exists($returnhash{$symb}->{$param}) &&
7042: $returnhash{$symb}->{'v.'.$param} > $v);
7043: $returnhash{$symb}->{$param}=$value;
7044: $returnhash{$symb}->{'v.'.$param}=$v;
7045: }
7046: #
7047: # Remove all of the keys in the hashes which keep track of
7048: # the version of the parameter.
7049: while (my ($symb,$param_hash) = each(%returnhash)) {
7050: # use a foreach because we are going to delete from the hash.
7051: foreach my $key (keys(%$param_hash)) {
7052: delete($param_hash->{$key}) if ($key =~ /^v\./);
7053: }
7054: }
7055: return \%returnhash;
1.12 www 7056: }
7057:
1.627 albertel 7058: # ------------------------------------------------------ critical inc interface
7059:
7060: sub cinc {
7061: return &inc(@_,'critical');
7062: }
7063:
1.449 matthew 7064: # --------------------------------------------------------------- inc interface
7065:
7066: sub inc {
1.627 albertel 7067: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7068: if (!$udomain) { $udomain=$env{'user.domain'}; }
7069: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7070: my $uhome=&homeserver($uname,$udomain);
7071: my $items='';
7072: if (! ref($store)) {
7073: # got a single value, so use that instead
7074: $items = &escape($store).'=&';
7075: } elsif (ref($store) eq 'SCALAR') {
7076: $items = &escape($$store).'=&';
7077: } elsif (ref($store) eq 'ARRAY') {
7078: $items = join('=&',map {&escape($_);} @{$store});
7079: } elsif (ref($store) eq 'HASH') {
7080: while (my($key,$value) = each(%{$store})) {
7081: $items.= &escape($key).'='.&escape($value).'&';
7082: }
7083: }
7084: $items=~s/\&$//;
1.627 albertel 7085: if ($critical) {
7086: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7087: } else {
7088: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7089: }
1.449 matthew 7090: }
7091:
1.12 www 7092: # --------------------------------------------------------------- put interface
7093:
7094: sub put {
1.134 albertel 7095: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7096: if (!$udomain) { $udomain=$env{'user.domain'}; }
7097: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7098: my $uhome=&homeserver($uname,$udomain);
1.12 www 7099: my $items='';
1.800 albertel 7100: foreach my $item (keys(%$storehash)) {
7101: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7102: }
1.12 www 7103: $items=~s/\&$//;
1.134 albertel 7104: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7105: }
7106:
1.631 albertel 7107: # ------------------------------------------------------------ newput interface
7108:
7109: sub newput {
7110: my ($namespace,$storehash,$udomain,$uname)=@_;
7111: if (!$udomain) { $udomain=$env{'user.domain'}; }
7112: if (!$uname) { $uname=$env{'user.name'}; }
7113: my $uhome=&homeserver($uname,$udomain);
7114: my $items='';
7115: foreach my $key (keys(%$storehash)) {
7116: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7117: }
7118: $items=~s/\&$//;
7119: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7120: }
7121:
7122: # --------------------------------------------------------- putstore interface
7123:
1.524 raeburn 7124: sub putstore {
1.1172.2.59 raeburn 7125: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7126: if (!$udomain) { $udomain=$env{'user.domain'}; }
7127: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7128: my $uhome=&homeserver($uname,$udomain);
7129: my $items='';
1.715 albertel 7130: foreach my $key (keys(%$storehash)) {
7131: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7132: }
1.715 albertel 7133: $items=~s/\&$//;
1.716 albertel 7134: my $esc_symb=&escape($symb);
7135: my $esc_v=&escape($version);
1.715 albertel 7136: my $reply =
1.716 albertel 7137: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7138: $uhome);
1.1172.2.59 raeburn 7139: if (($tolog) && ($reply eq 'ok')) {
7140: my $namevalue='';
7141: foreach my $key (keys(%{$storehash})) {
7142: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7143: }
1.1172.2.134 raeburn 7144: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7145: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7146: '&host='.&escape($perlvar{'lonHostID'}).
7147: '&version='.$esc_v.
7148: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7149: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7150: }
1.715 albertel 7151: if ($reply eq 'unknown_cmd') {
1.716 albertel 7152: # gfall back to way things use to be done
1.715 albertel 7153: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7154: $uname);
1.524 raeburn 7155: }
1.715 albertel 7156: return $reply;
7157: }
7158:
7159: sub old_putstore {
1.716 albertel 7160: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7161: if (!$udomain) { $udomain=$env{'user.domain'}; }
7162: if (!$uname) { $uname=$env{'user.name'}; }
7163: my $uhome=&homeserver($uname,$udomain);
7164: my %newstorehash;
1.800 albertel 7165: foreach my $item (keys(%$storehash)) {
7166: my $key = $version.':'.&escape($symb).':'.$item;
7167: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7168: }
7169: my $items='';
7170: my %allitems = ();
1.800 albertel 7171: foreach my $item (keys(%newstorehash)) {
7172: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7173: my $key = $1.':keys:'.$2;
7174: $allitems{$key} .= $3.':';
7175: }
1.800 albertel 7176: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7177: }
1.800 albertel 7178: foreach my $item (keys(%allitems)) {
7179: $allitems{$item} =~ s/\:$//;
7180: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7181: }
7182: $items=~s/\&$//;
7183: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7184: }
7185:
1.47 www 7186: # ------------------------------------------------------ critical put interface
7187:
7188: sub cput {
1.134 albertel 7189: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7190: if (!$udomain) { $udomain=$env{'user.domain'}; }
7191: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7192: my $uhome=&homeserver($uname,$udomain);
1.47 www 7193: my $items='';
1.800 albertel 7194: foreach my $item (keys(%$storehash)) {
7195: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7196: }
1.47 www 7197: $items=~s/\&$//;
1.134 albertel 7198: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7199: }
7200:
7201: # -------------------------------------------------------------- eget interface
7202:
7203: sub eget {
1.133 albertel 7204: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7205: my $items='';
1.800 albertel 7206: foreach my $item (@$storearr) {
7207: $items.=&escape($item).'&';
1.191 harris41 7208: }
1.12 www 7209: $items=~s/\&$//;
1.620 albertel 7210: if (!$udomain) { $udomain=$env{'user.domain'}; }
7211: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7212: my $uhome=&homeserver($uname,$udomain);
7213: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7214: my @pairs=split(/\&/,$rep);
7215: my %returnhash=();
1.42 www 7216: my $i=0;
1.800 albertel 7217: foreach my $item (@$storearr) {
7218: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7219: $i++;
1.191 harris41 7220: }
1.12 www 7221: return %returnhash;
7222: }
7223:
1.667 albertel 7224: # ------------------------------------------------------------ tmpput interface
7225: sub tmpput {
1.802 raeburn 7226: my ($storehash,$server,$context)=@_;
1.667 albertel 7227: my $items='';
1.800 albertel 7228: foreach my $item (keys(%$storehash)) {
7229: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7230: }
7231: $items=~s/\&$//;
1.802 raeburn 7232: if (defined($context)) {
7233: $items .= ':'.&escape($context);
7234: }
1.667 albertel 7235: return &reply("tmpput:$items",$server);
7236: }
7237:
7238: # ------------------------------------------------------------ tmpget interface
7239: sub tmpget {
1.688 albertel 7240: my ($token,$server)=@_;
7241: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7242: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7243: my %returnhash;
1.1172.2.85 raeburn 7244: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7245: return %returnhash;
7246: }
1.667 albertel 7247: foreach my $item (split(/\&/,$rep)) {
7248: my ($key,$value)=split(/=/,$item);
7249: $returnhash{&unescape($key)}=&thaw_unescape($value);
7250: }
7251: return %returnhash;
7252: }
7253:
1.1113 raeburn 7254: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7255: sub tmpdel {
7256: my ($token,$server)=@_;
7257: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7258: return &reply("tmpdel:$token",$server);
7259: }
7260:
1.1172.2.13 raeburn 7261: # ------------------------------------------------------------ get_timebased_id
7262:
7263: sub get_timebased_id {
7264: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7265: $maxtries) = @_;
7266: my ($newid,$error,$dellock);
7267: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7268: return ('','ok','invalid call to get suffix');
7269: }
7270:
7271: # set defaults for any optional args for which values were not supplied
7272: if ($who eq '') {
7273: $who = $env{'user.name'}.':'.$env{'user.domain'};
7274: }
7275: if (!$locktries) {
7276: $locktries = 3;
7277: }
7278: if (!$maxtries) {
7279: $maxtries = 10;
7280: }
7281:
7282: if (($cdom eq '') || ($cnum eq '')) {
7283: if ($env{'request.course.id'}) {
7284: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7285: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7286: }
7287: if (($cdom eq '') || ($cnum eq '')) {
7288: return ('','ok','call to get suffix not in course context');
7289: }
7290: }
7291:
7292: # construct locking item
7293: my $lockhash = {
7294: $prefix."\0".'locked_'.$keyid => $who,
7295: };
7296: my $tries = 0;
7297:
7298: # attempt to get lock on nohist_$namespace file
7299: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7300: while (($gotlock ne 'ok') && $tries <$locktries) {
7301: $tries ++;
7302: sleep 1;
7303: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7304: }
7305:
7306: # attempt to get unique identifier, based on current timestamp
7307: if ($gotlock eq 'ok') {
7308: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7309: my $id = time;
7310: $newid = $id;
1.1172.2.56 raeburn 7311: if ($idtype eq 'addcode') {
7312: $newid .= &sixnum_code();
7313: }
1.1172.2.13 raeburn 7314: my $idtries = 0;
7315: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7316: if ($idtype eq 'concat') {
7317: $newid = $id.$idtries;
1.1172.2.56 raeburn 7318: } elsif ($idtype eq 'addcode') {
7319: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7320: } else {
7321: $newid ++;
7322: }
7323: $idtries ++;
7324: }
7325: if (!exists($inuse{$prefix."\0".$newid})) {
7326: my %new_item = (
7327: $prefix."\0".$newid => $who,
7328: );
7329: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7330: $cdom,$cnum);
7331: if ($putresult ne 'ok') {
7332: undef($newid);
7333: $error = 'error saving new item: '.$putresult;
7334: }
7335: } else {
1.1172.2.56 raeburn 7336: undef($newid);
1.1172.2.13 raeburn 7337: $error = ('error: no unique suffix available for the new item ');
7338: }
7339: # remove lock
7340: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7341: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7342: } else {
7343: $error = "error: could not obtain lockfile\n";
7344: $dellock = 'ok';
1.1172.2.58 raeburn 7345: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7346: $dellock = 'nolock';
7347: }
1.1172.2.13 raeburn 7348: }
7349: return ($newid,$dellock,$error);
7350: }
7351:
1.1172.2.56 raeburn 7352: sub sixnum_code {
7353: my $code;
7354: for (0..6) {
7355: $code .= int( rand(9) );
7356: }
7357: return $code;
7358: }
7359:
1.765 albertel 7360: # -------------------------------------------------- portfolio access checking
7361:
7362: sub portfolio_access {
1.1172.2.77 raeburn 7363: my ($requrl,$clientip) = @_;
1.765 albertel 7364: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7365: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7366: if ($result) {
7367: my %setters;
7368: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7369: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7370: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7371: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7372: return 'B';
7373: }
7374: } else {
1.1172.2.142 raeburn 7375: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7376: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7377: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7378: return 'B';
7379: }
7380: }
7381: }
1.765 albertel 7382: if ($result eq 'ok') {
1.766 albertel 7383: return 'F';
1.765 albertel 7384: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7385: return 'A';
1.765 albertel 7386: }
1.766 albertel 7387: return '';
1.765 albertel 7388: }
7389:
7390: sub get_portfolio_access {
1.1172.2.77 raeburn 7391: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7392:
7393: if (!ref($access_hash)) {
7394: my $current_perms = &get_portfile_permissions($udom,$unum);
7395: my %access_controls = &get_access_controls($current_perms,$group,
7396: $file_name);
7397: $access_hash = $access_controls{$file_name};
7398: }
7399:
1.1172.2.77 raeburn 7400: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7401: my $now = time;
7402: if (ref($access_hash) eq 'HASH') {
7403: foreach my $key (keys(%{$access_hash})) {
7404: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7405: if ($start > $now) {
7406: next;
7407: }
7408: if ($end && $end<$now) {
7409: next;
7410: }
7411: if ($scope eq 'public') {
7412: $public = $key;
7413: last;
7414: } elsif ($scope eq 'guest') {
7415: $guest = $key;
7416: } elsif ($scope eq 'domains') {
7417: push(@domains,$key);
7418: } elsif ($scope eq 'users') {
7419: push(@users,$key);
7420: } elsif ($scope eq 'course') {
7421: push(@courses,$key);
7422: } elsif ($scope eq 'group') {
7423: push(@groups,$key);
1.1172.2.77 raeburn 7424: } elsif ($scope eq 'ip') {
7425: push(@ips,$key);
1.765 albertel 7426: }
7427: }
7428: if ($public) {
7429: return 'ok';
1.1172.2.77 raeburn 7430: } elsif (@ips > 0) {
7431: my $allowed;
7432: foreach my $ipkey (@ips) {
7433: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7434: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7435: $allowed = 1;
7436: last;
7437: }
7438: }
7439: }
7440: if ($allowed) {
7441: return 'ok';
7442: }
1.765 albertel 7443: }
7444: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7445: if ($guest) {
7446: return $guest;
7447: }
7448: } else {
7449: if (@domains > 0) {
7450: foreach my $domkey (@domains) {
7451: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7452: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7453: return 'ok';
7454: }
7455: }
7456: }
7457: }
7458: if (@users > 0) {
7459: foreach my $userkey (@users) {
1.865 raeburn 7460: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7461: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7462: if (ref($item) eq 'HASH') {
7463: if (($item->{'uname'} eq $env{'user.name'}) &&
7464: ($item->{'udom'} eq $env{'user.domain'})) {
7465: return 'ok';
7466: }
7467: }
7468: }
7469: }
1.765 albertel 7470: }
7471: }
7472: my %roleshash;
7473: my @courses_and_groups = @courses;
7474: push(@courses_and_groups,@groups);
7475: if (@courses_and_groups > 0) {
7476: my (%allgroups,%allroles);
7477: my ($start,$end,$role,$sec,$group);
7478: foreach my $envkey (%env) {
1.1060 raeburn 7479: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7480: my $cid = $2.'_'.$3;
7481: if ($1 eq 'gr') {
7482: $group = $4;
7483: $allgroups{$cid}{$group} = $env{$envkey};
7484: } else {
7485: if ($4 eq '') {
7486: $sec = 'none';
7487: } else {
7488: $sec = $4;
7489: }
7490: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7491: }
1.811 albertel 7492: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7493: my $cid = $2.'_'.$3;
7494: if ($4 eq '') {
7495: $sec = 'none';
7496: } else {
7497: $sec = $4;
7498: }
7499: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7500: }
7501: }
7502: if (keys(%allroles) == 0) {
7503: return;
7504: }
7505: foreach my $key (@courses_and_groups) {
7506: my %content = %{$$access_hash{$key}};
7507: my $cnum = $content{'number'};
7508: my $cdom = $content{'domain'};
7509: my $cid = $cdom.'_'.$cnum;
7510: if (!exists($allroles{$cid})) {
7511: next;
7512: }
7513: foreach my $role_id (keys(%{$content{'roles'}})) {
7514: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7515: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7516: my @status = @{$content{'roles'}{$role_id}{'access'}};
7517: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7518: foreach my $role (keys(%{$allroles{$cid}})) {
7519: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7520: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7521: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7522: if (grep/^all$/,@sections) {
7523: return 'ok';
7524: } else {
7525: if (grep/^$sec$/,@sections) {
7526: return 'ok';
7527: }
7528: }
7529: }
7530: }
7531: if (keys(%{$allgroups{$cid}}) == 0) {
7532: if (grep/^none$/,@groups) {
7533: return 'ok';
7534: }
7535: } else {
7536: if (grep/^all$/,@groups) {
7537: return 'ok';
7538: }
7539: foreach my $group (keys(%{$allgroups{$cid}})) {
7540: if (grep/^$group$/,@groups) {
7541: return 'ok';
7542: }
7543: }
7544: }
7545: }
7546: }
7547: }
7548: }
7549: }
7550: if ($guest) {
7551: return $guest;
7552: }
7553: }
7554: }
7555: return;
7556: }
7557:
7558: sub course_group_datechecker {
7559: my ($dates,$now,$status) = @_;
7560: my ($start,$end) = split(/\./,$dates);
7561: if (!$start && !$end) {
7562: return 'ok';
7563: }
7564: if (grep/^active$/,@{$status}) {
7565: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7566: return 'ok';
7567: }
7568: }
7569: if (grep/^previous$/,@{$status}) {
7570: if ($end > $now ) {
7571: return 'ok';
7572: }
7573: }
7574: if (grep/^future$/,@{$status}) {
7575: if ($start > $now) {
7576: return 'ok';
7577: }
7578: }
7579: return;
7580: }
7581:
7582: sub parse_portfolio_url {
7583: my ($url) = @_;
7584:
7585: my ($type,$udom,$unum,$group,$file_name);
7586:
1.823 albertel 7587: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7588: $type = 1;
7589: $udom = $1;
7590: $unum = $2;
7591: $file_name = $3;
1.823 albertel 7592: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7593: $type = 2;
7594: $udom = $1;
7595: $unum = $2;
7596: $group = $3;
7597: $file_name = $3.'/'.$4;
7598: }
7599: if (wantarray) {
7600: return ($type,$udom,$unum,$file_name,$group);
7601: }
7602: return $type;
7603: }
7604:
7605: sub is_portfolio_url {
7606: my ($url) = @_;
7607: return scalar(&parse_portfolio_url($url));
7608: }
7609:
1.798 raeburn 7610: sub is_portfolio_file {
7611: my ($file) = @_;
1.820 raeburn 7612: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7613: return 1;
7614: }
7615: return;
7616: }
7617:
1.976 raeburn 7618: sub usertools_access {
1.1084 raeburn 7619: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7620: my ($access,%tools);
7621: if ($context eq '') {
7622: $context = 'tools';
7623: }
7624: if ($context eq 'requestcourses') {
7625: %tools = (
7626: official => 1,
7627: unofficial => 1,
1.1006 raeburn 7628: community => 1,
1.1172.2.37 raeburn 7629: textbook => 1,
1.985 raeburn 7630: );
1.1172.2.9 raeburn 7631: } elsif ($context eq 'requestauthor') {
7632: %tools = (
7633: requestauthor => 1,
7634: );
1.985 raeburn 7635: } else {
7636: %tools = (
7637: aboutme => 1,
7638: blog => 1,
1.1172.2.6 raeburn 7639: webdav => 1,
1.985 raeburn 7640: portfolio => 1,
7641: );
7642: }
1.976 raeburn 7643: return if (!defined($tools{$tool}));
7644:
1.1172.2.35 raeburn 7645: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7646: $udom = $env{'user.domain'};
7647: $uname = $env{'user.name'};
7648: }
7649:
1.978 raeburn 7650: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7651: if ($action ne 'reload') {
1.985 raeburn 7652: if ($context eq 'requestcourses') {
7653: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7654: } elsif ($context eq 'requestauthor') {
7655: return $env{'environment.canrequest.author'};
1.985 raeburn 7656: } else {
7657: return $env{'environment.availabletools.'.$tool};
7658: }
7659: }
1.976 raeburn 7660: }
7661:
1.1172.2.9 raeburn 7662: my ($toolstatus,$inststatus,$envkey);
7663: if ($context eq 'requestauthor') {
7664: $envkey = $context;
7665: } else {
7666: $envkey = $context.'.'.$tool;
7667: }
1.976 raeburn 7668:
1.985 raeburn 7669: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7670: ($action ne 'reload')) {
1.1172.2.9 raeburn 7671: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7672: $inststatus = $env{'environment.inststatus'};
7673: } else {
1.1084 raeburn 7674: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7675: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7676: $inststatus = $userenvref->{'inststatus'};
7677: } else {
1.1172.2.9 raeburn 7678: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7679: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7680: $inststatus = $userenv{'inststatus'};
7681: }
1.976 raeburn 7682: }
7683:
7684: if ($toolstatus ne '') {
7685: if ($toolstatus) {
7686: $access = 1;
7687: } else {
7688: $access = 0;
7689: }
7690: return $access;
7691: }
7692:
1.1084 raeburn 7693: my ($is_adv,%domdef);
7694: if (ref($is_advref) eq 'HASH') {
7695: $is_adv = $is_advref->{'is_adv'};
7696: } else {
7697: $is_adv = &is_advanced_user($udom,$uname);
7698: }
7699: if (ref($domdefref) eq 'HASH') {
7700: %domdef = %{$domdefref};
7701: } else {
7702: %domdef = &get_domain_defaults($udom);
7703: }
1.976 raeburn 7704: if (ref($domdef{$tool}) eq 'HASH') {
7705: if ($is_adv) {
7706: if ($domdef{$tool}{'_LC_adv'} ne '') {
7707: if ($domdef{$tool}{'_LC_adv'}) {
7708: $access = 1;
7709: } else {
7710: $access = 0;
7711: }
7712: return $access;
7713: }
7714: }
7715: if ($inststatus ne '') {
7716: my ($hasaccess,$hasnoaccess);
7717: foreach my $affiliation (split(/:/,$inststatus)) {
7718: if ($domdef{$tool}{$affiliation} ne '') {
7719: if ($domdef{$tool}{$affiliation}) {
7720: $hasaccess = 1;
7721: } else {
7722: $hasnoaccess = 1;
7723: }
7724: }
7725: }
7726: if ($hasaccess || $hasnoaccess) {
7727: if ($hasaccess) {
7728: $access = 1;
7729: } elsif ($hasnoaccess) {
7730: $access = 0;
7731: }
7732: return $access;
7733: }
7734: } else {
7735: if ($domdef{$tool}{'default'} ne '') {
7736: if ($domdef{$tool}{'default'}) {
7737: $access = 1;
7738: } elsif ($domdef{$tool}{'default'} == 0) {
7739: $access = 0;
7740: }
7741: return $access;
7742: }
7743: }
7744: } else {
1.1172.2.6 raeburn 7745: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7746: $access = 1;
7747: } else {
7748: $access = 0;
7749: }
1.976 raeburn 7750: return $access;
7751: }
7752: }
7753:
1.1050 raeburn 7754: sub is_course_owner {
7755: my ($cdom,$cnum,$udom,$uname) = @_;
7756: if (($udom eq '') || ($uname eq '')) {
7757: $udom = $env{'user.domain'};
7758: $uname = $env{'user.name'};
7759: }
7760: unless (($udom eq '') || ($uname eq '')) {
7761: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7762: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7763: return 1;
7764: } else {
7765: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7766: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7767: return 1;
7768: }
7769: }
7770: }
7771: }
7772: return;
7773: }
7774:
1.976 raeburn 7775: sub is_advanced_user {
7776: my ($udom,$uname) = @_;
1.1085 raeburn 7777: if ($udom ne '' && $uname ne '') {
7778: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7779: if (wantarray) {
7780: return ($env{'user.adv'},$env{'user.author'});
7781: } else {
7782: return $env{'user.adv'};
7783: }
1.1085 raeburn 7784: }
7785: }
1.976 raeburn 7786: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7787: my %allroles;
1.1128 raeburn 7788: my ($is_adv,$is_author);
1.976 raeburn 7789: foreach my $role (keys(%roleshash)) {
7790: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7791: my $area = '/'.$tdomain.'/'.$trest;
7792: if ($sec ne '') {
7793: $area .= '/'.$sec;
7794: }
7795: if (($area ne '') && ($trole ne '')) {
7796: my $spec=$trole.'.'.$area;
7797: if ($trole =~ /^cr\//) {
7798: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7799: } elsif ($trole ne 'gr') {
7800: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7801: }
1.1128 raeburn 7802: if ($trole eq 'au') {
7803: $is_author = 1;
7804: }
1.976 raeburn 7805: }
7806: }
7807: foreach my $role (keys(%allroles)) {
7808: last if ($is_adv);
7809: foreach my $item (split(/:/,$allroles{$role})) {
7810: if ($item ne '') {
7811: my ($privilege,$restrictions)=split(/&/,$item);
7812: if ($privilege eq 'adv') {
7813: $is_adv = 1;
7814: last;
7815: }
7816: }
7817: }
7818: }
1.1128 raeburn 7819: if (wantarray) {
7820: return ($is_adv,$is_author);
7821: }
1.976 raeburn 7822: return $is_adv;
7823: }
1.798 raeburn 7824:
1.1035 raeburn 7825: sub check_can_request {
1.1036 raeburn 7826: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7827: my $canreq = 0;
7828: my ($types,$typename) = &Apache::loncommon::course_types();
7829: my @options = ('approval','validate','autolimit');
7830: my $optregex = join('|',@options);
7831: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7832: foreach my $type (@{$types}) {
7833: if (&usertools_access($env{'user.name'},
7834: $env{'user.domain'},
7835: $type,undef,'requestcourses')) {
7836: $canreq ++;
1.1036 raeburn 7837: if (ref($request_domains) eq 'HASH') {
7838: push(@{$request_domains->{$type}},$env{'user.domain'});
7839: }
1.1035 raeburn 7840: if ($dom eq $env{'user.domain'}) {
7841: $can_request->{$type} = 1;
7842: }
7843: }
7844: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7845: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7846: if (@curr > 0) {
1.1036 raeburn 7847: foreach my $item (@curr) {
7848: if (ref($request_domains) eq 'HASH') {
7849: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7850: if ($otherdom ne '') {
7851: if (ref($request_domains->{$type}) eq 'ARRAY') {
7852: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7853: push(@{$request_domains->{$type}},$otherdom);
7854: }
7855: } else {
7856: push(@{$request_domains->{$type}},$otherdom);
7857: }
7858: }
7859: }
7860: }
7861: unless($dom eq $env{'user.domain'}) {
7862: $canreq ++;
1.1035 raeburn 7863: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7864: $can_request->{$type} = 1;
7865: }
7866: }
7867: }
7868: }
7869: }
7870: }
7871: return $canreq;
7872: }
7873:
1.341 www 7874: # ---------------------------------------------- Custom access rule evaluation
7875:
7876: sub customaccess {
7877: my ($priv,$uri)=@_;
1.807 albertel 7878: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7879: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7880: $udom = &LONCAPA::clean_domain($udom);
7881: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7882: my $access=0;
1.800 albertel 7883: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7884: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7885: if ($type eq 'user') {
7886: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7887: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7888: if ($tdom) {
7889: if ($tdom ne $env{'user.domain'}) { next; }
7890: }
1.896 albertel 7891: if ($tuname) {
7892: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7893: }
7894: $access=($effect eq 'allow');
7895: last;
7896: }
7897: } else {
7898: if ($role) {
7899: if ($role ne $urole) { next; }
7900: }
7901: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7902: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7903: if ($tdom) {
7904: if ($tdom ne $udom) { next; }
7905: }
7906: if ($tcrs) {
7907: if ($tcrs ne $ucrs) { next; }
7908: }
7909: if ($tsec) {
7910: if ($tsec ne $usec) { next; }
7911: }
7912: $access=($effect eq 'allow');
7913: last;
7914: }
7915: if ($realm eq '' && $role eq '') {
7916: $access=($effect eq 'allow');
7917: }
1.402 bowersj2 7918: }
1.341 www 7919: }
7920: return $access;
7921: }
7922:
1.103 harris41 7923: # ------------------------------------------------- Check for a user privilege
1.12 www 7924:
7925: sub allowed {
1.1172.2.126 raeburn 7926: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7927: my $ver_orguri=$uri;
1.439 www 7928: $uri=&deversion($uri);
1.152 www 7929: my $orguri=$uri;
1.52 www 7930: $uri=&declutter($uri);
1.809 raeburn 7931:
1.810 raeburn 7932: if ($priv eq 'evb') {
7933: # Evade communication block restrictions for specified role in a course
7934: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7935: return $1;
7936: } else {
7937: return;
7938: }
7939: }
7940:
1.620 albertel 7941: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7942: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7943: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7944: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7945: && ($priv eq 'bre')) {
1.14 www 7946: return 'F';
1.159 www 7947: }
7948:
1.545 banghart 7949: # Free bre access to user's own portfolio contents
1.714 raeburn 7950: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7951: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7952: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7953: my %setters;
1.1172.2.142 raeburn 7954: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7955: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7956: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7957: return 'B';
7958: } else {
7959: return 'F';
7960: }
1.545 banghart 7961: }
7962:
1.762 raeburn 7963: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7964: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7965: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7966: if (exists($env{'request.course.id'})) {
7967: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7968: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7969: if (($domain eq $cdom) && ($name eq $cnum)) {
7970: my $courseprivid=$env{'request.course.id'};
7971: $courseprivid=~s/\_/\//;
7972: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7973: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7974: return $1;
1.762 raeburn 7975: } else {
7976: if ($env{'request.course.sec'}) {
7977: $courseprivid.='/'.$env{'request.course.sec'};
7978: }
7979: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7980: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7981: return $2;
7982: }
1.714 raeburn 7983: }
7984: }
7985: }
7986: }
7987:
1.159 www 7988: # Free bre to public access
7989:
7990: if ($priv eq 'bre') {
1.238 www 7991: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7992: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7993: return 'F';
7994: }
1.238 www 7995: if ($copyright eq 'priv') {
7996: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7997: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7998: return '';
7999: }
8000: }
8001: if ($copyright eq 'domain') {
8002: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8003: unless (($env{'user.domain'} eq $1) ||
8004: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8005: return '';
8006: }
1.262 matthew 8007: }
1.620 albertel 8008: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8009: # Library role, so allow browsing of resources in this domain.
8010: return 'F';
1.238 www 8011: }
1.341 www 8012: if ($copyright eq 'custom') {
8013: unless (&customaccess($priv,$uri)) { return ''; }
8014: }
1.14 www 8015: }
1.264 matthew 8016: # Domain coordinator is trying to create a course
1.620 albertel 8017: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8018: # uri is the requested domain in this case.
8019: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8020: # a role of dc for the domain in question.
1.620 albertel 8021: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8022: }
1.29 www 8023:
1.52 www 8024: my $thisallowed='';
8025: my $statecond=0;
8026: my $courseprivid='';
8027:
1.1039 raeburn 8028: my $ownaccess;
1.1043 raeburn 8029: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8030: if (($priv eq 'bro') && ($env{'user.author'})) {
8031: if ($uri eq '') {
8032: $ownaccess = 1;
8033: } else {
8034: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8035: my $udom = $env{'user.domain'};
8036: my $uname = $env{'user.name'};
8037: if ($uri =~ m{^\Q$udom\E/?$}) {
8038: $ownaccess = 1;
1.1040 raeburn 8039: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8040: unless ($uri =~ m{\.\./}) {
8041: $ownaccess = 1;
8042: }
8043: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8044: my $now = time;
8045: if ($uri =~ m{^([^/]+)/?$}) {
8046: my $adom = $1;
8047: foreach my $key (keys(%env)) {
1.1042 raeburn 8048: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8049: my ($start,$end) = split(/\./,$env{$key});
8050: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8051: $ownaccess = 1;
8052: last;
8053: }
8054: }
8055: }
8056: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8057: my $adom = $1;
8058: my $aname = $2;
1.1042 raeburn 8059: foreach my $role ('ca','aa') {
8060: if ($env{"user.role.$role./$adom/$aname"}) {
8061: my ($start,$end) =
1.1172.2.142 raeburn 8062: split(/\./,$env{"user.role.$role./$adom/$aname"});
8063: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8064: $ownaccess = 1;
8065: last;
8066: }
1.1039 raeburn 8067: }
8068: }
8069: }
8070: }
8071: }
8072: }
8073: }
8074:
1.52 www 8075: # Course
8076:
1.620 albertel 8077: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8078: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8079: $thisallowed.=$1;
8080: }
1.52 www 8081: }
1.29 www 8082:
1.52 www 8083: # Domain
8084:
1.620 albertel 8085: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8086: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8087: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8088: $thisallowed.=$1;
8089: }
1.12 www 8090: }
1.52 www 8091:
1.1141 raeburn 8092: # User who is not author or co-author might still be able to edit
8093: # resource of an author in the domain (e.g., if Domain Coordinator).
8094: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8095: (&allowed('mdc',$env{'request.course.id'}))) {
8096: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8097: $thisallowed.=$1;
8098: }
8099: }
8100:
1.52 www 8101: # Course: uri itself is a course
1.66 www 8102: my $courseuri=$uri;
8103: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8104: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8105:
1.620 albertel 8106: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8107: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8108: if ($priv eq 'mip') {
8109: my $rem = $1;
8110: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8111: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8112: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8113: if ($cdom ne '') {
8114: my %passwdconf = &get_passwdconf($cdom);
8115: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8116: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8117: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8118: my @inststatuses = split(':',$env{'environment.inststatus'});
8119: unless (@inststatuses) {
8120: @inststatuses = ('default');
8121: }
8122: foreach my $status (@inststatuses) {
8123: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8124: $thisallowed.=$rem;
8125: }
8126: }
8127: }
8128: }
8129: }
8130: }
8131: }
8132: } else {
8133: unless (($priv eq 'bro') && (!$ownaccess)) {
8134: $thisallowed.=$1;
8135: }
1.1039 raeburn 8136: }
1.12 www 8137: }
1.29 www 8138:
1.665 albertel 8139: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8140: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8141: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8142: $thisallowed='';
1.671 raeburn 8143: my ($match)=&is_on_map($uri);
8144: if ($match) {
8145: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8146: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8147: my $value = $1;
8148: if ($noblockcheck) {
8149: $thisallowed.=$value;
1.1162 raeburn 8150: } else {
1.1172.2.126 raeburn 8151: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8152: if (@blockers > 0) {
8153: $thisallowed = 'B';
8154: } else {
8155: $thisallowed.=$value;
8156: }
1.1162 raeburn 8157: }
1.671 raeburn 8158: }
8159: } else {
1.705 albertel 8160: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8161: if ($refuri) {
8162: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8163: $thisallowed='F';
1.671 raeburn 8164: } else {
8165: $refuri=&declutter($refuri);
8166: my ($match) = &is_on_map($refuri);
8167: if ($match) {
1.1172.2.65 raeburn 8168: if ($noblockcheck) {
1.1162 raeburn 8169: $thisallowed='F';
1.1172.2.65 raeburn 8170: } else {
1.1172.2.127 raeburn 8171: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8172: if (@blockers > 0) {
8173: $thisallowed = 'B';
8174: } else {
8175: $thisallowed='F';
8176: }
1.1162 raeburn 8177: }
1.671 raeburn 8178: }
1.669 raeburn 8179: }
1.671 raeburn 8180: }
8181: }
1.314 www 8182: }
1.492 albertel 8183:
1.766 albertel 8184: if ($priv eq 'bre'
8185: && $thisallowed ne 'F'
8186: && $thisallowed ne '2'
8187: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8188: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8189: }
8190:
1.52 www 8191: # Full access at system, domain or course-wide level? Exit.
1.29 www 8192: if ($thisallowed=~/F/) {
8193: return 'F';
8194: }
8195:
1.52 www 8196: # If this is generating or modifying users, exit with special codes
1.29 www 8197:
1.643 www 8198: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8199: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8200: my ($audom,$auname)=split('/',$uri);
1.643 www 8201: # no author name given, so this just checks on the general right to make a co-author in this domain
8202: unless ($auname) { return $thisallowed; }
8203: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8204: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8205: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8206: ($audom ne $env{'request.role.domain'}))) { return ''; }
8207: }
1.52 www 8208: return $thisallowed;
8209: }
8210: #
1.103 harris41 8211: # Gathered so far: system, domain and course wide privileges
1.52 www 8212: #
8213: # Course: See if uri or referer is an individual resource that is part of
8214: # the course
8215:
1.620 albertel 8216: if ($env{'request.course.id'}) {
1.232 www 8217:
1.1172.2.115 raeburn 8218: # If this is modifying password (internal auth) domains must match for user and user's role.
8219:
8220: if ($priv eq 'mip') {
8221: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8222: return $thisallowed;
8223: } else {
8224: return '';
8225: }
8226: }
8227:
1.620 albertel 8228: $courseprivid=$env{'request.course.id'};
8229: if ($env{'request.course.sec'}) {
8230: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8231: }
8232: $courseprivid=~s/\_/\//;
8233: my $checkreferer=1;
1.232 www 8234: my ($match,$cond)=&is_on_map($uri);
8235: if ($match) {
8236: $statecond=$cond;
1.620 albertel 8237: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8238: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8239: my $value = $1;
8240: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8241: if ($noblockcheck) {
1.1162 raeburn 8242: $thisallowed.=$value;
1.1172.2.65 raeburn 8243: } else {
1.1172.2.126 raeburn 8244: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8245: if (@blockers > 0) {
8246: $thisallowed = 'B';
8247: } else {
8248: $thisallowed.=$value;
8249: }
1.1162 raeburn 8250: }
8251: } else {
8252: $thisallowed.=$value;
8253: }
1.52 www 8254: $checkreferer=0;
8255: }
1.29 www 8256: }
1.1172.2.126 raeburn 8257:
1.148 www 8258: if ($checkreferer) {
1.620 albertel 8259: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8260: unless ($refuri) {
1.800 albertel 8261: foreach my $key (keys(%env)) {
8262: if ($key=~/^httpref\..*\*/) {
8263: my $pattern=$key;
1.156 www 8264: $pattern=~s/^httpref\.\/res\///;
1.148 www 8265: $pattern=~s/\*/\[\^\/\]\+/g;
8266: $pattern=~s/\//\\\//g;
1.152 www 8267: if ($orguri=~/$pattern/) {
1.800 albertel 8268: $refuri=$env{$key};
1.148 www 8269: }
8270: }
1.191 harris41 8271: }
1.148 www 8272: }
1.232 www 8273:
1.148 www 8274: if ($refuri) {
1.152 www 8275: $refuri=&declutter($refuri);
1.232 www 8276: my ($match,$cond)=&is_on_map($refuri);
8277: if ($match) {
8278: my $refstatecond=$cond;
1.620 albertel 8279: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8280: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8281: my $value = $1;
8282: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8283: if ($noblockcheck) {
1.1162 raeburn 8284: $thisallowed.=$value;
1.1172.2.65 raeburn 8285: } else {
1.1172.2.127 raeburn 8286: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8287: if (@blockers > 0) {
8288: $thisallowed = 'B';
8289: } else {
8290: $thisallowed.=$value;
8291: }
1.1162 raeburn 8292: }
8293: } else {
8294: $thisallowed.=$value;
8295: }
1.53 www 8296: $uri=$refuri;
8297: $statecond=$refstatecond;
1.52 www 8298: }
8299: }
1.148 www 8300: }
1.29 www 8301: }
1.52 www 8302: }
1.29 www 8303:
1.52 www 8304: #
1.103 harris41 8305: # Gathered now: all privileges that could apply, and condition number
1.52 www 8306: #
8307: #
8308: # Full or no access?
8309: #
1.29 www 8310:
1.52 www 8311: if ($thisallowed=~/F/) {
8312: return 'F';
8313: }
1.29 www 8314:
1.52 www 8315: unless ($thisallowed) {
8316: return '';
8317: }
1.29 www 8318:
1.52 www 8319: # Restrictions exist, deal with them
8320: #
8321: # C:according to course preferences
8322: # R:according to resource settings
8323: # L:unless locked
8324: # X:according to user session state
8325: #
8326:
8327: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8328: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8329: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8330: # courses, and 2 minutes for current course, in which user has st or ta role
8331: # which is neither expired nor a future role (unless current course).
1.52 www 8332:
1.1172.2.142 raeburn 8333: my ($needlockcheck,$now,$crsonly);
1.52 www 8334: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8335: $now = time;
8336: if ($priv eq 'bre') {
8337: if ($uri ne '') {
8338: if ($orguri =~ m{^/+res/}) {
8339: if ($uri =~ m{^lib/templates/}) {
8340: if ($env{'request.course.id'}) {
8341: $crsonly = 1;
8342: $needlockcheck = 1;
8343: }
8344: } else {
8345: $needlockcheck = 1;
8346: }
8347: } elsif ($env{'request.course.id'}) {
8348: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8349: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8350: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8351: $crsonly = 1;
8352: }
8353: $needlockcheck = 1;
8354: }
8355: }
8356: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8357: $needlockcheck = 1;
8358: }
8359: }
8360: if ($needlockcheck) {
8361: foreach my $envkey (keys(%env)) {
1.54 www 8362: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8363: my $courseid=$2;
8364: my $roleid=$1.'.'.$2;
1.92 www 8365: $courseid=~s/^\///;
1.1172.2.142 raeburn 8366: unless ($env{'request.role'} eq $roleid) {
8367: my ($start,$end) = split(/\./,$env{$envkey});
8368: next unless (($now >= $start) && (!$end || $end > $now));
8369: }
1.54 www 8370: my $expiretime=600;
1.620 albertel 8371: if ($env{'request.role'} eq $roleid) {
1.54 www 8372: $expiretime=120;
8373: }
8374: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8375: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8376: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8377: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8378: }
1.620 albertel 8379: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8380: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8381: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8382: &log($env{'user.domain'},$env{'user.name'},
8383: $env{'user.home'},
1.57 www 8384: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8385: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8386: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8387: return '';
8388: }
8389: }
1.620 albertel 8390: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8391: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8392: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8393: &log($env{'user.domain'},$env{'user.name'},
8394: $env{'user.home'},
1.57 www 8395: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8396: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8397: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8398: return '';
8399: }
8400: }
8401: }
1.29 www 8402: }
1.52 www 8403: }
1.1172.2.126 raeburn 8404:
1.52 www 8405: #
8406: # Rest of the restrictions depend on selected course
8407: #
8408:
1.620 albertel 8409: unless ($env{'request.course.id'}) {
1.766 albertel 8410: if ($thisallowed eq 'A') {
8411: return 'A';
1.814 raeburn 8412: } elsif ($thisallowed eq 'B') {
8413: return 'B';
1.766 albertel 8414: } else {
8415: return '1';
8416: }
1.52 www 8417: }
1.29 www 8418:
1.52 www 8419: #
8420: # Now user is definitely in a course
8421: #
1.53 www 8422:
8423:
8424: # Course preferences
8425:
8426: if ($thisallowed=~/C/) {
1.620 albertel 8427: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8428: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8429: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8430: =~/\Q$rolecode\E/) {
1.1103 raeburn 8431: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8432: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8433: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8434: $env{'request.course.id'});
8435: }
1.237 www 8436: return '';
8437: }
8438:
1.620 albertel 8439: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8440: =~/\Q$unamedom\E/) {
1.1103 raeburn 8441: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8442: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8443: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8444: $env{'request.course.id'});
8445: }
1.54 www 8446: return '';
8447: }
1.53 www 8448: }
8449:
8450: # Resource preferences
8451:
8452: if ($thisallowed=~/R/) {
1.620 albertel 8453: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8454: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8455: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8456: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8457: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8458: }
8459: return '';
1.54 www 8460: }
1.53 www 8461: }
1.30 www 8462:
1.246 www 8463: # Restricted by state or randomout?
1.30 www 8464:
1.52 www 8465: if ($thisallowed=~/X/) {
1.620 albertel 8466: if ($env{'acc.randomout'}) {
1.579 albertel 8467: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8468: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8469: return '';
8470: }
1.247 www 8471: }
8472: if (&condval($statecond)) {
1.52 www 8473: return '2';
8474: } else {
8475: return '';
8476: }
8477: }
1.30 www 8478:
1.766 albertel 8479: if ($thisallowed eq 'A') {
8480: return 'A';
1.814 raeburn 8481: } elsif ($thisallowed eq 'B') {
8482: return 'B';
1.766 albertel 8483: }
1.52 www 8484: return 'F';
1.232 www 8485: }
1.1162 raeburn 8486:
1.1172.2.13 raeburn 8487: # ------------------------------------------- Check construction space access
8488:
8489: sub constructaccess {
8490: my ($url,$setpriv)=@_;
8491:
8492: # We do not allow editing of previous versions of files
8493: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8494:
8495: # Get username and domain from URL
8496: my ($ownername,$ownerdomain,$ownerhome);
8497:
8498: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8499: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8500:
8501: # The URL does not really point to any authorspace, forget it
8502: unless (($ownername) && ($ownerdomain)) { return ''; }
8503:
8504: # Now we need to see if the user has access to the authorspace of
8505: # $ownername at $ownerdomain
8506:
8507: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8508: # Real author for this?
8509: $ownerhome = $env{'user.home'};
8510: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8511: return ($ownername,$ownerdomain,$ownerhome);
8512: }
8513: } else {
8514: # Co-author for this?
8515: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8516: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8517: $ownerhome = &homeserver($ownername,$ownerdomain);
8518: return ($ownername,$ownerdomain,$ownerhome);
8519: }
8520: }
8521:
8522: # We don't have any access right now. If we are not possibly going to do anything about this,
8523: # we might as well leave
8524: unless ($setpriv) { return ''; }
8525:
8526: # Backdoor access?
8527: my $allowed=&allowed('eco',$ownerdomain);
8528: # Nope
8529: unless ($allowed) { return ''; }
8530: # Looks like we may have access, but could be locked by the owner of the construction space
8531: if ($allowed eq 'U') {
8532: my %blocked=&get('environment',['domcoord.author'],
8533: $ownerdomain,$ownername);
8534: # Is blocked by owner
8535: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8536: }
8537: if (($allowed eq 'F') || ($allowed eq 'U')) {
8538: # Grant temporary access
8539: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8540: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8541: if (!$update) { $update = $then; }
8542: my $refresh=$env{'user.refresh.time'};
8543: if (!$refresh) { $refresh = $update; }
8544: my $now = time;
8545: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8546: $now,'ca','constructaccess');
8547: $ownerhome = &homeserver($ownername,$ownerdomain);
8548: return($ownername,$ownerdomain,$ownerhome);
8549: }
8550: # No business here
8551: return '';
8552: }
8553:
1.1172.2.66 raeburn 8554: # ----------------------------------------------------------- Content Blocking
8555:
8556: {
8557: # Caches for faster Course Contents display where content blocking
8558: # is in operation (i.e., interval param set) for timed quiz.
8559: #
8560: # User for whom data are being temporarily cached.
8561: my $cacheduser='';
1.1172.2.126 raeburn 8562: # Course for which data are being temporarily cached.
8563: my $cachedcid='';
1.1172.2.66 raeburn 8564: # Cached blockers for this user (a hash of blocking items).
8565: my %cachedblockers=();
8566: # When the data were last cached.
8567: my $cachedlast='';
8568:
8569: sub load_all_blockers {
1.1172.2.128 raeburn 8570: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8571: if (($uname ne '') && ($udom ne '')) {
8572: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8573: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8574: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8575: return;
8576: }
8577: }
8578: $cachedlast=time;
8579: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8580: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8581: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8582: return;
1.1172.2.66 raeburn 8583: }
8584:
1.1162 raeburn 8585: sub get_comm_blocks {
8586: my ($cdom,$cnum) = @_;
8587: if ($cdom eq '' || $cnum eq '') {
8588: return unless ($env{'request.course.id'});
8589: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8590: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8591: }
8592: my %commblocks;
8593: my $hashid=$cdom.'_'.$cnum;
8594: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8595: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8596: %commblocks = %{$blocksref};
8597: } else {
8598: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8599: my $cachetime = 600;
8600: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8601: }
8602: return %commblocks;
8603: }
8604:
1.1172.2.66 raeburn 8605: sub get_commblock_resources {
8606: my ($blocks) = @_;
8607: my %blockers = ();
8608: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8609: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8610: if ($env{'request.course.sec'}) {
8611: $courseurl .= '/'.$env{'request.course.sec'};
8612: }
8613: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8614: my %commblocks;
8615: if (ref($blocks) eq 'HASH') {
8616: %commblocks = %{$blocks};
8617: } else {
8618: %commblocks = &get_comm_blocks();
8619: }
1.1172.2.66 raeburn 8620: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8621: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8622: return %blockers unless (ref($navmap));
8623: my $now = time;
1.1162 raeburn 8624: foreach my $block (keys(%commblocks)) {
8625: if ($block =~ /^(\d+)____(\d+)$/) {
8626: my ($start,$end) = ($1,$2);
8627: if ($start <= $now && $end >= $now) {
8628: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8629: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8630: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8631: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8632: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8633: }
8634: }
8635: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8636: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8637: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8638: }
8639: }
8640: }
8641: }
8642: }
8643: } elsif ($block =~ /^firstaccess____(.+)$/) {
8644: my $item = $1;
8645: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8646: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8647: my (@interval,$mapname);
1.1172.2.66 raeburn 8648: my $type = 'map';
8649: if ($item eq 'course') {
8650: $type = 'course';
8651: @interval=&EXT("resource.0.interval");
8652: } else {
8653: if ($item =~ /___\d+___/) {
8654: $type = 'resource';
8655: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8656: } else {
1.1172.2.142 raeburn 8657: $mapname = &deversion($item);
8658: if (ref($navmap)) {
8659: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8660: @interval = ($timelimit,'map');
1.1162 raeburn 8661: }
8662: }
1.1172.2.66 raeburn 8663: }
8664: if ($interval[0] =~ /^\d+$/) {
8665: my $first_access;
8666: if ($type eq 'resource') {
8667: $first_access=&get_first_access($interval[1],$item);
8668: } elsif ($type eq 'map') {
8669: $first_access=&get_first_access($interval[1],undef,$item);
8670: } else {
8671: $first_access=&get_first_access($interval[1]);
8672: }
8673: if ($first_access) {
8674: my $timesup = $first_access+$interval[0];
8675: if ($timesup > $now) {
8676: my $activeblock;
1.1172.2.142 raeburn 8677: if ($type eq 'resource') {
8678: if (ref($navmap)) {
8679: my $res = $navmap->getBySymb($item);
8680: if ($res->answerable()) {
8681: $activeblock = 1;
8682: }
8683: }
8684: } elsif ($type eq 'map') {
8685: my $mapsymb = &symbread($mapname,1);
8686: if (($mapsymb) && (ref($navmap))) {
8687: my $mapres = $navmap->getBySymb($mapsymb);
8688: if (ref($mapres)) {
8689: my $first = $mapres->map_start();
8690: my $finish = $mapres->map_finish();
8691: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8692: if (ref($it)) {
8693: my $res;
8694: while ($res = $it->next(undef,1)) {
8695: next unless (ref($res));
8696: my $symb = $res->symb();
8697: next if (($symb eq $mapsymb) || ($symb eq ''));
8698: @interval=&EXT("resource.0.interval",$symb);
8699: if ($interval[1] eq 'map') {
8700: if ($res->answerable()) {
8701: $activeblock = 1;
8702: last;
8703: }
8704: }
8705: }
8706: }
8707: }
1.1172.2.66 raeburn 8708: }
8709: }
8710: if ($activeblock) {
8711: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8712: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8713: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8714: }
8715: }
8716: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8717: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8718: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8719: }
1.1162 raeburn 8720: }
8721: }
8722: }
8723: }
8724: }
8725: }
8726: }
8727: }
8728: }
1.1172.2.66 raeburn 8729: return %blockers;
1.1162 raeburn 8730: }
8731:
1.1172.2.66 raeburn 8732: sub has_comm_blocking {
1.1172.2.128 raeburn 8733: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8734: my @blockers;
8735: return unless ($env{'request.course.id'});
8736: return unless ($priv eq 'bre');
8737: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8738: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8739: if ($env{'request.course.sec'}) {
8740: $courseurl .= '/'.$env{'request.course.sec'};
8741: }
8742: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8743: my %blockinfo;
8744: if (ref($blocks) eq 'HASH') {
8745: %blockinfo = &get_commblock_resources($blocks);
8746: } else {
8747: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8748: %blockinfo = %cachedblockers;
8749: }
8750: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8751: my (%possibles,@symbs);
8752: if (!$symb) {
1.1172.2.128 raeburn 8753: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8754: }
1.1172.2.66 raeburn 8755: if ($symb) {
8756: @symbs = ($symb);
8757: } elsif (keys(%possibles)) {
8758: @symbs = keys(%possibles);
8759: }
8760: my $noblock;
8761: foreach my $symb (@symbs) {
8762: last if ($noblock);
8763: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8764: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8765: if ($block =~ /^firstaccess____(.+)$/) {
8766: my $item = $1;
1.1172.2.126 raeburn 8767: unless ($blocked) {
8768: if (($item eq $map) || ($item eq $symb)) {
8769: $noblock = 1;
8770: last;
8771: }
1.1172.2.66 raeburn 8772: }
1.1162 raeburn 8773: }
1.1172.2.128 raeburn 8774: if (ref($blockinfo{$block}) eq 'HASH') {
8775: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8776: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8777: unless (grep(/^\Q$block\E$/,@blockers)) {
8778: push(@blockers,$block);
8779: }
8780: }
8781: }
1.1172.2.128 raeburn 8782: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8783: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8784: unless (grep(/^\Q$block\E$/,@blockers)) {
8785: push(@blockers,$block);
8786: }
1.1172.2.66 raeburn 8787: }
8788: }
1.1162 raeburn 8789: }
8790: }
8791: }
1.1172.2.126 raeburn 8792: unless ($noblock) {
8793: return @blockers;
8794: }
8795: return;
1.1172.2.66 raeburn 8796: }
1.1162 raeburn 8797: }
8798:
1.1172.2.66 raeburn 8799: # -------------------------------- Deversion and split uri into path an filename
8800:
1.1133 foxr 8801: #
1.1172.2.66 raeburn 8802: # Removes the version from a URI and
1.1133 foxr 8803: # splits it in to its filename and path to the filename.
8804: # Seems like File::Basename could have done this more clearly.
8805: # Parameters:
8806: # $uri - input URI
8807: # Returns:
8808: # Two element list consisting of
8809: # $pathname - the URI up to and excluding the trailing /
8810: # $filename - The part of the URI following the last /
8811: # NOTE:
8812: # Another realization of this is simply:
8813: # use File::Basename;
8814: # ...
8815: # $uri = shift;
8816: # $filename = basename($uri);
8817: # $path = dirname($uri);
8818: # return ($filename, $path);
8819: #
8820: # The implementation below is probably faster however.
8821: #
1.710 albertel 8822: sub split_uri_for_cond {
8823: my $uri=&deversion(&declutter(shift));
8824: my @uriparts=split(/\//,$uri);
8825: my $filename=pop(@uriparts);
8826: my $pathname=join('/',@uriparts);
8827: return ($pathname,$filename);
8828: }
1.232 www 8829: # --------------------------------------------------- Is a resource on the map?
8830:
8831: sub is_on_map {
1.710 albertel 8832: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8833: #Trying to find the conditional for the file
1.620 albertel 8834: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8835: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8836: if ($match) {
1.289 bowersj2 8837: return (1,$1);
8838: } else {
1.434 www 8839: return (0,0);
1.289 bowersj2 8840: }
1.12 www 8841: }
8842:
1.427 www 8843: # --------------------------------------------------------- Get symb from alias
8844:
8845: sub get_symb_from_alias {
8846: my $symb=shift;
8847: my ($map,$resid,$url)=&decode_symb($symb);
8848: # Already is a symb
8849: if ($url) { return $symb; }
8850: # Must be an alias
8851: my $aliassymb='';
8852: my %bighash;
1.620 albertel 8853: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8854: &GDBM_READER(),0640)) {
8855: my $rid=$bighash{'mapalias_'.$symb};
8856: if ($rid) {
8857: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8858: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8859: $resid,$bighash{'src_'.$rid});
1.427 www 8860: }
8861: untie %bighash;
8862: }
8863: return $aliassymb;
8864: }
8865:
1.12 www 8866: # ----------------------------------------------------------------- Define Role
8867:
8868: sub definerole {
8869: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8870: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8871: foreach my $role (split(':',$sysrole)) {
8872: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8873: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8874: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8875: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8876: return "refused:s:$crole&$cqual";
8877: }
8878: }
1.191 harris41 8879: }
1.800 albertel 8880: foreach my $role (split(':',$domrole)) {
8881: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8882: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8883: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8884: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8885: return "refused:d:$crole&$cqual";
8886: }
8887: }
1.191 harris41 8888: }
1.800 albertel 8889: foreach my $role (split(':',$courole)) {
8890: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8891: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8892: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8893: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8894: return "refused:c:$crole&$cqual";
8895: }
8896: }
1.191 harris41 8897: }
1.1172.2.84 raeburn 8898: my $uhome;
8899: if (($uname ne '') && ($udom ne '')) {
8900: $uhome = &homeserver($uname,$udom);
8901: return $uhome if ($uhome eq 'no_host');
8902: } else {
8903: $uname = $env{'user.name'};
8904: $udom = $env{'user.domain'};
8905: $uhome = $env{'user.home'};
8906: }
1.620 albertel 8907: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8908: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8909: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8910: return reply($command,$uhome);
1.12 www 8911: } else {
8912: return 'refused';
8913: }
1.105 harris41 8914: }
8915:
8916: # ---------------- Make a metadata query against the network of library servers
8917:
8918: sub metadata_query {
1.1172.2.33 raeburn 8919: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8920: my %rhash;
1.845 albertel 8921: my %libserv = &all_library();
1.244 matthew 8922: my @server_list = (defined($server_array) ? @$server_array
8923: : keys(%libserv) );
8924: for my $server (@server_list) {
1.1172.2.33 raeburn 8925: my $domains = '';
8926: if (ref($domains_hash) eq 'HASH') {
8927: $domains = $domains_hash->{$server};
8928: }
1.118 harris41 8929: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8930: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8931: $rhash{$server}=$reply;
8932: }
8933: else {
8934: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8935: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8936: $server);
8937: $rhash{$server}=$reply;
8938: }
1.112 harris41 8939: }
1.118 harris41 8940: return \%rhash;
1.240 www 8941: }
8942:
8943: # ----------------------------------------- Send log queries and wait for reply
8944:
8945: sub log_query {
8946: my ($uname,$udom,$query,%filters)=@_;
8947: my $uhome=&homeserver($uname,$udom);
8948: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8949: my $uhost=&hostname($uhome);
1.800 albertel 8950: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8951: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8952: $uhome);
1.479 albertel 8953: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8954: return get_query_reply($queryid);
8955: }
8956:
1.818 raeburn 8957: # -------------------------- Update MySQL table for portfolio file
8958:
8959: sub update_portfolio_table {
1.821 raeburn 8960: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8961: if ($group ne '') {
8962: $file_name =~s /^\Q$group\E//;
8963: }
1.818 raeburn 8964: my $homeserver = &homeserver($uname,$udom);
8965: my $queryid=
1.821 raeburn 8966: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8967: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8968: my $reply = &get_query_reply($queryid);
8969: return $reply;
8970: }
8971:
1.899 raeburn 8972: # -------------------------- Update MySQL allusers table
8973:
8974: sub update_allusers_table {
8975: my ($uname,$udom,$names) = @_;
8976: my $homeserver = &homeserver($uname,$udom);
8977: my $queryid=
8978: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8979: 'lastname='.&escape($names->{'lastname'}).'%%'.
8980: 'firstname='.&escape($names->{'firstname'}).'%%'.
8981: 'middlename='.&escape($names->{'middlename'}).'%%'.
8982: 'generation='.&escape($names->{'generation'}).'%%'.
8983: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8984: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8985: return;
1.899 raeburn 8986: }
8987:
1.508 raeburn 8988: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8989:
8990: sub fetch_enrollment_query {
1.511 raeburn 8991: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8992: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8993: my $maxtries = 1;
1.508 raeburn 8994: if ($context eq 'automated') {
8995: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8996: $sleep = 2;
8997: $loopmax = 100;
1.547 raeburn 8998: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8999: } else {
9000: $homeserver = &homeserver($cnum,$dom);
9001: }
1.838 albertel 9002: my $host=&hostname($homeserver);
1.506 raeburn 9003: my $cmd = '';
1.1000 raeburn 9004: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9005: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9006: }
9007: $cmd =~ s/%%$//;
9008: $cmd = &escape($cmd);
9009: my $query = 'fetchenrollment';
1.620 albertel 9010: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9011: unless ($queryid=~/^\Q$host\E\_/) {
9012: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9013: return 'error: '.$queryid;
9014: }
1.1172.2.93 raeburn 9015: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9016: my $tries = 1;
9017: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 9018: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9019: $tries ++;
9020: }
1.526 raeburn 9021: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9022: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9023: } else {
1.901 albertel 9024: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9025: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9026: foreach my $line (@responses) {
9027: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9028: $$replyref{$key} = $value;
9029: }
9030: } else {
1.1117 foxr 9031: my $pathname = LONCAPA::tempdir();
1.800 albertel 9032: foreach my $line (@responses) {
9033: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9034: $$replyref{$key} = $value;
9035: if ($value > 0) {
1.800 albertel 9036: foreach my $item (@{$$affiliatesref{$key}}) {
9037: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9038: my $destname = $pathname.'/'.$filename;
9039: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9040: if ($xml_classlist =~ /^error/) {
9041: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9042: } else {
1.1172.2.96 raeburn 9043: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9044: print FILE &unescape($xml_classlist);
9045: close(FILE);
1.526 raeburn 9046: } else {
9047: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9048: }
9049: }
9050: }
9051: }
9052: }
9053: }
9054: return 'ok';
9055: }
9056: return 'error';
9057: }
9058:
1.242 www 9059: sub get_query_reply {
1.1172.2.79 raeburn 9060: my ($queryid,$sleep,$loopmax) = @_;
9061: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9062: $sleep = 0.2;
9063: }
9064: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9065: $loopmax = 100;
9066: }
1.1117 foxr 9067: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9068: my $reply='';
1.1172.2.79 raeburn 9069: for (1..$loopmax) {
9070: sleep($sleep);
1.240 www 9071: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9072: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9073: $reply = join('',<$fh>);
9074: close($fh);
1.240 www 9075: } else { return 'error: reply_file_error'; }
1.242 www 9076: return &unescape($reply);
9077: }
1.240 www 9078: }
1.242 www 9079: return 'timeout:'.$queryid;
1.240 www 9080: }
9081:
9082: sub courselog_query {
1.241 www 9083: #
9084: # possible filters:
9085: # url: url or symb
9086: # username
9087: # domain
9088: # action: view, submit, grade
9089: # start: timestamp
9090: # end: timestamp
9091: #
1.240 www 9092: my (%filters)=@_;
1.620 albertel 9093: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9094: if ($filters{'url'}) {
9095: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9096: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9097: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9098: }
1.620 albertel 9099: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9100: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9101: return &log_query($cname,$cdom,'courselog',%filters);
9102: }
9103:
9104: sub userlog_query {
1.858 raeburn 9105: #
9106: # possible filters:
9107: # action: log check role
9108: # start: timestamp
9109: # end: timestamp
9110: #
1.240 www 9111: my ($uname,$udom,%filters)=@_;
9112: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9113: }
9114:
1.506 raeburn 9115: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9116:
9117: sub auto_run {
1.508 raeburn 9118: my ($cnum,$cdom) = @_;
1.876 raeburn 9119: my $response = 0;
9120: my $settings;
9121: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9122: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9123: $settings = $domconfig{'autoenroll'};
9124: if ($settings->{'run'} eq '1') {
9125: $response = 1;
9126: }
9127: } else {
1.934 raeburn 9128: my $homeserver;
9129: if (&is_course($cdom,$cnum)) {
9130: $homeserver = &homeserver($cnum,$cdom);
9131: } else {
9132: $homeserver = &domain($cdom,'primary');
9133: }
9134: if ($homeserver ne 'no_host') {
9135: $response = &reply('autorun:'.$cdom,$homeserver);
9136: }
1.876 raeburn 9137: }
1.506 raeburn 9138: return $response;
9139: }
1.776 albertel 9140:
1.506 raeburn 9141: sub auto_get_sections {
1.508 raeburn 9142: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9143: my $homeserver;
9144: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9145: $homeserver = &homeserver($cnum,$cdom);
9146: }
9147: if (!defined($homeserver)) {
9148: if ($cdom =~ /^$match_domain$/) {
9149: $homeserver = &domain($cdom,'primary');
9150: }
9151: }
9152: my @secs;
9153: if (defined($homeserver)) {
9154: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9155: unless ($response eq 'refused') {
9156: @secs = split(/:/,$response);
9157: }
1.506 raeburn 9158: }
9159: return @secs;
9160: }
1.776 albertel 9161:
1.506 raeburn 9162: sub auto_new_course {
1.1099 raeburn 9163: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9164: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9165: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9166: return $response;
9167: }
1.776 albertel 9168:
1.506 raeburn 9169: sub auto_validate_courseID {
1.508 raeburn 9170: my ($cnum,$cdom,$inst_course_id) = @_;
9171: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9172: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9173: return $response;
9174: }
1.776 albertel 9175:
1.1007 raeburn 9176: sub auto_validate_instcode {
1.1020 raeburn 9177: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9178: my ($homeserver,$response);
9179: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9180: $homeserver = &homeserver($cnum,$cdom);
9181: }
9182: if (!defined($homeserver)) {
9183: if ($cdom =~ /^$match_domain$/) {
9184: $homeserver = &domain($cdom,'primary');
9185: }
9186: }
1.1065 raeburn 9187: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9188: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9189: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9190: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9191: }
9192:
1.1172.2.141 raeburn 9193: sub auto_validate_inst_crosslist {
9194: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9195: my ($homeserver,$response);
9196: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9197: $homeserver = &homeserver($cnum,$cdom);
9198: }
9199: if (!defined($homeserver)) {
9200: if ($cdom =~ /^$match_domain$/) {
9201: $homeserver = &domain($cdom,'primary');
9202: }
9203: }
9204: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9205: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9206: &escape($instcode).':'.&escape($inst_xlist).':'.
9207: &escape($coowner),$homeserver);
9208: }
9209: return $response;
9210: }
9211:
1.506 raeburn 9212: sub auto_create_password {
1.873 raeburn 9213: my ($cnum,$cdom,$authparam,$udom) = @_;
9214: my ($homeserver,$response);
1.506 raeburn 9215: my $create_passwd = 0;
9216: my $authchk = '';
1.873 raeburn 9217: if ($udom =~ /^$match_domain$/) {
9218: $homeserver = &domain($udom,'primary');
9219: }
9220: if ($homeserver eq '') {
9221: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9222: $homeserver = &homeserver($cnum,$cdom);
9223: }
9224: }
9225: if ($homeserver eq '') {
9226: $authchk = 'nodomain';
1.506 raeburn 9227: } else {
1.873 raeburn 9228: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9229: if ($response eq 'refused') {
9230: $authchk = 'refused';
9231: } else {
1.901 albertel 9232: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9233: }
1.506 raeburn 9234: }
9235: return ($authparam,$create_passwd,$authchk);
9236: }
9237:
1.706 raeburn 9238: sub auto_photo_permission {
9239: my ($cnum,$cdom,$students) = @_;
9240: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9241: my ($outcome,$perm_reqd,$conditions) =
9242: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9243: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9244: return (undef,undef);
9245: }
1.706 raeburn 9246: return ($outcome,$perm_reqd,$conditions);
9247: }
9248:
9249: sub auto_checkphotos {
9250: my ($uname,$udom,$pid) = @_;
9251: my $homeserver = &homeserver($uname,$udom);
9252: my ($result,$resulttype);
9253: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9254: &escape($uname).':'.&escape($pid),
9255: $homeserver));
1.709 albertel 9256: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9257: return (undef,undef);
9258: }
1.706 raeburn 9259: if ($outcome) {
9260: ($result,$resulttype) = split(/:/,$outcome);
9261: }
9262: return ($result,$resulttype);
9263: }
9264:
9265: sub auto_photochoice {
9266: my ($cnum,$cdom) = @_;
9267: my $homeserver = &homeserver($cnum,$cdom);
9268: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9269: &escape($cdom),
9270: $homeserver)));
1.709 albertel 9271: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9272: return (undef,undef);
9273: }
1.706 raeburn 9274: return ($update,$comment);
9275: }
9276:
9277: sub auto_photoupdate {
9278: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9279: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9280: my $host=&hostname($homeserver);
1.706 raeburn 9281: my $cmd = '';
9282: my $maxtries = 1;
1.800 albertel 9283: foreach my $affiliate (keys(%{$affiliatesref})) {
9284: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9285: }
9286: $cmd =~ s/%%$//;
9287: $cmd = &escape($cmd);
9288: my $query = 'institutionalphotos';
9289: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9290: unless ($queryid=~/^\Q$host\E\_/) {
9291: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9292: return 'error: '.$queryid;
9293: }
9294: my $reply = &get_query_reply($queryid);
9295: my $tries = 1;
9296: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9297: $reply = &get_query_reply($queryid);
9298: $tries ++;
9299: }
9300: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9301: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9302: } else {
9303: my @responses = split(/:/,$reply);
9304: my $outcome = shift(@responses);
9305: foreach my $item (@responses) {
9306: my ($key,$value) = split(/=/,$item);
9307: $$photo{$key} = $value;
9308: }
9309: return $outcome;
9310: }
9311: return 'error';
9312: }
9313:
1.521 raeburn 9314: sub auto_instcode_format {
1.793 albertel 9315: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9316: $cat_order) = @_;
1.521 raeburn 9317: my $courses = '';
1.772 raeburn 9318: my @homeservers;
1.521 raeburn 9319: if ($caller eq 'global') {
1.841 albertel 9320: my %servers = &get_servers($codedom,'library');
9321: foreach my $tryserver (keys(%servers)) {
9322: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9323: push(@homeservers,$tryserver);
9324: }
1.584 raeburn 9325: }
1.1022 raeburn 9326: } elsif ($caller eq 'requests') {
9327: if ($codedom =~ /^$match_domain$/) {
9328: my $chome = &domain($codedom,'primary');
9329: unless ($chome eq 'no_host') {
9330: push(@homeservers,$chome);
9331: }
9332: }
1.521 raeburn 9333: } else {
1.772 raeburn 9334: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9335: }
1.793 albertel 9336: foreach my $code (keys(%{$instcodes})) {
9337: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9338: }
9339: chop($courses);
1.772 raeburn 9340: my $ok_response = 0;
9341: my $response;
9342: while (@homeservers > 0 && $ok_response == 0) {
9343: my $server = shift(@homeservers);
9344: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9345: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9346: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9347: split(/:/,$response);
1.772 raeburn 9348: %{$codes} = (%{$codes},&str2hash($codes_str));
9349: push(@{$codetitles},&str2array($codetitles_str));
9350: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9351: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9352: $ok_response = 1;
9353: }
9354: }
9355: if ($ok_response) {
1.521 raeburn 9356: return 'ok';
1.772 raeburn 9357: } else {
9358: return $response;
1.521 raeburn 9359: }
9360: }
9361:
1.792 raeburn 9362: sub auto_instcode_defaults {
9363: my ($domain,$returnhash,$code_order) = @_;
9364: my @homeservers;
1.841 albertel 9365:
9366: my %servers = &get_servers($domain,'library');
9367: foreach my $tryserver (keys(%servers)) {
9368: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9369: push(@homeservers,$tryserver);
9370: }
1.792 raeburn 9371: }
1.841 albertel 9372:
1.792 raeburn 9373: my $response;
1.841 albertel 9374: foreach my $server (@homeservers) {
1.792 raeburn 9375: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9376: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9377:
9378: foreach my $pair (split(/\&/,$response)) {
9379: my ($name,$value)=split(/\=/,$pair);
9380: if ($name eq 'code_order') {
9381: @{$code_order} = split(/\&/,&unescape($value));
9382: } else {
9383: $returnhash->{&unescape($name)}=&unescape($value);
9384: }
9385: }
9386: return 'ok';
1.792 raeburn 9387: }
1.841 albertel 9388:
9389: return $response;
1.1003 raeburn 9390: }
9391:
9392: sub auto_possible_instcodes {
1.1007 raeburn 9393: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9394: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9395: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9396: return;
9397: }
1.1003 raeburn 9398: my (@homeservers,$uhome);
9399: if (defined(&domain($domain,'primary'))) {
9400: $uhome=&domain($domain,'primary');
9401: push(@homeservers,&domain($domain,'primary'));
9402: } else {
9403: my %servers = &get_servers($domain,'library');
9404: foreach my $tryserver (keys(%servers)) {
9405: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9406: push(@homeservers,$tryserver);
9407: }
9408: }
9409: }
9410: my $response;
9411: foreach my $server (@homeservers) {
9412: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9413: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9414: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9415: split(':',$response);
9416: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9417: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9418: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9419: my ($name,$value)=split('=',$item);
9420: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9421: }
9422: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9423: my ($name,$value)=split('=',$item);
9424: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9425: }
9426: return 'ok';
9427: }
9428: return $response;
9429: }
1.792 raeburn 9430:
1.1010 raeburn 9431: sub auto_courserequest_checks {
9432: my ($dom) = @_;
1.1020 raeburn 9433: my ($homeserver,%validations);
9434: if ($dom =~ /^$match_domain$/) {
9435: $homeserver = &domain($dom,'primary');
9436: }
9437: unless ($homeserver eq 'no_host') {
9438: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9439: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9440: my @items = split(/&/,$response);
9441: foreach my $item (@items) {
9442: my ($key,$value) = split('=',$item);
9443: $validations{&unescape($key)} = &thaw_unescape($value);
9444: }
9445: }
9446: }
1.1010 raeburn 9447: return %validations;
9448: }
9449:
1.1020 raeburn 9450: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9451: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9452: my ($homeserver,$response);
9453: if ($dom =~ /^$match_domain$/) {
9454: $homeserver = &domain($dom,'primary');
9455: }
1.1172.2.43 raeburn 9456: unless ($homeserver eq 'no_host') {
9457: my $customdata;
9458: if (ref($custominfo) eq 'HASH') {
9459: $customdata = &freeze_escape($custominfo);
9460: }
1.1020 raeburn 9461: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9462: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9463: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9464: $customdata,$homeserver));
1.1020 raeburn 9465: }
9466: return $response;
9467: }
9468:
1.777 albertel 9469: sub auto_validate_class_sec {
1.918 raeburn 9470: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9471: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9472: my $ownerlist;
9473: if (ref($owners) eq 'ARRAY') {
9474: $ownerlist = join(',',@{$owners});
9475: } else {
9476: $ownerlist = $owners;
9477: }
1.773 raeburn 9478: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9479: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9480: return $response;
9481: }
9482:
1.1172.2.141 raeburn 9483: sub auto_instsec_reformat {
9484: my ($cdom,$action,$instsecref) = @_;
9485: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9486: my @homeservers;
9487: if (defined(&domain($cdom,'primary'))) {
9488: push(@homeservers,&domain($cdom,'primary'));
9489: } else {
9490: my %servers = &get_servers($cdom,'library');
9491: foreach my $tryserver (keys(%servers)) {
9492: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9493: push(@homeservers,$tryserver);
9494: }
9495: }
9496: }
9497: my $response;
9498: my %reformatted = %{$instsecref};
9499: foreach my $server (@homeservers) {
9500: if (ref($instsecref) eq 'HASH') {
9501: my $info = &freeze_escape($instsecref);
9502: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9503: $action.':'.$info,$server);
9504: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9505: my @items = split(/&/,$response);
9506: foreach my $item (@items) {
9507: my ($key,$value) = split(/=/,$item);
9508: $reformatted{&unescape($key)} = &thaw_unescape($value);
9509: }
9510: }
9511: }
9512: return %reformatted;
9513: }
9514:
1.1172.2.94 raeburn 9515: sub auto_validate_instclasses {
9516: my ($cdom,$cnum,$owners,$classesref) = @_;
9517: my ($homeserver,%validations);
9518: $homeserver = &homeserver($cnum,$cdom);
9519: unless ($homeserver eq 'no_host') {
9520: my $ownerlist;
9521: if (ref($owners) eq 'ARRAY') {
9522: $ownerlist = join(',',@{$owners});
9523: } else {
9524: $ownerlist = $owners;
9525: }
9526: if (ref($classesref) eq 'HASH') {
9527: my $classes = &freeze_escape($classesref);
9528: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9529: ':'.$cdom.':'.$classes,$homeserver);
9530: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9531: my @items = split(/&/,$response);
9532: foreach my $item (@items) {
9533: my ($key,$value) = split('=',$item);
9534: $validations{&unescape($key)} = &thaw_unescape($value);
9535: }
9536: }
9537: }
9538: }
9539: return %validations;
9540: }
9541:
1.1172.2.38 raeburn 9542: sub auto_crsreq_update {
9543: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9544: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9545: my ($homeserver,%crsreqresponse);
9546: if ($cdom =~ /^$match_domain$/) {
9547: $homeserver = &domain($cdom,'primary');
9548: }
9549: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9550: my $info;
9551: if (ref($inbound) eq 'HASH') {
9552: $info = &freeze_escape($inbound);
9553: }
9554: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9555: ':'.&escape($action).':'.&escape($ownername).':'.
9556: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9557: &escape($title).':'.&escape($code).':'.
9558: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9559: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9560: my @items = split(/&/,$response);
9561: foreach my $item (@items) {
9562: my ($key,$value) = split('=',$item);
9563: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9564: }
9565: }
9566: }
9567: return \%crsreqresponse;
9568: }
9569:
1.1172.2.78 raeburn 9570: sub auto_export_grades {
9571: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9572: my ($homeserver,%exportresponse);
9573: if ($cdom =~ /^$match_domain$/) {
9574: $homeserver = &domain($cdom,'primary');
9575: }
9576: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9577: my $info;
9578: if (ref($inforef) eq 'HASH') {
9579: $info = &freeze_escape($inforef);
9580: }
9581: if (ref($gradesref) eq 'HASH') {
9582: my $grades = &freeze_escape($gradesref);
9583: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9584: $info.':'.$grades,$homeserver);
9585: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9586: my @items = split(/&/,$response);
9587: foreach my $item (@items) {
9588: my ($key,$value) = split('=',$item);
9589: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9590: }
9591: }
9592: }
9593: }
9594: return \%exportresponse;
9595: }
9596:
1.1172.2.68 raeburn 9597: sub check_instcode_cloning {
9598: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9599: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9600: return;
9601: }
9602: my $canclone;
9603: if (@{$code_order} > 0) {
9604: my $instcoderegexp ='^';
9605: my @clonecodes = split(/\&/,$cloner);
9606: foreach my $item (@{$code_order}) {
9607: if (grep(/^\Q$item\E=/,@clonecodes)) {
9608: foreach my $pair (@clonecodes) {
9609: my ($key,$val) = split(/\=/,$pair,2);
9610: $val = &unescape($val);
9611: if ($key eq $item) {
9612: $instcoderegexp .= '('.$val.')';
9613: last;
9614: }
9615: }
9616: } else {
9617: $instcoderegexp .= $codedefaults->{$item};
9618: }
9619: }
9620: $instcoderegexp .= '$';
9621: my (@from,@to);
9622: eval {
9623: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9624: (@to) = ($clonetocode =~ /$instcoderegexp/);
9625: };
9626: if ((@from > 0) && (@to > 0)) {
9627: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9628: if (!@diffs) {
9629: $canclone = 1;
9630: }
9631: }
9632: }
9633: return $canclone;
9634: }
9635:
9636: sub default_instcode_cloning {
9637: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9638: my (%codedefaults,@code_order,$canclone);
9639: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9640: %codedefaults = %{$codedefaultsref};
9641: @code_order = @{$codeorderref};
9642: } elsif ($clonedom) {
9643: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9644: }
9645: if (($domdefclone) && (@code_order)) {
9646: my @clonecodes = split(/\+/,$domdefclone);
9647: my $instcoderegexp ='^';
9648: foreach my $item (@code_order) {
9649: if (grep(/^\Q$item\E$/,@clonecodes)) {
9650: $instcoderegexp .= '('.$codedefaults{$item}.')';
9651: } else {
9652: $instcoderegexp .= $codedefaults{$item};
9653: }
9654: }
9655: $instcoderegexp .= '$';
9656: my (@from,@to);
9657: eval {
9658: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9659: (@to) = ($clonetocode =~ /$instcoderegexp/);
9660: };
9661: if ((@from > 0) && (@to > 0)) {
9662: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9663: if (!@diffs) {
9664: $canclone = 1;
9665: }
9666: }
9667: }
9668: return $canclone;
9669: }
9670:
1.679 raeburn 9671: # ------------------------------------------------------- Course Group routines
9672:
9673: sub get_coursegroups {
1.809 raeburn 9674: my ($cdom,$cnum,$group,$namespace) = @_;
9675: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9676: }
9677:
1.679 raeburn 9678: sub modify_coursegroup {
9679: my ($cdom,$cnum,$groupsettings) = @_;
9680: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9681: }
9682:
1.809 raeburn 9683: sub toggle_coursegroup_status {
9684: my ($cdom,$cnum,$group,$action) = @_;
9685: my ($from_namespace,$to_namespace);
9686: if ($action eq 'delete') {
9687: $from_namespace = 'coursegroups';
9688: $to_namespace = 'deleted_groups';
9689: } else {
9690: $from_namespace = 'deleted_groups';
9691: $to_namespace = 'coursegroups';
9692: }
9693: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9694: if (my $tmp = &error(%curr_group)) {
9695: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9696: return ('read error',$tmp);
9697: } else {
9698: my %savedsettings = %curr_group;
1.809 raeburn 9699: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9700: my $deloutcome;
9701: if ($result eq 'ok') {
1.809 raeburn 9702: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9703: } else {
9704: return ('write error',$result);
9705: }
9706: if ($deloutcome eq 'ok') {
9707: return 'ok';
9708: } else {
9709: return ('delete error',$deloutcome);
9710: }
9711: }
9712: }
9713:
1.679 raeburn 9714: sub modify_group_roles {
1.957 raeburn 9715: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9716: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9717: my $role = 'gr/'.&escape($userprivs);
9718: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9719: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9720: if ($result eq 'ok') {
9721: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9722: }
1.679 raeburn 9723: return $result;
9724: }
9725:
9726: sub modify_coursegroup_membership {
9727: my ($cdom,$cnum,$membership) = @_;
9728: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9729: return $result;
9730: }
9731:
1.682 raeburn 9732: sub get_active_groups {
9733: my ($udom,$uname,$cdom,$cnum) = @_;
9734: my $now = time;
9735: my %groups = ();
9736: foreach my $key (keys(%env)) {
1.811 albertel 9737: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9738: my ($start,$end) = split(/\./,$env{$key});
9739: if (($end!=0) && ($end<$now)) { next; }
9740: if (($start!=0) && ($start>$now)) { next; }
9741: if ($1 eq $cdom && $2 eq $cnum) {
9742: $groups{$3} = $env{$key} ;
9743: }
9744: }
9745: }
9746: return %groups;
9747: }
9748:
1.683 raeburn 9749: sub get_group_membership {
9750: my ($cdom,$cnum,$group) = @_;
9751: return(&dump('groupmembership',$cdom,$cnum,$group));
9752: }
9753:
9754: sub get_users_groups {
9755: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9756: my @usersgroups;
1.683 raeburn 9757: my $cachetime=1800;
9758:
9759: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9760: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9761: if (defined($cached)) {
1.734 albertel 9762: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9763: } else {
9764: $grouplist = '';
1.816 raeburn 9765: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9766: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9767: my $access_end = $env{'course.'.$courseid.
9768: '.default_enrollment_end_date'};
9769: my $now = time;
9770: foreach my $key (keys(%roleshash)) {
9771: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9772: my $group = $1;
9773: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9774: my $start = $2;
9775: my $end = $1;
9776: if ($start == -1) { next; } # deleted from group
9777: if (($start!=0) && ($start>$now)) { next; }
9778: if (($end!=0) && ($end<$now)) {
9779: if ($access_end && $access_end < $now) {
9780: if ($access_end - $end < 86400) {
9781: push(@usersgroups,$group);
1.733 raeburn 9782: }
9783: }
1.817 raeburn 9784: next;
1.733 raeburn 9785: }
1.817 raeburn 9786: push(@usersgroups,$group);
1.683 raeburn 9787: }
9788: }
9789: }
1.817 raeburn 9790: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9791: $grouplist = join(':',@usersgroups);
9792: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9793: }
1.733 raeburn 9794: return @usersgroups;
1.683 raeburn 9795: }
9796:
9797: sub devalidate_getgroups_cache {
9798: my ($udom,$uname,$cdom,$cnum)=@_;
9799: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9800:
1.683 raeburn 9801: my $hashid="$udom:$uname:$courseid";
9802: &devalidate_cache_new('getgroups',$hashid);
9803: }
9804:
1.12 www 9805: # ------------------------------------------------------------------ Plain Text
9806:
9807: sub plaintext {
1.988 raeburn 9808: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9809: if ($short =~ m{^cr/}) {
1.758 albertel 9810: return (split('/',$short))[-1];
9811: }
1.742 raeburn 9812: if (!defined($cid)) {
9813: $cid = $env{'request.course.id'};
9814: }
9815: my %rolenames = (
1.1008 raeburn 9816: Course => 'std',
9817: Community => 'alt1',
1.742 raeburn 9818: );
1.1037 raeburn 9819: if ($cid ne '') {
9820: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9821: unless ($forcedefault) {
9822: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9823: &Apache::lonlocal::mt_escape(\$roletext);
9824: return &Apache::lonlocal::mt($roletext);
9825: }
9826: }
9827: }
9828: if ((defined($type)) && (defined($rolenames{$type})) &&
9829: (defined($rolenames{$type})) &&
9830: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9831: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9832: } elsif ($cid ne '') {
9833: my $crstype = $env{'course.'.$cid.'.type'};
9834: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9835: (defined($prp{$short}{$rolenames{$crstype}}))) {
9836: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9837: }
1.742 raeburn 9838: }
1.1037 raeburn 9839: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9840: }
9841:
9842: # ----------------------------------------------------------------- Assign Role
9843:
9844: sub assignrole {
1.957 raeburn 9845: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9846: $context)=@_;
1.21 www 9847: my $mrole;
9848: if ($role =~ /^cr\//) {
1.393 www 9849: my $cwosec=$url;
1.811 albertel 9850: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9851: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9852: my $refused = 1;
9853: if ($context eq 'requestcourses') {
9854: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9855: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9856: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9857: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9858: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9859: if ($crsenv{'internal.courseowner'} eq
9860: $env{'user.name'}.':'.$env{'user.domain'}) {
9861: $refused = '';
9862: }
9863: }
9864: }
9865: }
9866: }
9867: if ($refused) {
9868: &logthis('Refused custom assignrole: '.
9869: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9870: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9871: return 'refused';
9872: }
1.104 www 9873: }
1.21 www 9874: $mrole='cr';
1.678 raeburn 9875: } elsif ($role =~ /^gr\//) {
9876: my $cwogrp=$url;
1.811 albertel 9877: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9878: unless (&allowed('mdg',$cwogrp)) {
9879: &logthis('Refused group assignrole: '.
9880: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9881: $env{'user.name'}.' at '.$env{'user.domain'});
9882: return 'refused';
9883: }
9884: $mrole='gr';
1.21 www 9885: } else {
1.82 www 9886: my $cwosec=$url;
1.811 albertel 9887: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9888: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9889: my $refused;
9890: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9891: if (!(&allowed('c'.$role,$url))) {
9892: $refused = 1;
9893: }
9894: } else {
9895: $refused = 1;
9896: }
1.947 raeburn 9897: if ($refused) {
1.1045 raeburn 9898: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9899: if (!$selfenroll && $context eq 'course') {
9900: my %crsenv;
9901: if ($role eq 'cc' || $role eq 'co') {
9902: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9903: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9904: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9905: if ($crsenv{'internal.courseowner'} eq
9906: $env{'user.name'}.':'.$env{'user.domain'}) {
9907: $refused = '';
9908: }
9909: }
9910: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9911: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9912: if ($crsenv{'internal.courseowner'} eq
9913: $env{'user.name'}.':'.$env{'user.domain'}) {
9914: $refused = '';
9915: }
9916: }
9917: }
9918: }
9919: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9920: $refused = '';
1.1017 raeburn 9921: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9922: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9923: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9924: my $wrongcc;
9925: if ($cnum =~ /^$match_community$/) {
9926: $wrongcc = 1 if ($role eq 'cc');
9927: } else {
9928: $wrongcc = 1 if ($role eq 'co');
9929: }
9930: unless ($wrongcc) {
9931: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9932: if ($crsenv{'internal.courseowner'} eq
9933: $env{'user.name'}.':'.$env{'user.domain'}) {
9934: $refused = '';
9935: }
1.1017 raeburn 9936: }
9937: }
1.1172.2.9 raeburn 9938: } elsif ($context eq 'requestauthor') {
9939: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9940: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9941: if ($env{'environment.requestauthor'} eq 'automatic') {
9942: $refused = '';
9943: } else {
9944: my %domdefaults = &get_domain_defaults($udom);
9945: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9946: my $checkbystatus;
9947: if ($env{'user.adv'}) {
9948: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9949: if ($disposition eq 'automatic') {
9950: $refused = '';
9951: } elsif ($disposition eq '') {
9952: $checkbystatus = 1;
9953: }
9954: } else {
9955: $checkbystatus = 1;
9956: }
9957: if ($checkbystatus) {
9958: if ($env{'environment.inststatus'}) {
9959: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9960: foreach my $type (@inststatuses) {
9961: if (($type ne '') &&
9962: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9963: $refused = '';
9964: }
9965: }
9966: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9967: $refused = '';
9968: }
9969: }
9970: }
9971: }
9972: }
1.1017 raeburn 9973: }
9974: if ($refused) {
1.947 raeburn 9975: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9976: ' '.$role.' '.$end.' '.$start.' by '.
9977: $env{'user.name'}.' at '.$env{'user.domain'});
9978: return 'refused';
9979: }
1.932 raeburn 9980: }
1.1131 raeburn 9981: } elsif ($role eq 'au') {
9982: if ($url ne '/'.$udom.'/') {
9983: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9984: ' to assign author role for '.$uname.':'.$udom.
9985: ' in domain: '.$url.' refused (wrong domain).');
9986: return 'refused';
9987: }
1.104 www 9988: }
1.21 www 9989: $mrole=$role;
9990: }
1.620 albertel 9991: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9992: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9993: if ($end) { $command.='_'.$end; }
1.21 www 9994: if ($start) {
9995: if ($end) {
1.81 www 9996: $command.='_'.$start;
1.21 www 9997: } else {
1.81 www 9998: $command.='_0_'.$start;
1.21 www 9999: }
10000: }
1.739 raeburn 10001: my $origstart = $start;
10002: my $origend = $end;
1.957 raeburn 10003: my $delflag;
1.357 www 10004: # actually delete
10005: if ($deleteflag) {
1.373 www 10006: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10007: # modify command to delete the role
1.620 albertel 10008: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10009: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10010: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10011: # set start and finish to negative values for userrolelog
10012: $start=-1;
10013: $end=-1;
1.957 raeburn 10014: $delflag = 1;
1.357 www 10015: }
10016: }
10017: # send command
1.349 www 10018: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10019: # log new user role if status is ok
1.349 www 10020: if ($answer eq 'ok') {
1.663 raeburn 10021: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 10022: if (($role eq 'cc') || ($role eq 'in') ||
10023: ($role eq 'ep') || ($role eq 'ad') ||
10024: ($role eq 'ta') || ($role eq 'st') ||
10025: ($role=~/^cr/) || ($role eq 'gr') ||
10026: ($role eq 'co')) {
1.1172.2.13 raeburn 10027: # for course roles, perform group memberships changes triggered by role change.
10028: unless ($role =~ /^gr/) {
10029: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10030: $origstart,$selfenroll,$context);
10031: }
1.1172.2.9 raeburn 10032: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10033: $selfenroll,$context);
10034: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10035: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10036: ($role eq 'da')) {
1.1172.2.9 raeburn 10037: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10038: $context);
10039: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10040: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10041: $context);
10042: }
1.1053 raeburn 10043: if ($role eq 'cc') {
10044: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10045: }
1.349 www 10046: }
10047: return $answer;
1.169 harris41 10048: }
10049:
1.1053 raeburn 10050: sub autoupdate_coowners {
10051: my ($url,$end,$start,$uname,$udom) = @_;
10052: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10053: if (($cdom ne '') && ($cnum ne '')) {
10054: my $now = time;
10055: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10056: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10057: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10058: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10059: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10060: if ($instcode ne '') {
1.1056 raeburn 10061: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10062: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10063: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10064: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10065: unless ($result eq 'valid') {
10066: if ($xlists ne '') {
10067: foreach my $xlist (split(',',$xlists)) {
10068: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10069: $result =
10070: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10071: $inst_crosslist,$uname.':'.$udom);
10072: last if ($result eq 'valid');
10073: }
10074: }
10075: }
1.1056 raeburn 10076: if ($result eq 'valid') {
10077: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10078: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10079: push(@newcoowners,$coowner);
10080: }
10081: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10082: push(@newcoowners,$uname.':'.$udom);
10083: }
10084: @newcoowners = sort(@newcoowners);
10085: } else {
10086: push(@newcoowners,$uname.':'.$udom);
10087: }
1.1172.2.141 raeburn 10088: } elsif ($coursehash{'internal.co-owners'}) {
10089: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10090: unless ($coowner eq $uname.':'.$udom) {
10091: push(@newcoowners,$coowner);
1.1053 raeburn 10092: }
10093: }
1.1172.2.141 raeburn 10094: unless (@newcoowners > 0) {
10095: $delcoowners = 1;
10096: $coowners = '';
10097: }
1.1053 raeburn 10098: }
10099: if (@newcoowners || $delcoowners) {
10100: &store_coowners($cdom,$cnum,$coursehash{'home'},
10101: $delcoowners,@newcoowners);
10102: }
10103: }
10104: }
10105: }
10106: }
10107: }
10108: }
10109:
10110: sub store_coowners {
10111: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10112: my $cid = $cdom.'_'.$cnum;
10113: my ($coowners,$delresult,$putresult);
10114: if (@newcoowners) {
10115: $coowners = join(',',@newcoowners);
10116: my %coownershash = (
10117: 'internal.co-owners' => $coowners,
10118: );
10119: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10120: if ($putresult eq 'ok') {
10121: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10122: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10123: }
10124: }
10125: }
10126: if ($delcoowners) {
10127: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10128: if ($delresult eq 'ok') {
10129: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10130: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10131: }
10132: }
10133: }
10134: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10135: my %crsinfo =
10136: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10137: if (ref($crsinfo{$cid}) eq 'HASH') {
10138: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10139: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10140: }
10141: }
10142: }
10143:
1.169 harris41 10144: # -------------------------------------------------- Modify user authentication
1.197 www 10145: # Overrides without validation
10146:
1.169 harris41 10147: sub modifyuserauth {
10148: my ($udom,$uname,$umode,$upass)=@_;
10149: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10150: my $allowed;
10151: if (&allowed('mau',$udom)) {
10152: $allowed = 1;
10153: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10154: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10155: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10156: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10157: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10158: if (($cdom ne '') && ($cnum ne '')) {
10159: my $is_owner = &is_course_owner($cdom,$cnum);
10160: if ($is_owner) {
10161: $allowed = 1;
10162: }
10163: }
10164: }
10165: unless ($allowed) { return 'refused'; }
1.197 www 10166: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10167: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10168: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10169: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10170: &escape($upass),$uhome);
1.1172.2.134 raeburn 10171: my $ip = &get_requestor_ip();
1.620 albertel 10172: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10173: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10174: '(Remote '.$ip.'): '.$reply);
1.197 www 10175: &log($udom,,$uname,$uhome,
1.620 albertel 10176: 'Authentication changed by '.$env{'user.domain'}.', '.
10177: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10178: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10179: unless ($reply eq 'ok') {
1.197 www 10180: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10181: return 'error: '.$reply;
10182: }
1.170 harris41 10183: return 'ok';
1.80 www 10184: }
10185:
1.81 www 10186: # --------------------------------------------------------------- Modify a user
1.80 www 10187:
1.81 www 10188: sub modifyuser {
1.206 matthew 10189: my ($udom, $uname, $uid,
10190: $umode, $upass, $first,
10191: $middle, $last, $gene,
1.1058 raeburn 10192: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10193: $udom= &LONCAPA::clean_domain($udom);
10194: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10195: my $showcandelete = 'none';
10196: if (ref($candelete) eq 'ARRAY') {
10197: if (@{$candelete} > 0) {
10198: $showcandelete = join(', ',@{$candelete});
10199: }
10200: }
1.81 www 10201: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10202: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10203: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10204: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10205: ' desiredhome not specified').
1.620 albertel 10206: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10207: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10208: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10209: my $newuser;
10210: if ($uhome eq 'no_host') {
10211: $newuser = 1;
10212: }
1.80 www 10213: # ----------------------------------------------------------------- Create User
1.406 albertel 10214: if (($uhome eq 'no_host') &&
10215: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10216: my $unhome='';
1.844 albertel 10217: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10218: $unhome = $desiredhome;
1.620 albertel 10219: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10220: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10221: } else { # load balancing routine for determining $unhome
1.81 www 10222: my $loadm=10000000;
1.841 albertel 10223: my %servers = &get_servers($udom,'library');
10224: foreach my $tryserver (keys(%servers)) {
10225: my $answer=reply('load',$tryserver);
10226: if (($answer=~/\d+/) && ($answer<$loadm)) {
10227: $loadm=$answer;
10228: $unhome=$tryserver;
10229: }
1.80 www 10230: }
10231: }
10232: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10233: return 'error: unable to find a home server for '.$uname.
10234: ' in domain '.$udom;
1.80 www 10235: }
10236: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10237: &escape($upass),$unhome);
10238: unless ($reply eq 'ok') {
10239: return 'error: '.$reply;
10240: }
1.230 stredwic 10241: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10242: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10243: return 'error: unable verify users home machine.';
1.80 www 10244: }
1.209 matthew 10245: } # End of creation of new user
1.80 www 10246: # ---------------------------------------------------------------------- Add ID
10247: if ($uid) {
10248: $uid=~tr/A-Z/a-z/;
10249: my %uidhash=&idrget($udom,$uname);
1.196 www 10250: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10251: && (!$forceid)) {
1.80 www 10252: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10253: return 'error: user id "'.$uid.'" does not match '.
10254: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10255: }
10256: } else {
10257: &idput($udom,($uname => $uid));
10258: }
10259: }
10260: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10261: my @tmp=&get('environment',
1.899 raeburn 10262: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10263: 'permanentemail','inststatus'],
1.134 albertel 10264: $udom,$uname);
1.1075 raeburn 10265: my (%names,%oldnames);
1.313 matthew 10266: if ($tmp[0] =~ m/^error:.*/) {
10267: %names=();
10268: } else {
10269: %names = @tmp;
1.1075 raeburn 10270: %oldnames = %names;
1.313 matthew 10271: }
1.388 www 10272: #
1.1058 raeburn 10273: # If name, email and/or uid are blank (e.g., because an uploaded file
10274: # of users did not contain them), do not overwrite existing values
10275: # unless field is in $candelete array ref.
10276: #
10277:
10278: my @fields = ('firstname','middlename','lastname','generation',
10279: 'permanentemail','id');
10280: my %newvalues;
10281: if (ref($candelete) eq 'ARRAY') {
10282: foreach my $field (@fields) {
10283: if (grep(/^\Q$field\E$/,@{$candelete})) {
10284: if ($field eq 'firstname') {
10285: $names{$field} = $first;
10286: } elsif ($field eq 'middlename') {
10287: $names{$field} = $middle;
10288: } elsif ($field eq 'lastname') {
10289: $names{$field} = $last;
10290: } elsif ($field eq 'generation') {
10291: $names{$field} = $gene;
10292: } elsif ($field eq 'permanentemail') {
10293: $names{$field} = $email;
10294: } elsif ($field eq 'id') {
10295: $names{$field} = $uid;
10296: }
10297: }
10298: }
10299: }
1.388 www 10300: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10301: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10302: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10303: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10304: if ($email) {
10305: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10306: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10307: }
1.899 raeburn 10308: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10309: if (defined($inststatus)) {
10310: $names{'inststatus'} = '';
10311: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10312: if (ref($usertypes) eq 'HASH') {
10313: my @okstatuses;
10314: foreach my $item (split(/:/,$inststatus)) {
10315: if (defined($usertypes->{$item})) {
10316: push(@okstatuses,$item);
10317: }
10318: }
10319: if (@okstatuses) {
10320: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10321: }
10322: }
10323: }
1.1075 raeburn 10324: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10325: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10326: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10327: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10328: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10329: } else {
10330: $logmsg .= ' during self creation';
10331: }
1.1075 raeburn 10332: my $changed;
10333: if ($newuser) {
10334: $changed = 1;
10335: } else {
10336: foreach my $field (@fields) {
10337: if ($names{$field} ne $oldnames{$field}) {
10338: $changed = 1;
10339: last;
10340: }
10341: }
10342: }
10343: unless ($changed) {
10344: $logmsg = 'No changes in user information needed for: '.$logmsg;
10345: &logthis($logmsg);
10346: return 'ok';
10347: }
10348: my $reply = &put('environment', \%names, $udom,$uname);
10349: if ($reply ne 'ok') {
10350: return 'error: '.$reply;
10351: }
1.1087 raeburn 10352: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10353: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10354: }
1.1075 raeburn 10355: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10356: &devalidate_cache_new('namescache',$uname.':'.$udom);
10357: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10358: &logthis($logmsg);
1.134 albertel 10359: return 'ok';
1.80 www 10360: }
10361:
1.81 www 10362: # -------------------------------------------------------------- Modify student
1.80 www 10363:
1.81 www 10364: sub modifystudent {
10365: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10366: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10367: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10368: if (!$cid) {
1.620 albertel 10369: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10370: return 'not_in_class';
10371: }
1.80 www 10372: }
10373: # --------------------------------------------------------------- Make the user
1.81 www 10374: my $reply=&modifyuser
1.209 matthew 10375: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10376: $desiredhome,$email,$inststatus);
1.80 www 10377: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10378: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10379: # student's environment
1.297 matthew 10380: $uid = undef if (!$forceid);
1.455 albertel 10381: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10382: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10383: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10384: return $reply;
10385: }
10386:
10387: sub modify_student_enrollment {
1.1172.2.23 raeburn 10388: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10389: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10390: my ($cdom,$cnum,$chome);
10391: if (!$cid) {
1.620 albertel 10392: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10393: return 'not_in_class';
10394: }
1.620 albertel 10395: $cdom=$env{'course.'.$cid.'.domain'};
10396: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10397: } else {
10398: ($cdom,$cnum)=split(/_/,$cid);
10399: }
1.620 albertel 10400: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10401: if (!$chome) {
1.457 raeburn 10402: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10403: }
1.455 albertel 10404: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10405: # Make sure the user exists
1.81 www 10406: my $uhome=&homeserver($uname,$udom);
10407: if (($uhome eq '') || ($uhome eq 'no_host')) {
10408: return 'error: no such user';
10409: }
1.297 matthew 10410: # Get student data if we were not given enough information
10411: if (!defined($first) || $first eq '' ||
10412: !defined($last) || $last eq '' ||
10413: !defined($uid) || $uid eq '' ||
10414: !defined($middle) || $middle eq '' ||
10415: !defined($gene) || $gene eq '') {
1.294 matthew 10416: # They did not supply us with enough data to enroll the student, so
10417: # we need to pick up more information.
1.297 matthew 10418: my %tmp = &get('environment',
1.294 matthew 10419: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10420: ,$udom,$uname);
10421:
1.800 albertel 10422: #foreach my $key (keys(%tmp)) {
10423: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10424: #}
1.294 matthew 10425: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10426: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10427: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10428: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10429: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10430: }
1.556 albertel 10431: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10432: my $user = "$uname:$udom";
10433: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10434: my $reply=cput('classlist',
1.1148 raeburn 10435: {$user =>
1.1172.2.76 raeburn 10436: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10437: $cdom,$cnum);
1.1148 raeburn 10438: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10439: &devalidate_getsection_cache($udom,$uname,$cid);
10440: } else {
1.81 www 10441: return 'error: '.$reply;
10442: }
1.297 matthew 10443: # Add student role to user
1.83 www 10444: my $uurl='/'.$cid;
1.81 www 10445: $uurl=~s/\_/\//g;
10446: if ($usec) {
10447: $uurl.='/'.$usec;
10448: }
1.1148 raeburn 10449: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10450: $selfenroll,$context);
10451: if ($result ne 'ok') {
10452: if ($old_entry{$user} ne '') {
10453: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10454: } else {
10455: $reply = &del('classlist',[$user],$cdom,$cnum);
10456: }
10457: }
10458: return $result;
1.21 www 10459: }
10460:
1.556 albertel 10461: sub format_name {
10462: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10463: my $name;
10464: if ($first ne 'lastname') {
10465: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10466: } else {
10467: if ($lastname=~/\S/) {
10468: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10469: $name=~s/\s+,/,/;
10470: } else {
10471: $name.= $firstname.' '.$middlename.' '.$generation;
10472: }
10473: }
10474: $name=~s/^\s+//;
10475: $name=~s/\s+$//;
10476: $name=~s/\s+/ /g;
10477: return $name;
10478: }
10479:
1.84 www 10480: # ------------------------------------------------- Write to course preferences
10481:
10482: sub writecoursepref {
10483: my ($courseid,%prefs)=@_;
10484: $courseid=~s/^\///;
10485: $courseid=~s/\_/\//g;
10486: my ($cdomain,$cnum)=split(/\//,$courseid);
10487: my $chome=homeserver($cnum,$cdomain);
10488: if (($chome eq '') || ($chome eq 'no_host')) {
10489: return 'error: no such course';
10490: }
10491: my $cstring='';
1.800 albertel 10492: foreach my $pref (keys(%prefs)) {
10493: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10494: }
1.84 www 10495: $cstring=~s/\&$//;
10496: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10497: }
10498:
10499: # ---------------------------------------------------------- Make/modify course
10500:
10501: sub createcourse {
1.741 raeburn 10502: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10503: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10504: $url=&declutter($url);
10505: my $cid='';
1.1028 raeburn 10506: if ($context eq 'requestcourses') {
10507: my $can_create = 0;
10508: my ($ownername,$ownerdom) = split(':',$course_owner);
10509: if ($udom eq $ownerdom) {
10510: if (&usertools_access($ownername,$ownerdom,$category,undef,
10511: $context)) {
10512: $can_create = 1;
10513: }
10514: } else {
10515: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10516: $category);
10517: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10518: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10519: if (@curr > 0) {
10520: my @options = qw(approval validate autolimit);
10521: my $optregex = join('|',@options);
10522: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10523: $can_create = 1;
10524: }
10525: }
10526: }
10527: }
10528: if ($can_create) {
10529: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10530: unless (&allowed('ccc',$udom)) {
10531: return 'refused';
10532: }
1.1017 raeburn 10533: }
10534: } else {
10535: return 'refused';
10536: }
1.1028 raeburn 10537: } elsif (!&allowed('ccc',$udom)) {
10538: return 'refused';
1.84 www 10539: }
1.1011 raeburn 10540: # --------------------------------------------------------------- Get Unique ID
10541: my $uname;
10542: if ($cnum =~ /^$match_courseid$/) {
10543: my $chome=&homeserver($cnum,$udom,'true');
10544: if (($chome eq '') || ($chome eq 'no_host')) {
10545: $uname = $cnum;
10546: } else {
1.1038 raeburn 10547: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10548: }
10549: } else {
1.1038 raeburn 10550: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10551: }
10552: return $uname if ($uname =~ /^error/);
10553: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10554: if (!defined($course_server)) {
10555: if (defined(&domain($udom,'primary'))) {
10556: $course_server = &domain($udom,'primary');
10557: } else {
10558: $course_server = $env{'user.home'};
10559: }
10560: }
10561: my %host_servers =
10562: &Apache::lonnet::get_servers($udom,'library');
10563: unless ($host_servers{$course_server}) {
10564: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10565: }
1.84 www 10566: # ------------------------------------------------------------- Make the course
10567: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10568: $course_server);
1.84 www 10569: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10570: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10571: if (($uhome eq '') || ($uhome eq 'no_host')) {
10572: return 'error: no such course';
10573: }
1.271 www 10574: # ----------------------------------------------------------------- Course made
1.516 raeburn 10575: # log existence
1.1029 raeburn 10576: my $now = time;
1.918 raeburn 10577: my $newcourse = {
10578: $udom.'_'.$uname => {
1.921 raeburn 10579: description => $description,
10580: inst_code => $inst_code,
10581: owner => $course_owner,
10582: type => $crstype,
1.1029 raeburn 10583: creator => $env{'user.name'}.':'.
10584: $env{'user.domain'},
10585: created => $now,
10586: context => $context,
1.918 raeburn 10587: },
10588: };
1.921 raeburn 10589: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10590: # set toplevel url
1.271 www 10591: my $topurl=$url;
10592: unless ($nonstandard) {
10593: # ------------------------------------------ For standard courses, make top url
10594: my $mapurl=&clutter($url);
1.278 www 10595: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10596: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10597: <map>
10598: <resource id="1" type="start"></resource>
10599: <resource id="2" src="$mapurl"></resource>
10600: <resource id="3" type="finish"></resource>
10601: <link index="1" from="1" to="2"></link>
10602: <link index="2" from="2" to="3"></link>
10603: </map>
10604: ENDINITMAP
10605: $topurl=&declutter(
1.638 albertel 10606: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10607: );
10608: }
10609: # ----------------------------------------------------------- Write preferences
1.84 www 10610: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10611: ('description' => $description,
10612: 'url' => $topurl,
10613: 'internal.creator' => $env{'user.name'}.':'.
10614: $env{'user.domain'},
10615: 'internal.created' => $now,
10616: 'internal.creationcontext' => $context)
10617: );
1.84 www 10618: return '/'.$udom.'/'.$uname;
10619: }
10620:
1.1011 raeburn 10621: # ------------------------------------------------------------------- Create ID
10622: sub generate_coursenum {
1.1038 raeburn 10623: my ($udom,$crstype) = @_;
1.1011 raeburn 10624: my $domdesc = &domain($udom);
10625: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10626: my $first;
10627: if ($crstype eq 'Community') {
10628: $first = '0';
10629: } else {
10630: $first = int(1+rand(9));
10631: }
10632: my $uname=$first.
1.1011 raeburn 10633: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10634: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10635: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10636: # ----------------------------------------------- Make sure that does not exist
10637: my $uhome=&homeserver($uname,$udom,'true');
10638: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10639: if ($crstype eq 'Community') {
10640: $first = '0';
10641: } else {
10642: $first = int(1+rand(9));
10643: }
10644: $uname=$first.
1.1011 raeburn 10645: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10646: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10647: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10648: $uhome=&homeserver($uname,$udom,'true');
10649: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10650: return 'error: unable to generate unique course-ID';
10651: }
10652: }
10653: return $uname;
10654: }
10655:
1.813 albertel 10656: sub is_course {
1.1167 droeschl 10657: my ($cdom, $cnum) = scalar(@_) == 1 ?
10658: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10659: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10660: my $uhome=&homeserver($cnum,$cdom);
10661: my $iscourse;
10662: if (grep { $_ eq $uhome } current_machine_ids()) {
10663: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10664: } else {
10665: my $hashid = $cdom.':'.$cnum;
10666: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10667: unless (defined($cached)) {
10668: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10669: $cnum,undef,undef,'.');
10670: $iscourse = 0;
10671: if (exists($courses{$cdom.'_'.$cnum})) {
10672: $iscourse = 1;
10673: }
10674: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10675: }
10676: }
10677: return unless($iscourse);
1.1167 droeschl 10678: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10679: }
10680:
1.1015 raeburn 10681: sub store_userdata {
10682: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10683: my $result;
1.1016 raeburn 10684: if ($datakey ne '') {
1.1013 raeburn 10685: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10686: if ($udom eq '' || $uname eq '') {
10687: $udom = $env{'user.domain'};
10688: $uname = $env{'user.name'};
10689: }
10690: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10691: if (($uhome eq '') || ($uhome eq 'no_host')) {
10692: $result = 'error: no_host';
10693: } else {
1.1172.2.138 raeburn 10694: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10695: $storehash->{'host'} = $perlvar{'lonHostID'};
10696:
10697: my $namevalue='';
10698: foreach my $key (keys(%{$storehash})) {
10699: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10700: }
10701: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10702: unless ($namespace eq 'courserequests') {
10703: $datakey = &escape($datakey);
10704: }
1.1105 raeburn 10705: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10706: $namevalue,$uhome);
1.1013 raeburn 10707: }
10708: } else {
10709: $result = 'error: data to store was not a hash reference';
10710: }
10711: } else {
10712: $result= 'error: invalid requestkey';
10713: }
10714: return $result;
10715: }
10716:
1.21 www 10717: # ---------------------------------------------------------- Assign Custom Role
10718:
10719: sub assigncustomrole {
1.957 raeburn 10720: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10721: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10722: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10723: }
10724:
10725: # ----------------------------------------------------------------- Revoke Role
10726:
10727: sub revokerole {
1.957 raeburn 10728: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10729: my $now=time;
1.965 raeburn 10730: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10731: }
10732:
10733: # ---------------------------------------------------------- Revoke Custom Role
10734:
10735: sub revokecustomrole {
1.957 raeburn 10736: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10737: my $now=time;
1.357 www 10738: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10739: $deleteflag,$selfenroll,$context);
1.17 www 10740: }
10741:
1.533 banghart 10742: # ------------------------------------------------------------ Disk usage
1.535 albertel 10743: sub diskusage {
1.955 raeburn 10744: my ($udom,$uname,$directorypath,$getpropath)=@_;
10745: $directorypath =~ s/\/$//;
10746: my $listing=&reply('du2:'.&escape($directorypath).':'
10747: .&escape($getpropath).':'.&escape($uname).':'
10748: .&escape($udom),homeserver($uname,$udom));
10749: if ($listing eq 'unknown_cmd') {
10750: if ($getpropath) {
10751: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10752: }
10753: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10754: }
1.514 albertel 10755: return $listing;
1.512 banghart 10756: }
10757:
1.566 banghart 10758: sub is_locked {
1.1096 raeburn 10759: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10760: my @check;
10761: my $is_locked;
1.1093 raeburn 10762: push (@check,$file_name);
1.613 albertel 10763: my %locked = &get('file_permissions',\@check,
1.620 albertel 10764: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10765: my ($tmp)=keys(%locked);
10766: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10767:
1.566 banghart 10768: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10769: $is_locked = 'false';
10770: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10771: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10772: $is_locked = 'true';
1.1096 raeburn 10773: if (ref($which) eq 'ARRAY') {
10774: push(@{$which},$entry);
10775: } else {
10776: last;
10777: }
1.745 raeburn 10778: }
10779: }
1.566 banghart 10780: } else {
10781: $is_locked = 'false';
10782: }
1.1093 raeburn 10783: return $is_locked;
1.566 banghart 10784: }
10785:
1.759 albertel 10786: sub declutter_portfile {
10787: my ($file) = @_;
1.833 albertel 10788: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10789: return $file;
10790: }
10791:
1.559 banghart 10792: # ------------------------------------------------------------- Mark as Read Only
10793:
10794: sub mark_as_readonly {
10795: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10796: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10797: my ($tmp)=keys(%current_permissions);
10798: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10799: foreach my $file (@{$files}) {
1.759 albertel 10800: $file = &declutter_portfile($file);
1.561 banghart 10801: push(@{$current_permissions{$file}},$what);
1.559 banghart 10802: }
1.613 albertel 10803: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10804: return;
10805: }
10806:
1.572 banghart 10807: # ------------------------------------------------------------Save Selected Files
10808:
10809: sub save_selected_files {
10810: my ($user, $path, @files) = @_;
10811: my $filename = $user."savedfiles";
1.573 banghart 10812: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10813: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10814: foreach my $file (@files) {
1.620 albertel 10815: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10816: }
10817: foreach my $file (@other_files) {
1.574 banghart 10818: print (OUT $file."\n");
1.572 banghart 10819: }
1.574 banghart 10820: close (OUT);
1.572 banghart 10821: return 'ok';
10822: }
10823:
1.574 banghart 10824: sub clear_selected_files {
10825: my ($user) = @_;
10826: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10827: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10828: print (OUT undef);
10829: close (OUT);
10830: return ("ok");
10831: }
10832:
1.572 banghart 10833: sub files_in_path {
10834: my ($user, $path) = @_;
10835: my $filename = $user."savedfiles";
10836: my %return_files;
1.1172.2.96 raeburn 10837: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10838: while (my $line_in = <IN>) {
1.574 banghart 10839: chomp ($line_in);
10840: my @paths_and_file = split (m!/!, $line_in);
10841: my $file_part = pop (@paths_and_file);
10842: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10843: $path_part.='/';
10844: my $path_and_file = $path_part.$file_part;
10845: if ($path_part eq $path) {
10846: $return_files{$file_part}= 'selected';
10847: }
10848: }
1.574 banghart 10849: close (IN);
10850: return (\%return_files);
1.572 banghart 10851: }
10852:
10853: # called in portfolio select mode, to show files selected NOT in current directory
10854: sub files_not_in_path {
10855: my ($user, $path) = @_;
10856: my $filename = $user."savedfiles";
10857: my @return_files;
10858: my $path_part;
1.1172.2.96 raeburn 10859: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10860: while (my $line = <IN>) {
1.572 banghart 10861: #ok, I know it's clunky, but I want it to work
1.800 albertel 10862: my @paths_and_file = split(m|/|, $line);
10863: my $file_part = pop(@paths_and_file);
10864: chomp($file_part);
10865: my $path_part = join('/', @paths_and_file);
1.572 banghart 10866: $path_part .= '/';
10867: my $path_and_file = $path_part.$file_part;
10868: if ($path_part ne $path) {
1.800 albertel 10869: push(@return_files, ($path_and_file));
1.572 banghart 10870: }
10871: }
1.800 albertel 10872: close(OUT);
1.574 banghart 10873: return (@return_files);
1.572 banghart 10874: }
10875:
1.745 raeburn 10876: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10877:
1.745 raeburn 10878: sub get_portfile_permissions {
10879: my ($domain,$user) = @_;
1.613 albertel 10880: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10881: my ($tmp)=keys(%current_permissions);
10882: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10883: return \%current_permissions;
10884: }
10885:
10886: #---------------------------------------------Get portfolio file access controls
10887:
1.749 raeburn 10888: sub get_access_controls {
1.745 raeburn 10889: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10890: my %access;
10891: my $real_file = $file;
10892: $file =~ s/\.meta$//;
1.745 raeburn 10893: if (defined($file)) {
1.749 raeburn 10894: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10895: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10896: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10897: }
10898: }
1.745 raeburn 10899: } else {
1.749 raeburn 10900: foreach my $key (keys(%{$current_permissions})) {
10901: if ($key =~ /\0accesscontrol$/) {
10902: if (defined($group)) {
10903: if ($key !~ m-^\Q$group\E/-) {
10904: next;
10905: }
10906: }
10907: my ($fullpath) = split(/\0/,$key);
10908: if (ref($$current_permissions{$key}) eq 'HASH') {
10909: foreach my $control (keys(%{$$current_permissions{$key}})) {
10910: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10911: }
10912: }
10913: }
10914: }
10915: }
10916: return %access;
10917: }
10918:
10919: sub modify_access_controls {
10920: my ($file_name,$changes,$domain,$user)=@_;
10921: my ($outcome,$deloutcome);
10922: my %store_permissions;
10923: my %new_values;
10924: my %new_control;
10925: my %translation;
10926: my @deletions = ();
10927: my $now = time;
10928: if (exists($$changes{'activate'})) {
10929: if (ref($$changes{'activate'}) eq 'HASH') {
10930: my @newitems = sort(keys(%{$$changes{'activate'}}));
10931: my $numnew = scalar(@newitems);
10932: for (my $i=0; $i<$numnew; $i++) {
10933: my $newkey = $newitems[$i];
10934: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10935: if ($newkey =~ /^\d+:/) {
10936: $newkey =~ s/^(\d+)/$newid/;
10937: $translation{$1} = $newid;
10938: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10939: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10940: $translation{$1} = $newid;
10941: }
1.749 raeburn 10942: $new_values{$file_name."\0".$newkey} =
10943: $$changes{'activate'}{$newitems[$i]};
10944: $new_control{$newkey} = $now;
10945: }
10946: }
10947: }
10948: my %todelete;
10949: my %changed_items;
10950: foreach my $action ('delete','update') {
10951: if (exists($$changes{$action})) {
10952: if (ref($$changes{$action}) eq 'HASH') {
10953: foreach my $key (keys(%{$$changes{$action}})) {
10954: my ($itemnum) = ($key =~ /^([^:]+):/);
10955: if ($action eq 'delete') {
10956: $todelete{$itemnum} = 1;
10957: } else {
10958: $changed_items{$itemnum} = $key;
10959: }
10960: }
1.745 raeburn 10961: }
10962: }
1.749 raeburn 10963: }
10964: # get lock on access controls for file.
10965: my $lockhash = {
10966: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10967: ':'.$env{'user.domain'},
10968: };
10969: my $tries = 0;
10970: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10971:
1.1172.2.79 raeburn 10972: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10973: $tries ++;
1.1172.2.79 raeburn 10974: sleep(0.1);
1.749 raeburn 10975: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10976: }
10977: if ($gotlock eq 'ok') {
10978: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10979: my ($tmp)=keys(%curr_permissions);
10980: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10981: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10982: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10983: if (ref($curr_controls) eq 'HASH') {
10984: foreach my $control_item (keys(%{$curr_controls})) {
10985: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10986: if (defined($todelete{$itemnum})) {
10987: push(@deletions,$file_name."\0".$control_item);
10988: } else {
10989: if (defined($changed_items{$itemnum})) {
10990: $new_control{$changed_items{$itemnum}} = $now;
10991: push(@deletions,$file_name."\0".$control_item);
10992: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10993: } else {
10994: $new_control{$control_item} = $$curr_controls{$control_item};
10995: }
10996: }
1.745 raeburn 10997: }
10998: }
10999: }
1.970 raeburn 11000: my ($group);
11001: if (&is_course($domain,$user)) {
11002: ($group,my $file) = split(/\//,$file_name,2);
11003: }
1.749 raeburn 11004: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11005: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11006: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11007: # remove lock
11008: my @del_lock = ($file_name."\0".'locked_access_records');
11009: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11010: my $sqlresult =
1.970 raeburn 11011: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11012: $group);
1.749 raeburn 11013: } else {
11014: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11015: }
1.749 raeburn 11016: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11017: }
11018:
1.827 raeburn 11019: sub make_public_indefinitely {
11020: my ($requrl) = @_;
11021: my $now = time;
11022: my $action = 'activate';
11023: my $aclnum = 0;
11024: if (&is_portfolio_url($requrl)) {
11025: my (undef,$udom,$unum,$file_name,$group) =
11026: &parse_portfolio_url($requrl);
11027: my $current_perms = &get_portfile_permissions($udom,$unum);
11028: my %access_controls = &get_access_controls($current_perms,
11029: $group,$file_name);
11030: foreach my $key (keys(%{$access_controls{$file_name}})) {
11031: my ($num,$scope,$end,$start) =
11032: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11033: if ($scope eq 'public') {
11034: if ($start <= $now && $end == 0) {
11035: $action = 'none';
11036: } else {
11037: $action = 'update';
11038: $aclnum = $num;
11039: }
11040: last;
11041: }
11042: }
11043: if ($action eq 'none') {
11044: return 'ok';
11045: } else {
11046: my %changes;
11047: my $newend = 0;
11048: my $newstart = $now;
11049: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11050: $changes{$action}{$newkey} = {
11051: type => 'public',
11052: time => {
11053: start => $newstart,
11054: end => $newend,
11055: },
11056: };
11057: my ($outcome,$deloutcome,$new_values,$translation) =
11058: &modify_access_controls($file_name,\%changes,$udom,$unum);
11059: return $outcome;
11060: }
11061: } else {
11062: return 'invalid';
11063: }
11064: }
11065:
1.745 raeburn 11066: #------------------------------------------------------Get Marked as Read Only
11067:
11068: sub get_marked_as_readonly {
11069: my ($domain,$user,$what,$group) = @_;
11070: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11071: my @readonly_files;
1.629 banghart 11072: my $cmp1=$what;
11073: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11074: while (my ($file_name,$value) = each(%{$current_permissions})) {
11075: if (defined($group)) {
11076: if ($file_name !~ m-^\Q$group\E/-) {
11077: next;
11078: }
11079: }
1.561 banghart 11080: if (ref($value) eq "ARRAY"){
11081: foreach my $stored_what (@{$value}) {
1.629 banghart 11082: my $cmp2=$stored_what;
1.759 albertel 11083: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11084: $cmp2=join('',@{$stored_what});
1.745 raeburn 11085: }
1.629 banghart 11086: if ($cmp1 eq $cmp2) {
1.561 banghart 11087: push(@readonly_files, $file_name);
1.745 raeburn 11088: last;
1.563 banghart 11089: } elsif (!defined($what)) {
11090: push(@readonly_files, $file_name);
1.745 raeburn 11091: last;
1.561 banghart 11092: }
11093: }
1.745 raeburn 11094: }
1.561 banghart 11095: }
11096: return @readonly_files;
11097: }
1.577 banghart 11098: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11099:
1.577 banghart 11100: sub get_marked_as_readonly_hash {
1.745 raeburn 11101: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11102: my %readonly_files;
1.745 raeburn 11103: while (my ($file_name,$value) = each(%{$current_permissions})) {
11104: if (defined($group)) {
11105: if ($file_name !~ m-^\Q$group\E/-) {
11106: next;
11107: }
11108: }
1.577 banghart 11109: if (ref($value) eq "ARRAY"){
11110: foreach my $stored_what (@{$value}) {
1.745 raeburn 11111: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11112: foreach my $lock_descriptor(@{$stored_what}) {
11113: if ($lock_descriptor eq 'graded') {
11114: $readonly_files{$file_name} = 'graded';
11115: } elsif ($lock_descriptor eq 'handback') {
11116: $readonly_files{$file_name} = 'handback';
11117: } else {
11118: if (!exists($readonly_files{$file_name})) {
11119: $readonly_files{$file_name} = 'locked';
11120: }
11121: }
1.745 raeburn 11122: }
1.750 banghart 11123: }
1.577 banghart 11124: }
11125: }
11126: }
11127: return %readonly_files;
11128: }
1.559 banghart 11129: # ------------------------------------------------------------ Unmark as Read Only
11130:
11131: sub unmark_as_readonly {
1.629 banghart 11132: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11133: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11134: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11135: $file_name = &declutter_portfile($file_name);
1.634 albertel 11136: my $symb_crs = $what;
11137: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11138: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11139: my ($tmp)=keys(%current_permissions);
11140: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11141: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11142: foreach my $file (@readonly_files) {
1.759 albertel 11143: my $clean_file = &declutter_portfile($file);
11144: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11145: my $current_locks = $current_permissions{$file};
1.563 banghart 11146: my @new_locks;
11147: my @del_keys;
11148: if (ref($current_locks) eq "ARRAY"){
11149: foreach my $locker (@{$current_locks}) {
1.632 albertel 11150: my $compare=$locker;
1.749 raeburn 11151: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11152: $compare=join('',@{$locker});
1.746 raeburn 11153: if ($compare ne $symb_crs) {
11154: push(@new_locks, $locker);
11155: }
1.563 banghart 11156: }
11157: }
1.650 albertel 11158: if (scalar(@new_locks) > 0) {
1.563 banghart 11159: $current_permissions{$file} = \@new_locks;
11160: } else {
11161: push(@del_keys, $file);
1.613 albertel 11162: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11163: delete($current_permissions{$file});
1.563 banghart 11164: }
11165: }
1.561 banghart 11166: }
1.613 albertel 11167: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11168: return;
11169: }
1.512 banghart 11170:
1.17 www 11171: # ------------------------------------------------------------ Directory lister
11172:
11173: sub dirlist {
1.955 raeburn 11174: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11175: $uri=~s/^\///;
11176: $uri=~s/\/$//;
1.253 stredwic 11177: my ($udom, $uname);
1.955 raeburn 11178: if ($getuserdir) {
1.253 stredwic 11179: $udom = $userdomain;
11180: $uname = $username;
1.955 raeburn 11181: } else {
11182: (undef,$udom,$uname)=split(/\//,$uri);
11183: if(defined($userdomain)) {
11184: $udom = $userdomain;
11185: }
11186: if(defined($username)) {
11187: $uname = $username;
11188: }
1.253 stredwic 11189: }
1.955 raeburn 11190: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11191:
1.955 raeburn 11192: $dirRoot = $perlvar{'lonDocRoot'};
11193: if (defined($getpropath)) {
11194: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11195: $dirRoot =~ s/\/$//;
1.955 raeburn 11196: } elsif (defined($getuserdir)) {
11197: my $subdir=$uname.'__';
11198: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11199: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11200: ."/$udom/$subdir/$uname";
11201: } elsif (defined($alternateRoot)) {
11202: $dirRoot = $alternateRoot;
1.751 banghart 11203: }
1.253 stredwic 11204:
11205: if($udom) {
11206: if($uname) {
1.1135 raeburn 11207: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11208: if ($uhome eq 'no_host') {
11209: return ([],'no_host');
11210: }
1.955 raeburn 11211: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11212: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11213: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11214: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11215: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11216: } else {
11217: @listing_results = map { &unescape($_); } split(/:/,$listing);
11218: }
1.605 matthew 11219: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11220: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11221: @listing_results = split(/:/,$listing);
11222: } else {
11223: @listing_results = map { &unescape($_); } split(/:/,$listing);
11224: }
1.1135 raeburn 11225: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11226: ($listing eq 'rejected') || ($listing eq 'refused') ||
11227: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11228: return ([],$listing);
11229: } else {
11230: return (\@listing_results);
1.1135 raeburn 11231: }
1.955 raeburn 11232: } elsif(!$alternateRoot) {
1.1136 raeburn 11233: my (%allusers,%listerror);
1.841 albertel 11234: my %servers = &get_servers($udom,'library');
1.955 raeburn 11235: foreach my $tryserver (keys(%servers)) {
11236: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11237: &escape($udom),$tryserver);
11238: if ($listing eq 'unknown_cmd') {
11239: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11240: $udom, $tryserver);
11241: } else {
11242: @listing_results = map { &unescape($_); } split(/:/,$listing);
11243: }
1.841 albertel 11244: if ($listing eq 'unknown_cmd') {
11245: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11246: $udom, $tryserver);
11247: @listing_results = split(/:/,$listing);
11248: } else {
11249: @listing_results =
11250: map { &unescape($_); } split(/:/,$listing);
11251: }
1.1136 raeburn 11252: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11253: ($listing eq 'rejected') || ($listing eq 'refused') ||
11254: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11255: $listerror{$tryserver} = $listing;
11256: } else {
1.841 albertel 11257: foreach my $line (@listing_results) {
11258: my ($entry) = split(/&/,$line,2);
11259: $allusers{$entry} = 1;
11260: }
11261: }
1.253 stredwic 11262: }
1.1136 raeburn 11263: my @alluserslist=();
1.800 albertel 11264: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11265: push(@alluserslist,$user.'&user');
1.253 stredwic 11266: }
1.1172.2.80 raeburn 11267: if (!%listerror) {
11268: # no errors
11269: return (\@alluserslist);
11270: } elsif (scalar(keys(%servers)) == 1) {
11271: # one library server, one error
11272: my ($key) = keys(%listerror);
11273: return (\@alluserslist, $listerror{$key});
11274: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11275: # con_lost indicates that we might miss data from at least one
11276: # library server
11277: return (\@alluserslist, 'con_lost');
11278: } else {
11279: # multiple library servers and no con_lost -> data should be
11280: # complete.
11281: return (\@alluserslist);
11282: }
11283:
1.253 stredwic 11284: } else {
1.1136 raeburn 11285: return ([],'missing username');
1.253 stredwic 11286: }
1.955 raeburn 11287: } elsif(!defined($getpropath)) {
1.1136 raeburn 11288: my $path = $perlvar{'lonDocRoot'}.'/res/';
11289: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11290: return (\@all_domains);
1.955 raeburn 11291: } else {
1.1136 raeburn 11292: return ([],'missing domain');
1.275 stredwic 11293: }
11294: }
11295:
11296: # --------------------------------------------- GetFileTimestamp
11297: # This function utilizes dirlist and returns the date stamp for
11298: # when it was last modified. It will also return an error of -1
11299: # if an error occurs
11300:
11301: sub GetFileTimestamp {
1.955 raeburn 11302: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11303: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11304: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11305: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11306: undef,$getuserdir);
11307: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11308: return -1;
11309: }
11310: if (ref($fileref) eq 'ARRAY') {
11311: my @stats = split('&',$fileref->[0]);
1.375 matthew 11312: # @stats contains first the filename, then the stat output
11313: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11314: } else {
11315: return -1;
1.253 stredwic 11316: }
1.26 www 11317: }
11318:
1.712 albertel 11319: sub stat_file {
11320: my ($uri) = @_;
1.787 albertel 11321: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11322:
1.955 raeburn 11323: my ($udom,$uname,$file);
1.712 albertel 11324: if ($uri =~ m-^/(uploaded|editupload)/-) {
11325: ($udom,$uname,$file) =
1.811 albertel 11326: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11327: $file = 'userfiles/'.$file;
11328: }
11329: if ($uri =~ m-^/res/-) {
11330: ($udom,$uname) =
1.807 albertel 11331: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11332: $file = $uri;
11333: }
11334:
11335: if (!$udom || !$uname || !$file) {
11336: # unable to handle the uri
11337: return ();
11338: }
1.956 raeburn 11339: my $getpropath;
11340: if ($file =~ /^userfiles\//) {
11341: $getpropath = 1;
11342: }
1.1136 raeburn 11343: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11344: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11345: return ();
11346: } else {
11347: if (ref($listref) eq 'ARRAY') {
11348: my @stats = split('&',$listref->[0]);
11349: shift(@stats); #filename is first
11350: return @stats;
11351: }
1.712 albertel 11352: }
11353: return ();
11354: }
11355:
1.26 www 11356: # -------------------------------------------------------- Value of a Condition
11357:
1.713 albertel 11358: # gets the value of a specific preevaluated condition
11359: # stored in the string $env{user.state.<cid>}
11360: # or looks up a condition reference in the bighash and if if hasn't
11361: # already been evaluated recurses into docondval to get the value of
11362: # the condition, then memoizing it to
11363: # $env{user.state.<cid>.<condition>}
1.40 www 11364: sub directcondval {
11365: my $number=shift;
1.620 albertel 11366: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11367: &Apache::lonuserstate::evalstate();
11368: }
1.713 albertel 11369: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11370: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11371: } elsif ($number =~ /^_/) {
11372: my $sub_condition;
11373: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11374: &GDBM_READER(),0640)) {
11375: $sub_condition=$bighash{'conditions'.$number};
11376: untie(%bighash);
11377: }
11378: my $value = &docondval($sub_condition);
1.949 raeburn 11379: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11380: return $value;
11381: }
1.620 albertel 11382: if ($env{'user.state.'.$env{'request.course.id'}}) {
11383: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11384: } else {
11385: return 2;
11386: }
11387: }
11388:
1.713 albertel 11389: # get the collection of conditions for this resource
1.26 www 11390: sub condval {
11391: my $condidx=shift;
1.54 www 11392: my $allpathcond='';
1.713 albertel 11393: foreach my $cond (split(/\|/,$condidx)) {
11394: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11395: $allpathcond.=
11396: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11397: }
1.191 harris41 11398: }
1.54 www 11399: $allpathcond=~s/\|$//;
1.713 albertel 11400: return &docondval($allpathcond);
11401: }
11402:
11403: #evaluates an expression of conditions
11404: sub docondval {
11405: my ($allpathcond) = @_;
11406: my $result=0;
11407: if ($env{'request.course.id'}
11408: && defined($allpathcond)) {
11409: my $operand='|';
11410: my @stack;
11411: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11412: if ($chunk eq '(') {
11413: push @stack,($operand,$result);
11414: } elsif ($chunk eq ')') {
11415: my $before=pop @stack;
11416: if (pop @stack eq '&') {
11417: $result=$result>$before?$before:$result;
11418: } else {
11419: $result=$result>$before?$result:$before;
11420: }
11421: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11422: $operand=$chunk;
11423: } else {
11424: my $new=directcondval($chunk);
11425: if ($operand eq '&') {
11426: $result=$result>$new?$new:$result;
11427: } else {
11428: $result=$result>$new?$result:$new;
11429: }
11430: }
11431: }
1.26 www 11432: }
11433: return $result;
1.421 albertel 11434: }
11435:
11436: # ---------------------------------------------------- Devalidate courseresdata
11437:
11438: sub devalidatecourseresdata {
11439: my ($coursenum,$coursedomain)=@_;
11440: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11441: &devalidate_cache_new('courseres',$hashid);
1.28 www 11442: }
11443:
1.763 www 11444:
1.200 www 11445: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11446: #
11447: # Parameters:
11448: # $coursenum - Number of the course.
11449: # $coursedomain - Domain at which the course was created.
11450: # Returns:
11451: # A hash of the course parameters along (I think) with timestamps
11452: # and version info.
1.877 foxr 11453:
1.624 albertel 11454: sub get_courseresdata {
11455: my ($coursenum,$coursedomain)=@_;
1.200 www 11456: my $coursehom=&homeserver($coursenum,$coursedomain);
11457: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11458: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11459: my %dumpreply;
1.417 albertel 11460: unless (defined($cached)) {
1.624 albertel 11461: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11462: $result=\%dumpreply;
1.251 albertel 11463: my ($tmp) = keys(%dumpreply);
11464: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11465: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11466: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11467: return $tmp;
1.416 albertel 11468: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11469: $result=undef;
1.599 albertel 11470: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11471: }
11472: }
1.624 albertel 11473: return $result;
11474: }
11475:
1.633 albertel 11476: sub devalidateuserresdata {
11477: my ($uname,$udom)=@_;
11478: my $hashid="$udom:$uname";
11479: &devalidate_cache_new('userres',$hashid);
11480: }
11481:
1.624 albertel 11482: sub get_userresdata {
11483: my ($uname,$udom)=@_;
11484: #most student don\'t have any data set, check if there is some data
11485: if (&EXT_cache_status($udom,$uname)) { return undef; }
11486:
11487: my $hashid="$udom:$uname";
11488: my ($result,$cached)=&is_cached_new('userres',$hashid);
11489: if (!defined($cached)) {
11490: my %resourcedata=&dump('resourcedata',$udom,$uname);
11491: $result=\%resourcedata;
11492: &do_cache_new('userres',$hashid,$result,600);
11493: }
11494: my ($tmp)=keys(%$result);
11495: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11496: return $result;
11497: }
11498: #error 2 occurs when the .db doesn't exist
11499: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11500: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11501: &logthis("<font color=\"blue\">WARNING:".
11502: " Trying to get resource data for ".
11503: $uname." at ".$udom.": ".
11504: $tmp."</font>");
11505: }
1.624 albertel 11506: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11507: #&EXT_cache_set($udom,$uname);
11508: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11509: undef($tmp); # not really an error so don't send it back
1.624 albertel 11510: }
11511: return $tmp;
11512: }
1.879 foxr 11513: #----------------------------------------------- resdata - return resource data
11514: # Purpose:
11515: # Return resource data for either users or for a course.
11516: # Parameters:
11517: # $name - Course/user name.
11518: # $domain - Name of the domain the user/course is registered on.
11519: # $type - Type of thing $name is (must be 'course' or 'user'
11520: # @which - Array of names of resources desired.
11521: # Returns:
11522: # The value of the first reasource in @which that is found in the
11523: # resource hash.
11524: # Exceptional Conditions:
11525: # If the $type passed in is not valid (not the string 'course' or
11526: # 'user', an undefined reference is returned.
11527: # If none of the resources are found, an undef is returned
1.624 albertel 11528: sub resdata {
11529: my ($name,$domain,$type,@which)=@_;
11530: my $result;
11531: if ($type eq 'course') {
11532: $result=&get_courseresdata($name,$domain);
11533: } elsif ($type eq 'user') {
11534: $result=&get_userresdata($name,$domain);
11535: }
11536: if (!ref($result)) { return $result; }
1.251 albertel 11537: foreach my $item (@which) {
1.927 albertel 11538: if (defined($result->{$item->[0]})) {
11539: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11540: }
1.250 albertel 11541: }
1.291 albertel 11542: return undef;
1.200 www 11543: }
11544:
1.1172.2.31 raeburn 11545: sub get_numsuppfiles {
11546: my ($cnum,$cdom,$ignorecache)=@_;
11547: my $hashid=$cnum.':'.$cdom;
11548: my ($suppcount,$cached);
11549: unless ($ignorecache) {
11550: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11551: }
11552: unless (defined($cached)) {
11553: my $chome=&homeserver($cnum,$cdom);
11554: unless ($chome eq 'no_host') {
11555: ($suppcount,my $errors) = (0,0);
11556: my $suppmap = 'supplemental.sequence';
11557: ($suppcount,$errors) =
11558: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11559: }
11560: &do_cache_new('suppcount',$hashid,$suppcount,600);
11561: }
11562: return $suppcount;
11563: }
11564:
1.379 matthew 11565: #
11566: # EXT resource caching routines
11567: #
11568:
11569: sub clear_EXT_cache_status {
1.383 albertel 11570: &delenv('cache.EXT.');
1.379 matthew 11571: }
11572:
11573: sub EXT_cache_status {
11574: my ($target_domain,$target_user) = @_;
1.383 albertel 11575: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11576: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11577: # We know already the user has no data
11578: return 1;
11579: } else {
11580: return 0;
11581: }
11582: }
11583:
11584: sub EXT_cache_set {
11585: my ($target_domain,$target_user) = @_;
1.383 albertel 11586: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11587: #&appenv({$cachename => time});
1.379 matthew 11588: }
11589:
1.28 www 11590: # --------------------------------------------------------- Value of a Variable
1.58 www 11591: sub EXT {
1.715 albertel 11592:
1.1172.2.28 raeburn 11593: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11594: unless ($varname) { return ''; }
1.218 albertel 11595: #get real user name/domain, courseid and symb
11596: my $courseid;
1.359 albertel 11597: my $publicuser;
1.427 www 11598: if ($symbparm) {
11599: $symbparm=&get_symb_from_alias($symbparm);
11600: }
1.218 albertel 11601: if (!($uname && $udom)) {
1.790 albertel 11602: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11603: if (!$symbparm) { $symbparm=$cursymb; }
11604: } else {
1.620 albertel 11605: $courseid=$env{'request.course.id'};
1.218 albertel 11606: }
1.48 www 11607: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11608: my $rest;
1.320 albertel 11609: if (defined($therest[0])) {
1.48 www 11610: $rest=join('.',@therest);
11611: } else {
11612: $rest='';
11613: }
1.320 albertel 11614:
1.57 www 11615: my $qualifierrest=$qualifier;
11616: if ($rest) { $qualifierrest.='.'.$rest; }
11617: my $spacequalifierrest=$space;
11618: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11619: if ($realm eq 'user') {
1.48 www 11620: # --------------------------------------------------------------- user.resource
11621: if ($space eq 'resource') {
1.651 albertel 11622: if ( (defined($Apache::lonhomework::parsing_a_problem)
11623: || defined($Apache::lonhomework::parsing_a_task))
11624: &&
1.1172.2.142 raeburn 11625: ($symbparm eq &symbread()) ) {
1.744 albertel 11626: # if we are in the middle of processing the resource the
11627: # get the value we are planning on committing
11628: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11629: return $Apache::lonhomework::results{$qualifierrest};
11630: } else {
11631: return $Apache::lonhomework::history{$qualifierrest};
11632: }
1.335 albertel 11633: } else {
1.359 albertel 11634: my %restored;
1.620 albertel 11635: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11636: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11637: } else {
11638: %restored=&restore($symbparm,$courseid,$udom,$uname);
11639: }
1.335 albertel 11640: return $restored{$qualifierrest};
11641: }
1.48 www 11642: # ----------------------------------------------------------------- user.access
11643: } elsif ($space eq 'access') {
1.218 albertel 11644: # FIXME - not supporting calls for a specific user
1.48 www 11645: return &allowed($qualifier,$rest);
11646: # ------------------------------------------ user.preferences, user.environment
11647: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11648: if (($uname eq $env{'user.name'}) &&
11649: ($udom eq $env{'user.domain'})) {
11650: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11651: } else {
1.359 albertel 11652: my %returnhash;
11653: if (!$publicuser) {
11654: %returnhash=&userenvironment($udom,$uname,
11655: $qualifierrest);
11656: }
1.218 albertel 11657: return $returnhash{$qualifierrest};
11658: }
1.48 www 11659: # ----------------------------------------------------------------- user.course
11660: } elsif ($space eq 'course') {
1.218 albertel 11661: # FIXME - not supporting calls for a specific user
1.620 albertel 11662: return $env{join('.',('request.course',$qualifier))};
1.48 www 11663: # ------------------------------------------------------------------- user.role
11664: } elsif ($space eq 'role') {
1.218 albertel 11665: # FIXME - not supporting calls for a specific user
1.620 albertel 11666: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11667: if ($qualifier eq 'value') {
11668: return $role;
11669: } elsif ($qualifier eq 'extent') {
11670: return $where;
11671: }
11672: # ----------------------------------------------------------------- user.domain
11673: } elsif ($space eq 'domain') {
1.218 albertel 11674: return $udom;
1.48 www 11675: # ------------------------------------------------------------------- user.name
11676: } elsif ($space eq 'name') {
1.218 albertel 11677: return $uname;
1.48 www 11678: # ---------------------------------------------------- Any other user namespace
1.29 www 11679: } else {
1.359 albertel 11680: my %reply;
11681: if (!$publicuser) {
11682: %reply=&get($space,[$qualifierrest],$udom,$uname);
11683: }
11684: return $reply{$qualifierrest};
1.48 www 11685: }
1.236 www 11686: } elsif ($realm eq 'query') {
11687: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11688: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11689: [$spacequalifierrest]);
1.620 albertel 11690: return $env{'form.'.$spacequalifierrest};
1.236 www 11691: } elsif ($realm eq 'request') {
1.48 www 11692: # ------------------------------------------------------------- request.browser
11693: if ($space eq 'browser') {
1.1145 bisitz 11694: return $env{'browser.'.$qualifier};
1.57 www 11695: # ------------------------------------------------------------ request.filename
11696: } else {
1.620 albertel 11697: return $env{'request.'.$spacequalifierrest};
1.29 www 11698: }
1.28 www 11699: } elsif ($realm eq 'course') {
1.48 www 11700: # ---------------------------------------------------------- course.description
1.620 albertel 11701: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11702: } elsif ($realm eq 'resource') {
1.165 www 11703:
1.620 albertel 11704: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11705: if (!$symbparm) { $symbparm=&symbread(); }
11706: }
1.693 albertel 11707:
1.1172.2.30 raeburn 11708: if ($qualifier eq '') {
11709: if ($space eq 'title') {
11710: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11711: return &gettitle($symbparm);
11712: }
1.693 albertel 11713:
1.1172.2.30 raeburn 11714: if ($space eq 'map') {
11715: my ($map) = &decode_symb($symbparm);
11716: return &symbread($map);
11717: }
11718: if ($space eq 'maptitle') {
11719: my ($map) = &decode_symb($symbparm);
11720: return &gettitle($map);
11721: }
11722: if ($space eq 'filename') {
11723: if ($symbparm) {
11724: return &clutter((&decode_symb($symbparm))[2]);
11725: }
11726: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11727: }
1.1172.2.30 raeburn 11728:
11729: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11730: if ($space eq 'visibleparts') {
11731: my $navmap = Apache::lonnavmaps::navmap->new();
11732: my $item;
11733: if (ref($navmap)) {
11734: my $res = $navmap->getBySymb($symbparm);
11735: my $parts = $res->parts();
11736: if (ref($parts) eq 'ARRAY') {
11737: $item = join(',',@{$parts});
11738: }
11739: undef($navmap);
11740: }
11741: return $item;
11742: }
11743: }
11744: }
1.693 albertel 11745:
11746: my ($section, $group, @groups);
1.593 albertel 11747: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11748: if (($courseid eq '') && ($cid)) {
11749: $courseid = $cid;
11750: }
11751: if (($symbparm && $courseid) &&
11752: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11753:
1.218 albertel 11754: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11755:
1.60 www 11756: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11757: my $symbp=$symbparm;
1.735 albertel 11758: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11759:
11760: my $symbparm=$symbp.'.'.$spacequalifierrest;
11761: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11762:
1.620 albertel 11763: if (($env{'user.name'} eq $uname) &&
11764: ($env{'user.domain'} eq $udom)) {
11765: $section=$env{'request.course.sec'};
1.733 raeburn 11766: @groups = split(/:/,$env{'request.course.groups'});
11767: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11768: } else {
1.539 albertel 11769: if (! defined($usection)) {
1.551 albertel 11770: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11771: } else {
11772: $section = $usection;
11773: }
1.733 raeburn 11774: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11775: }
11776:
11777: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11778: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11779: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11780:
1.593 albertel 11781: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11782: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11783: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11784:
1.60 www 11785: # ----------------------------------------------------------- first, check user
1.624 albertel 11786:
11787: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11788: ([$courselevelr,'resource'],
11789: [$courselevelm,'map' ],
11790: [$courselevel, 'course' ]));
1.931 albertel 11791: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11792:
1.594 albertel 11793: # ------------------------------------------------ second, check some of course
1.684 raeburn 11794: my $coursereply;
1.691 raeburn 11795: if (@groups > 0) {
11796: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11797: $mapparm,$spacequalifierrest);
1.927 albertel 11798: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11799: }
1.96 www 11800:
1.684 raeburn 11801: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11802: $env{'course.'.$courseid.'.domain'},
11803: 'course',
11804: ([$seclevelr, 'resource'],
11805: [$seclevelm, 'map' ],
11806: [$seclevel, 'course' ],
11807: [$courselevelr,'resource']));
11808: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11809:
1.60 www 11810: # ------------------------------------------------------ third, check map parms
1.218 albertel 11811: my %parmhash=();
11812: my $thisparm='';
11813: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11814: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11815: &GDBM_READER(),0640)) {
1.218 albertel 11816: $thisparm=$parmhash{$symbparm};
11817: untie(%parmhash);
11818: }
1.927 albertel 11819: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11820: }
1.594 albertel 11821: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11822:
1.218 albertel 11823: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11824: my $filename;
11825: if (!$symbparm) { $symbparm=&symbread(); }
11826: if ($symbparm) {
1.409 www 11827: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11828: } else {
1.620 albertel 11829: $filename=$env{'request.filename'};
1.282 albertel 11830: }
11831: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11832: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11833: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11834: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11835:
1.927 albertel 11836: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11837: if ($symbparm && defined($courseid) &&
1.620 albertel 11838: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11839: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11840: $env{'course.'.$courseid.'.domain'},
11841: 'course',
1.927 albertel 11842: ([$courselevelm,'map' ],
11843: [$courselevel, 'course']));
11844: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11845: }
1.145 www 11846: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11847: unless ($space eq '0') {
1.336 albertel 11848: my @parts=split(/_/,$space);
11849: my $id=pop(@parts);
11850: my $part=join('_',@parts);
11851: if ($part eq '') { $part='0'; }
1.927 albertel 11852: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11853: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11854: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11855: }
1.395 albertel 11856: if ($recurse) { return undef; }
11857: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11858: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11859: # ---------------------------------------------------- Any other user namespace
11860: } elsif ($realm eq 'environment') {
11861: # ----------------------------------------------------------------- environment
1.620 albertel 11862: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11863: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11864: } else {
1.770 albertel 11865: if ($uname eq 'anonymous' && $udom eq '') {
11866: return '';
11867: }
1.219 albertel 11868: my %returnhash=&userenvironment($udom,$uname,
11869: $spacequalifierrest);
11870: return $returnhash{$spacequalifierrest};
11871: }
1.28 www 11872: } elsif ($realm eq 'system') {
1.48 www 11873: # ----------------------------------------------------------------- system.time
11874: if ($space eq 'time') {
11875: return time;
11876: }
1.696 albertel 11877: } elsif ($realm eq 'server') {
11878: # ----------------------------------------------------------------- system.time
11879: if ($space eq 'name') {
11880: return $ENV{'SERVER_NAME'};
11881: }
1.28 www 11882: }
1.48 www 11883: return '';
1.61 www 11884: }
11885:
1.927 albertel 11886: sub get_reply {
11887: my ($reply_value) = @_;
1.940 raeburn 11888: if (ref($reply_value) eq 'ARRAY') {
11889: if (wantarray) {
11890: return @$reply_value;
11891: }
11892: return $reply_value->[0];
11893: } else {
11894: return $reply_value;
1.927 albertel 11895: }
11896: }
11897:
1.691 raeburn 11898: sub check_group_parms {
11899: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11900: my @groupitems = ();
11901: my $resultitem;
1.927 albertel 11902: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11903: foreach my $group (@{$groups}) {
11904: foreach my $level (@levels) {
1.927 albertel 11905: my $item = $courseid.'.['.$group.'].'.$level->[0];
11906: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11907: }
11908: }
11909: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11910: $env{'course.'.$courseid.'.domain'},
11911: 'course',@groupitems);
11912: return $coursereply;
11913: }
11914:
11915: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11916: my ($courseid,@groups) = @_;
11917: @groups = sort(@groups);
1.691 raeburn 11918: return @groups;
11919: }
11920:
1.395 albertel 11921: sub packages_tab_default {
11922: my ($uri,$varname)=@_;
11923: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11924:
11925: my (@extension,@specifics,$do_default);
11926: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11927: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11928: if ($pack_type eq 'default') {
11929: $do_default=1;
11930: } elsif ($pack_type eq 'extension') {
11931: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11932: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11933: # only look at packages defaults for packages that this id is
1.738 albertel 11934: push(@specifics,[$package,$pack_type,$pack_part]);
11935: }
11936: }
11937: # first look for a package that matches the requested part id
11938: foreach my $package (@specifics) {
11939: my (undef,$pack_type,$pack_part)=@{$package};
11940: next if ($pack_part ne $part);
11941: if (defined($packagetab{"$pack_type&$name&default"})) {
11942: return $packagetab{"$pack_type&$name&default"};
11943: }
11944: }
11945: # look for any possible matching non extension_ package
11946: foreach my $package (@specifics) {
11947: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11948: if (defined($packagetab{"$pack_type&$name&default"})) {
11949: return $packagetab{"$pack_type&$name&default"};
11950: }
1.585 albertel 11951: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11952: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11953: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11954: }
11955: }
1.738 albertel 11956: # look for any posible extension_ match
11957: foreach my $package (@extension) {
11958: my ($package,$pack_type)=@{$package};
11959: if (defined($packagetab{"$pack_type&$name&default"})) {
11960: return $packagetab{"$pack_type&$name&default"};
11961: }
11962: if (defined($packagetab{$package."&$name&default"})) {
11963: return $packagetab{$package."&$name&default"};
11964: }
11965: }
11966: # look for a global default setting
11967: if ($do_default && defined($packagetab{"default&$name&default"})) {
11968: return $packagetab{"default&$name&default"};
11969: }
1.395 albertel 11970: return undef;
11971: }
11972:
1.334 albertel 11973: sub add_prefix_and_part {
11974: my ($prefix,$part)=@_;
11975: my $keyroot;
11976: if (defined($prefix) && $prefix !~ /^__/) {
11977: # prefix that has a part already
11978: $keyroot=$prefix;
11979: } elsif (defined($prefix)) {
11980: # prefix that is missing a part
11981: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11982: } else {
11983: # no prefix at all
11984: if (defined($part)) { $keyroot='_'.$part; }
11985: }
11986: return $keyroot;
11987: }
11988:
1.71 www 11989: # ---------------------------------------------------------------- Get metadata
11990:
1.599 albertel 11991: my %metaentry;
1.1070 www 11992: my %importedpartids;
1.1172.2.99 raeburn 11993: my %importedrespids;
1.71 www 11994: sub metadata {
1.176 www 11995: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11996: $uri=&declutter($uri);
1.288 albertel 11997: # if it is a non metadata possible uri return quickly
1.529 albertel 11998: if (($uri eq '') ||
11999: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 12000: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 12001: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12002: return undef;
12003: }
1.1172.2.49 raeburn 12004: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12005: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12006: return undef;
1.288 albertel 12007: }
1.73 www 12008: my $filename=$uri;
12009: $uri=~s/\.meta$//;
1.172 www 12010: #
12011: # Is the metadata already cached?
1.177 www 12012: # Look at timestamp of caching
1.172 www 12013: # Everything is cached by the main uri, libraries are never directly cached
12014: #
1.428 albertel 12015: if (!defined($liburi)) {
1.599 albertel 12016: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12017: if (defined($cached)) { return $result->{':'.$what}; }
12018: }
12019: {
1.1069 www 12020: # Imported parts would go here
1.1172.2.99 raeburn 12021: my @origfiletagids=();
1.1069 www 12022: my $importedparts=0;
1.1172.2.99 raeburn 12023:
12024: # Imported responseids would go here
12025: my $importedresponses=0;
1.172 www 12026: #
12027: # Is this a recursive call for a library?
12028: #
1.599 albertel 12029: # if (! exists($metacache{$uri})) {
12030: # $metacache{$uri}={};
12031: # }
1.924 albertel 12032: my $cachetime = 60*60;
1.171 www 12033: if ($liburi) {
12034: $liburi=&declutter($liburi);
12035: $filename=$liburi;
1.401 bowersj2 12036: } else {
1.599 albertel 12037: &devalidate_cache_new('meta',$uri);
12038: undef(%metaentry);
1.401 bowersj2 12039: }
1.140 www 12040: my %metathesekeys=();
1.73 www 12041: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12042: my $metastring;
1.1140 www 12043: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12044: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12045: $metastring =
1.929 albertel 12046: &Apache::lonnet::ssi_body($which,
1.924 albertel 12047: ('grade_target' => 'meta'));
12048: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12049: } elsif (($uri !~ m -^(editupload)/-) &&
12050: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12051: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12052: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12053: $metastring=&getfile($file);
1.489 albertel 12054: }
1.208 albertel 12055: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12056: my $token;
1.140 www 12057: undef %metathesekeys;
1.71 www 12058: while ($token=$parser->get_token) {
1.339 albertel 12059: if ($token->[0] eq 'S') {
12060: if (defined($token->[2]->{'package'})) {
1.172 www 12061: #
12062: # This is a package - get package info
12063: #
1.339 albertel 12064: my $package=$token->[2]->{'package'};
12065: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12066: if (defined($token->[2]->{'id'})) {
12067: $keyroot.='_'.$token->[2]->{'id'};
12068: }
1.599 albertel 12069: if ($metaentry{':packages'}) {
12070: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12071: } else {
1.599 albertel 12072: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12073: }
1.736 albertel 12074: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12075: my $part=$keyroot;
12076: $part=~s/^\_//;
1.736 albertel 12077: if ($pack_entry=~/^\Q$package\E\&/ ||
12078: $pack_entry=~/^\Q$package\E_0\&/) {
12079: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12080: # ignore package.tab specified default values
12081: # here &package_tab_default() will fetch those
12082: if ($subp eq 'default') { next; }
1.736 albertel 12083: my $value=$packagetab{$pack_entry};
1.432 albertel 12084: my $unikey;
12085: if ($pack =~ /_0$/) {
12086: $unikey='parameter_0_'.$name;
12087: $part=0;
12088: } else {
12089: $unikey='parameter'.$keyroot.'_'.$name;
12090: }
1.339 albertel 12091: if ($subp eq 'display') {
12092: $value.=' [Part: '.$part.']';
12093: }
1.599 albertel 12094: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12095: $metathesekeys{$unikey}=1;
1.599 albertel 12096: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12097: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12098: }
1.599 albertel 12099: if (defined($metaentry{':'.$unikey.'.default'})) {
12100: $metaentry{':'.$unikey}=
12101: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12102: }
1.339 albertel 12103: }
12104: }
12105: } else {
1.172 www 12106: #
12107: # This is not a package - some other kind of start tag
1.339 albertel 12108: #
12109: my $entry=$token->[1];
1.1068 www 12110: my $unikey='';
1.175 www 12111:
1.339 albertel 12112: if ($entry eq 'import') {
1.175 www 12113: #
12114: # Importing a library here
1.339 albertel 12115: #
1.1067 www 12116: my $location=$parser->get_text('/import');
12117: my $dir=$filename;
12118: $dir=~s|[^/]*$||;
12119: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12120:
12121: my $importid=$token->[2]->{'id'};
1.1068 www 12122: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12123: #
12124: # Check metadata for imported file to
12125: # see if it contained response items
12126: #
12127: my %currmetaentry = %metaentry;
12128: my $libresponseorder = &metadata($location,'responseorder');
12129: my $origfile;
12130: if ($libresponseorder ne '') {
12131: if ($#origfiletagids<0) {
12132: undef(%importedrespids);
12133: undef(%importedpartids);
12134: }
12135: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12136: if (@{$importedrespids{$importid}} > 0) {
12137: $importedresponses = 1;
12138: # We need to get the original file and the imported file to get the response order correct
12139: # Load and inspect original file
12140: if ($#origfiletagids<0) {
12141: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12142: $origfile=&getfile($origfilelocation);
12143: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12144: }
12145: }
12146: }
12147: # Do not overwrite contents of %metaentry hash for resource itself with
12148: # hash populated for imported library file
12149: %metaentry = %currmetaentry;
12150: undef(%currmetaentry);
1.1068 www 12151: if ($importmode eq 'problem') {
1.1069 www 12152: # Import as problem/response
1.1068 www 12153: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12154: } elsif ($importmode eq 'part') {
12155: # Import as part(s)
1.1069 www 12156: $importedparts=1;
12157: # We need to get the original file and the imported file to get the part order correct
12158: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12159: # Load and inspect original file if we didn't do that already
12160: if ($#origfiletagids<0) {
12161: undef(%importedrespids);
12162: undef(%importedpartids);
12163: if ($origfile eq '') {
12164: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12165: $origfile=&getfile($origfilelocation);
12166: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12167: }
1.1070 www 12168: }
12169:
1.1069 www 12170: # Load and inspect imported file
12171: my $impfile=&getfile($location);
12172: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12173: if ($#impfilepartids>=0) {
12174: # This problem had parts
1.1070 www 12175: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12176: } else {
12177: # Importing by turning a single problem into a problem part
12178: # It gets the import-tags ID as part-ID
12179: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12180: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12181: }
1.1068 www 12182: } else {
12183: # Normal import
12184: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12185: if (defined($token->[2]->{'id'})) {
12186: $unikey.='_'.$token->[2]->{'id'};
12187: }
1.1067 www 12188: }
12189:
1.339 albertel 12190: if ($depthcount<20) {
1.736 albertel 12191: my $metadata =
12192: &metadata($uri,'keys', $location,$unikey,
12193: $depthcount+1);
12194: foreach my $meta (split(',',$metadata)) {
12195: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12196: $metathesekeys{$meta}=1;
1.339 albertel 12197: }
1.1068 www 12198:
12199: }
1.1067 www 12200: } else {
12201: #
12202: # Not importing, some other kind of non-package, non-library start tag
12203: #
12204: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12205: if (defined($token->[2]->{'id'})) {
12206: $unikey.='_'.$token->[2]->{'id'};
12207: }
1.339 albertel 12208: if (defined($token->[2]->{'name'})) {
12209: $unikey.='_'.$token->[2]->{'name'};
12210: }
12211: $metathesekeys{$unikey}=1;
1.736 albertel 12212: foreach my $param (@{$token->[3]}) {
12213: $metaentry{':'.$unikey.'.'.$param} =
12214: $token->[2]->{$param};
1.339 albertel 12215: }
12216: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12217: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12218: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12219: # only ws inside the tag, and not in default, so use default
12220: # as value
1.599 albertel 12221: $metaentry{':'.$unikey}=$default;
1.908 albertel 12222: } elsif ( $internaltext =~ /\S/ ) {
12223: # something interesting inside the tag
12224: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12225: } else {
1.908 albertel 12226: # no interesting values, don't set a default
1.339 albertel 12227: }
1.172 www 12228: # end of not-a-package not-a-library import
1.339 albertel 12229: }
1.172 www 12230: # end of not-a-package start tag
1.339 albertel 12231: }
1.172 www 12232: # the next is the end of "start tag"
1.339 albertel 12233: }
12234: }
1.483 albertel 12235: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12236: $extension = lc($extension);
12237: if ($extension eq 'htm') { $extension='html'; }
12238:
1.737 albertel 12239: foreach my $key (keys(%packagetab)) {
1.483 albertel 12240: #no specific packages #how's our extension
12241: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12242: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12243: \%metathesekeys);
12244: }
1.883 albertel 12245:
12246: if (!exists($metaentry{':packages'})
12247: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12248: foreach my $key (keys(%packagetab)) {
1.483 albertel 12249: #no specific packages well let's get default then
12250: if ($key!~/^default&/) { next; }
1.488 albertel 12251: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12252: \%metathesekeys);
12253: }
12254: }
1.338 www 12255: # are there custom rights to evaluate
1.599 albertel 12256: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12257:
1.338 www 12258: #
12259: # Importing a rights file here
1.339 albertel 12260: #
12261: unless ($depthcount) {
1.599 albertel 12262: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12263: my $dir=$filename;
12264: $dir=~s|[^/]*$||;
12265: $location=&filelocation($dir,$location);
1.736 albertel 12266: my $rights_metadata =
12267: &metadata($uri,'keys',$location,'_rights',
12268: $depthcount+1);
12269: foreach my $rights (split(',',$rights_metadata)) {
12270: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12271: $metathesekeys{$rights}=1;
1.339 albertel 12272: }
12273: }
12274: }
1.737 albertel 12275: # uniqifiy package listing
12276: my %seen;
12277: my @uniq_packages =
12278: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12279: $metaentry{':packages'} = join(',',@uniq_packages);
12280:
1.1172.2.99 raeburn 12281: if (($importedresponses) || ($importedparts)) {
12282: if ($importedparts) {
1.1070 www 12283: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12284: $metaentry{':partorder'}='';
12285: $metathesekeys{'partorder'}=1;
12286: }
12287: if ($importedresponses) {
12288: # We had imported responses and need to rebuild responseorder
12289: $metaentry{':responseorder'}='';
12290: $metathesekeys{'responseorder'}=1;
12291: }
12292: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12293: my $origid = $origfiletagids[$index+1];
12294: if ($origfiletagids[$index] eq 'part') {
12295: # Original part, part of the problem
12296: if ($importedparts) {
12297: $metaentry{':partorder'}.=','.$origid;
12298: }
12299: } elsif ($origfiletagids[$index] eq 'import') {
12300: if ($importedparts) {
12301: # We have imported parts at this position
12302: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12303: }
12304: if ($importedresponses) {
12305: # We have imported responses at this position
12306: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12307: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12308: }
12309: }
12310: } else {
12311: # Original response item, part of the problem
12312: if ($importedresponses) {
12313: $metaentry{':responseorder'}.=','.$origid;
12314: }
12315: }
12316: }
12317: if ($importedparts) {
12318: $metaentry{':partorder'}=~s/^\,//;
12319: }
12320: if ($importedresponses) {
12321: $metaentry{':responseorder'}=~s/^\,//;
12322: }
1.1070 www 12323: }
12324:
1.737 albertel 12325: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12326: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12327: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12328: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12329: # this is the end of "was not already recently cached
1.71 www 12330: }
1.599 albertel 12331: return $metaentry{':'.$what};
1.261 albertel 12332: }
12333:
1.488 albertel 12334: sub metadata_create_package_def {
1.483 albertel 12335: my ($uri,$key,$package,$metathesekeys)=@_;
12336: my ($pack,$name,$subp)=split(/\&/,$key);
12337: if ($subp eq 'default') { next; }
12338:
1.599 albertel 12339: if (defined($metaentry{':packages'})) {
12340: $metaentry{':packages'}.=','.$package;
1.483 albertel 12341: } else {
1.599 albertel 12342: $metaentry{':packages'}=$package;
1.483 albertel 12343: }
12344: my $value=$packagetab{$key};
12345: my $unikey;
12346: $unikey='parameter_0_'.$name;
1.599 albertel 12347: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12348: $$metathesekeys{$unikey}=1;
1.599 albertel 12349: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12350: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12351: }
1.599 albertel 12352: if (defined($metaentry{':'.$unikey.'.default'})) {
12353: $metaentry{':'.$unikey}=
12354: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12355: }
12356: }
12357:
1.261 albertel 12358: sub metadata_generate_part0 {
12359: my ($metadata,$metacache,$uri) = @_;
12360: my %allnames;
1.737 albertel 12361: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12362: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12363: my $part=$$metacache{':'.$metakey.'.part'};
12364: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12365: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12366: $allnames{$name}=$part;
12367: }
12368: }
12369: }
12370: foreach my $name (keys(%allnames)) {
12371: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12372: my $key=":parameter_0_$name";
1.261 albertel 12373: $$metacache{"$key.part"}='0';
12374: $$metacache{"$key.name"}=$name;
1.428 albertel 12375: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12376: $allnames{$name}.'_'.$name.
12377: '.type'};
1.428 albertel 12378: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12379: '.display'};
1.644 www 12380: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12381: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12382: $$metacache{"$key.display"}=$olddis;
12383: }
1.71 www 12384: }
12385:
1.764 albertel 12386: # ------------------------------------------------------ Devalidate title cache
12387:
12388: sub devalidate_title_cache {
12389: my ($url)=@_;
12390: if (!$env{'request.course.id'}) { return; }
12391: my $symb=&symbread($url);
12392: if (!$symb) { return; }
12393: my $key=$env{'request.course.id'}."\0".$symb;
12394: &devalidate_cache_new('title',$key);
12395: }
12396:
1.1014 droeschl 12397: # ------------------------------------------------- Get the title of a course
12398:
12399: sub current_course_title {
12400: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12401: }
1.301 www 12402: # ------------------------------------------------- Get the title of a resource
12403:
12404: sub gettitle {
12405: my $urlsymb=shift;
12406: my $symb=&symbread($urlsymb);
1.534 albertel 12407: if ($symb) {
1.620 albertel 12408: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12409: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12410: if (defined($cached)) {
12411: return $result;
12412: }
1.534 albertel 12413: my ($map,$resid,$url)=&decode_symb($symb);
12414: my $title='';
1.907 albertel 12415: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12416: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12417: } else {
12418: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12419: &GDBM_READER(),0640)) {
12420: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12421: $title=$bighash{'title_'.$mapid.'.'.$resid};
12422: untie(%bighash);
12423: }
1.534 albertel 12424: }
12425: $title=~s/\&colon\;/\:/gs;
12426: if ($title) {
1.1159 www 12427: # Remember both $symb and $title for dynamic metadata
12428: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12429: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12430: # Cache this title and then return it
1.599 albertel 12431: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12432: }
12433: $urlsymb=$url;
12434: }
12435: my $title=&metadata($urlsymb,'title');
12436: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12437: return $title;
1.301 www 12438: }
1.613 albertel 12439:
1.614 albertel 12440: sub get_slot {
12441: my ($which,$cnum,$cdom)=@_;
12442: if (!$cnum || !$cdom) {
1.790 albertel 12443: (undef,my $courseid)=&whichuser();
1.620 albertel 12444: $cdom=$env{'course.'.$courseid.'.domain'};
12445: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12446: }
1.703 albertel 12447: my $key=join("\0",'slots',$cdom,$cnum,$which);
12448: my %slotinfo;
12449: if (exists($remembered{$key})) {
12450: $slotinfo{$which} = $remembered{$key};
12451: } else {
12452: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12453: &Apache::lonhomework::showhash(%slotinfo);
12454: my ($tmp)=keys(%slotinfo);
12455: if ($tmp=~/^error:/) { return (); }
12456: $remembered{$key} = $slotinfo{$which};
12457: }
1.616 albertel 12458: if (ref($slotinfo{$which}) eq 'HASH') {
12459: return %{$slotinfo{$which}};
12460: }
12461: return $slotinfo{$which};
1.614 albertel 12462: }
1.1150 raeburn 12463:
12464: sub get_reservable_slots {
12465: my ($cnum,$cdom,$uname,$udom) = @_;
12466: my $now = time;
12467: my $reservable_info;
12468: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12469: if (exists($remembered{$key})) {
12470: $reservable_info = $remembered{$key};
12471: } else {
12472: my %resv;
12473: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12474: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12475: $reservable_info = \%resv;
12476: $remembered{$key} = $reservable_info;
12477: }
12478: return $reservable_info;
12479: }
12480:
12481: sub get_course_slots {
12482: my ($cnum,$cdom) = @_;
12483: my $hashid=$cnum.':'.$cdom;
12484: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12485: if (defined($cached)) {
12486: if (ref($result) eq 'HASH') {
12487: return %{$result};
12488: }
12489: } else {
12490: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12491: my ($tmp) = keys(%slots);
12492: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12493: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12494: return %slots;
12495: }
12496: }
12497: return;
12498: }
12499:
12500: sub devalidate_slots_cache {
12501: my ($cnum,$cdom)=@_;
12502: my $hashid=$cnum.':'.$cdom;
12503: &devalidate_cache_new('allslots',$hashid);
12504: }
12505:
1.1172.2.8 raeburn 12506: sub get_coursechange {
12507: my ($cdom,$cnum) = @_;
12508: if ($cdom eq '' || $cnum eq '') {
12509: return unless ($env{'request.course.id'});
12510: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12511: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12512: }
12513: my $hashid=$cdom.'_'.$cnum;
12514: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12515: if ((defined($cached)) && ($change ne '')) {
12516: return $change;
12517: } else {
12518: my %crshash;
12519: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12520: if ($crshash{'internal.contentchange'} eq '') {
12521: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12522: if ($change eq '') {
12523: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12524: $change = $crshash{'internal.created'};
12525: }
12526: } else {
12527: $change = $crshash{'internal.contentchange'};
12528: }
12529: my $cachetime = 600;
12530: &do_cache_new('crschange',$hashid,$change,$cachetime);
12531: }
12532: return $change;
12533: }
12534:
12535: sub devalidate_coursechange_cache {
12536: my ($cnum,$cdom)=@_;
12537: my $hashid=$cnum.':'.$cdom;
12538: &devalidate_cache_new('crschange',$hashid);
12539: }
12540:
1.31 www 12541: # ------------------------------------------------- Update symbolic store links
12542:
12543: sub symblist {
12544: my ($mapname,%newhash)=@_;
1.438 www 12545: $mapname=&deversion(&declutter($mapname));
1.31 www 12546: my %hash;
1.620 albertel 12547: if (($env{'request.course.fn'}) && (%newhash)) {
12548: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12549: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12550: foreach my $url (keys(%newhash)) {
1.711 albertel 12551: next if ($url eq 'last_known'
12552: && $env{'form.no_update_last_known'});
12553: $hash{declutter($url)}=&encode_symb($mapname,
12554: $newhash{$url}->[1],
12555: $newhash{$url}->[0]);
1.191 harris41 12556: }
1.31 www 12557: if (untie(%hash)) {
12558: return 'ok';
12559: }
12560: }
12561: }
12562: return 'error';
1.212 www 12563: }
12564:
12565: # --------------------------------------------------------------- Verify a symb
12566:
12567: sub symbverify {
1.1172.2.11 raeburn 12568: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12569: my $thisfn=$thisurl;
1.439 www 12570: $thisfn=&declutter($thisfn);
1.215 www 12571: # direct jump to resource in page or to a sequence - will construct own symbs
12572: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12573: # check URL part
1.409 www 12574: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12575:
1.431 www 12576: unless ($url eq $thisfn) { return 0; }
1.213 www 12577:
1.216 www 12578: $symb=&symbclean($symb);
1.510 www 12579: $thisurl=&deversion($thisurl);
1.439 www 12580: $thisfn=&deversion($thisfn);
1.213 www 12581:
12582: my %bighash;
12583: my $okay=0;
1.431 www 12584:
1.620 albertel 12585: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12586: &GDBM_READER(),0640)) {
1.1032 raeburn 12587: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12588: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12589: if ($map =~ m{^uploaded/.+\.page$}) {
12590: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12591: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12592: }
12593: }
12594: my $ids;
1.1172.2.122 raeburn 12595: if ($map =~ m{^uploaded/.+\.page$}) {
12596: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12597: } else {
12598: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12599: }
1.1102 raeburn 12600: unless ($ids) {
1.1172.2.13 raeburn 12601: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12602: $ids=$bighash{$idkey};
1.216 www 12603: }
12604: if ($ids) {
12605: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12606: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12607: $symb =~ s/\?.+$//;
12608: }
1.800 albertel 12609: foreach my $id (split(/\,/,$ids)) {
12610: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12611: if (
12612: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12613: eq $symb) {
1.1172.2.11 raeburn 12614: if (ref($encstate)) {
12615: $$encstate = $bighash{'encrypted_'.$id};
12616: }
1.1172.2.13 raeburn 12617: if (($env{'request.role.adv'}) ||
12618: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12619: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12620: $okay=1;
12621: last;
12622: }
12623: }
12624: }
1.216 www 12625: }
1.213 www 12626: untie(%bighash);
12627: }
12628: return $okay;
1.31 www 12629: }
12630:
1.210 www 12631: # --------------------------------------------------------------- Clean-up symb
12632:
12633: sub symbclean {
12634: my $symb=shift;
1.568 albertel 12635: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12636: # remove version from map
12637: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12638:
1.210 www 12639: # remove version from URL
12640: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12641:
1.507 www 12642: # remove wrapper
12643:
1.510 www 12644: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12645: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12646: return $symb;
1.409 www 12647: }
12648:
12649: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12650:
12651: sub encode_symb {
12652: my ($map,$resid,$url)=@_;
12653: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12654: }
1.409 www 12655:
12656: sub decode_symb {
1.568 albertel 12657: my $symb=shift;
12658: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12659: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12660: return (&fixversion($map),$resid,&fixversion($url));
12661: }
12662:
12663: sub fixversion {
12664: my $fn=shift;
1.609 banghart 12665: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12666: my %bighash;
12667: my $uri=&clutter($fn);
1.620 albertel 12668: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12669: # is this cached?
1.599 albertel 12670: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12671: if (defined($cached)) { return $result; }
12672: # unfortunately not cached, or expired
1.620 albertel 12673: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12674: &GDBM_READER(),0640)) {
12675: if ($bighash{'version_'.$uri}) {
12676: my $version=$bighash{'version_'.$uri};
1.444 www 12677: unless (($version eq 'mostrecent') ||
12678: ($version==&getversion($uri))) {
1.440 www 12679: $uri=~s/\.(\w+)$/\.$version\.$1/;
12680: }
12681: }
12682: untie %bighash;
1.413 www 12683: }
1.599 albertel 12684: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12685: }
12686:
12687: sub deversion {
12688: my $url=shift;
12689: $url=~s/\.\d+\.(\w+)$/\.$1/;
12690: return $url;
1.210 www 12691: }
12692:
1.31 www 12693: # ------------------------------------------------------ Return symb list entry
12694:
12695: sub symbread {
1.1172.2.126 raeburn 12696: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12697: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12698: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12699: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12700: unless (ref($possibles) eq 'HASH') {
12701: if ($ignorecachednull) {
12702: return $env{$cache_str} unless ($env{$cache_str} eq '');
12703: } else {
12704: return $env{$cache_str};
12705: }
1.1172.2.66 raeburn 12706: }
12707: }
1.242 www 12708: # no filename provided? try from environment
1.1172.2.54 raeburn 12709: unless ($thisfn) {
1.620 albertel 12710: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12711: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12712: }
12713: $thisfn=$env{'request.filename'};
1.44 www 12714: }
1.569 albertel 12715: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12716: # is that filename actually a symb? Verify, clean, and return
12717: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12718: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12719: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12720: }
1.242 www 12721: }
1.44 www 12722: $thisfn=declutter($thisfn);
1.31 www 12723: my %hash;
1.37 www 12724: my %bighash;
12725: my $syval='';
1.620 albertel 12726: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12727: my $targetfn = $thisfn;
1.609 banghart 12728: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12729: $targetfn = 'adm/wrapper/'.$thisfn;
12730: }
1.687 albertel 12731: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12732: $targetfn=$1;
12733: }
1.1172.2.128 raeburn 12734: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12735: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12736: &GDBM_READER(),0640)) {
12737: $syval=$hash{$targetfn};
12738: untie(%hash);
12739: }
1.1172.2.128 raeburn 12740: if ($syval && $checkforblock) {
12741: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12742: if (@blockers) {
12743: $syval='';
12744: }
12745: }
1.37 www 12746: }
12747: # ---------------------------------------------------------- There was an entry
12748: if ($syval) {
1.601 albertel 12749: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12750: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12751: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12752: #return $env{$cache_str}='';
1.601 albertel 12753: #}
12754: #$syval.=$1;
12755: #}
1.37 www 12756: } else {
12757: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12758: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12759: &GDBM_READER(),0640)) {
1.37 www 12760: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12761: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12762: unless ($ids) {
12763: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12764: }
12765: unless ($ids) {
12766: # alias?
12767: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12768: }
1.37 www 12769: if ($ids) {
12770: # ------------------------------------------------------------------- Has ID(s)
12771: my @possibilities=split(/\,/,$ids);
1.39 www 12772: if ($#possibilities==0) {
12773: # ----------------------------------------------- There is only one possibility
1.37 www 12774: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12775: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12776: $resid,$thisfn);
1.1172.2.66 raeburn 12777: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12778: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12779: $possibles->{$syval} = 1;
12780: }
1.1172.2.66 raeburn 12781: }
12782: if ($checkforblock) {
1.1172.2.126 raeburn 12783: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12784: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12785: if (@blockers) {
12786: $syval = '';
12787: untie(%bighash);
12788: return $env{$cache_str}='';
12789: }
1.1172.2.66 raeburn 12790: }
12791: }
12792: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12793: # ------------------------------------------ There is more than one possibility
12794: my $realpossible=0;
1.800 albertel 12795: foreach my $id (@possibilities) {
12796: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12797: my $canaccess;
12798: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12799: $canaccess = 1;
12800: } else {
12801: $canaccess = &allowed('bre',$file);
12802: }
12803: if ($canaccess) {
12804: my ($mapid,$resid)=split(/\./,$id);
12805: if ($bighash{'map_type_'.$mapid} ne 'page') {
12806: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12807: $resid,$thisfn);
1.1172.2.126 raeburn 12808: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12809: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12810: if ($checkforblock) {
1.1172.2.127 raeburn 12811: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12812: if (@blockers > 0) {
12813: $syval = '';
12814: } else {
1.1172.2.66 raeburn 12815: $syval = $poss_syval;
12816: $realpossible++;
12817: }
12818: } else {
12819: $syval = $poss_syval;
12820: $realpossible++;
12821: }
1.1172.2.126 raeburn 12822: if ($syval) {
12823: if (ref($possibles) eq 'HASH') {
12824: $possibles->{$syval} = 1;
12825: }
12826: }
1.1172.2.66 raeburn 12827: }
1.39 www 12828: }
1.191 harris41 12829: }
1.39 www 12830: if ($realpossible!=1) { $syval=''; }
1.249 www 12831: } else {
12832: $syval='';
1.37 www 12833: }
12834: }
1.1172.2.66 raeburn 12835: untie(%bighash);
1.481 raeburn 12836: }
1.31 www 12837: }
1.62 www 12838: if ($syval) {
1.1172.2.128 raeburn 12839: return $env{$cache_str}=$syval;
1.62 www 12840: }
1.31 www 12841: }
1.949 raeburn 12842: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12843: return $env{$cache_str}='';
1.31 www 12844: }
12845:
12846: # ---------------------------------------------------------- Return random seed
12847:
1.32 www 12848: sub numval {
12849: my $txt=shift;
12850: $txt=~tr/A-J/0-9/;
12851: $txt=~tr/a-j/0-9/;
12852: $txt=~tr/K-T/0-9/;
12853: $txt=~tr/k-t/0-9/;
12854: $txt=~tr/U-Z/0-5/;
12855: $txt=~tr/u-z/0-5/;
12856: $txt=~s/\D//g;
1.564 albertel 12857: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12858: return int($txt);
1.368 albertel 12859: }
12860:
1.484 albertel 12861: sub numval2 {
12862: my $txt=shift;
12863: $txt=~tr/A-J/0-9/;
12864: $txt=~tr/a-j/0-9/;
12865: $txt=~tr/K-T/0-9/;
12866: $txt=~tr/k-t/0-9/;
12867: $txt=~tr/U-Z/0-5/;
12868: $txt=~tr/u-z/0-5/;
12869: $txt=~s/\D//g;
12870: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12871: my $total;
12872: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12873: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12874: return int($total);
12875: }
12876:
1.575 albertel 12877: sub numval3 {
12878: use integer;
12879: my $txt=shift;
12880: $txt=~tr/A-J/0-9/;
12881: $txt=~tr/a-j/0-9/;
12882: $txt=~tr/K-T/0-9/;
12883: $txt=~tr/k-t/0-9/;
12884: $txt=~tr/U-Z/0-5/;
12885: $txt=~tr/u-z/0-5/;
12886: $txt=~s/\D//g;
12887: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12888: my $total;
12889: foreach my $val (@txts) { $total+=$val; }
12890: if ($_64bit) { $total=(($total<<32)>>32); }
12891: return $total;
12892: }
12893:
1.675 albertel 12894: sub digest {
12895: my ($data)=@_;
12896: my $digest=&Digest::MD5::md5($data);
12897: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12898: my ($e,$f);
12899: {
12900: use integer;
12901: $e=($a+$b);
12902: $f=($c+$d);
12903: if ($_64bit) {
12904: $e=(($e<<32)>>32);
12905: $f=(($f<<32)>>32);
12906: }
12907: }
12908: if (wantarray) {
12909: return ($e,$f);
12910: } else {
12911: my $g;
12912: {
12913: use integer;
12914: $g=($e+$f);
12915: if ($_64bit) {
12916: $g=(($g<<32)>>32);
12917: }
12918: }
12919: return $g;
12920: }
12921: }
12922:
1.368 albertel 12923: sub latest_rnd_algorithm_id {
1.675 albertel 12924: return '64bit5';
1.366 albertel 12925: }
1.32 www 12926:
1.503 albertel 12927: sub get_rand_alg {
12928: my ($courseid)=@_;
1.790 albertel 12929: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12930: if ($courseid) {
1.620 albertel 12931: return $env{"course.$courseid.rndseed"};
1.503 albertel 12932: }
12933: return &latest_rnd_algorithm_id();
12934: }
12935:
1.562 albertel 12936: sub validCODE {
12937: my ($CODE)=@_;
12938: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12939: return 0;
12940: }
12941:
1.491 albertel 12942: sub getCODE {
1.620 albertel 12943: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12944: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12945: defined($Apache::lonhomework::parsing_a_task) ) &&
12946: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12947: return $Apache::lonhomework::history{'resource.CODE'};
12948: }
12949: return undef;
12950: }
1.1133 foxr 12951: #
12952: # Determines the random seed for a specific context:
12953: #
12954: # parameters:
12955: # symb - in course context the symb for the seed.
12956: # course_id - The course id of the form domain_coursenum.
12957: # domain - Domain for the user.
12958: # course - Course for the user.
12959: # cenv - environment of the course.
12960: #
12961: # NOTE:
12962: # All parameters are picked out of the environment if missing
12963: # or not defined.
12964: # If a symb cannot be determined the current time is used instead.
12965: #
12966: # For a given well defined symb, courside, domain, username,
12967: # and course environment, the seed is reproducible.
12968: #
1.31 www 12969: sub rndseed {
1.1133 foxr 12970: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12971: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12972: if (!defined($symb)) {
1.366 albertel 12973: unless ($symb=$wsymb) { return time; }
12974: }
1.1146 foxr 12975: if (!defined $courseid) {
12976: $courseid=$wcourseid;
12977: }
12978: if (!defined $domain) { $domain=$wdomain; }
12979: if (!defined $username) { $username=$wusername }
1.1133 foxr 12980:
12981: my $which;
12982: if (defined($cenv->{'rndseed'})) {
12983: $which = $cenv->{'rndseed'};
12984: } else {
12985: $which =&get_rand_alg($courseid);
12986: }
1.491 albertel 12987: if (defined(&getCODE())) {
1.675 albertel 12988: if ($which eq '64bit5') {
12989: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12990: } elsif ($which eq '64bit4') {
1.575 albertel 12991: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12992: } else {
12993: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12994: }
1.675 albertel 12995: } elsif ($which eq '64bit5') {
12996: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12997: } elsif ($which eq '64bit4') {
12998: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12999: } elsif ($which eq '64bit3') {
13000: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13001: } elsif ($which eq '64bit2') {
13002: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13003: } elsif ($which eq '64bit') {
13004: return &rndseed_64bit($symb,$courseid,$domain,$username);
13005: }
13006: return &rndseed_32bit($symb,$courseid,$domain,$username);
13007: }
13008:
13009: sub rndseed_32bit {
13010: my ($symb,$courseid,$domain,$username)=@_;
13011: {
13012: use integer;
13013: my $symbchck=unpack("%32C*",$symb) << 27;
13014: my $symbseed=numval($symb) << 22;
13015: my $namechck=unpack("%32C*",$username) << 17;
13016: my $nameseed=numval($username) << 12;
13017: my $domainseed=unpack("%32C*",$domain) << 7;
13018: my $courseseed=unpack("%32C*",$courseid);
13019: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13020: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13021: #&logthis("rndseed :$num:$symb");
1.564 albertel 13022: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13023: return $num;
13024: }
13025: }
13026:
13027: sub rndseed_64bit {
13028: my ($symb,$courseid,$domain,$username)=@_;
13029: {
13030: use integer;
13031: my $symbchck=unpack("%32S*",$symb) << 21;
13032: my $symbseed=numval($symb) << 10;
13033: my $namechck=unpack("%32S*",$username);
13034:
13035: my $nameseed=numval($username) << 21;
13036: my $domainseed=unpack("%32S*",$domain) << 10;
13037: my $courseseed=unpack("%32S*",$courseid);
13038:
13039: my $num1=$symbchck+$symbseed+$namechck;
13040: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13041: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13042: #&logthis("rndseed :$num:$symb");
1.564 albertel 13043: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13044: return "$num1,$num2";
1.155 albertel 13045: }
1.366 albertel 13046: }
13047:
1.443 albertel 13048: sub rndseed_64bit2 {
13049: my ($symb,$courseid,$domain,$username)=@_;
13050: {
13051: use integer;
13052: # strings need to be an even # of cahracters long, it it is odd the
13053: # last characters gets thrown away
13054: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13055: my $symbseed=numval($symb) << 10;
13056: my $namechck=unpack("%32S*",$username.' ');
13057:
13058: my $nameseed=numval($username) << 21;
1.501 albertel 13059: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13060: my $courseseed=unpack("%32S*",$courseid.' ');
13061:
13062: my $num1=$symbchck+$symbseed+$namechck;
13063: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13064: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13065: #&logthis("rndseed :$num:$symb");
1.803 albertel 13066: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13067: return "$num1,$num2";
13068: }
13069: }
13070:
13071: sub rndseed_64bit3 {
13072: my ($symb,$courseid,$domain,$username)=@_;
13073: {
13074: use integer;
13075: # strings need to be an even # of cahracters long, it it is odd the
13076: # last characters gets thrown away
13077: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13078: my $symbseed=numval2($symb) << 10;
13079: my $namechck=unpack("%32S*",$username.' ');
13080:
13081: my $nameseed=numval2($username) << 21;
1.443 albertel 13082: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13083: my $courseseed=unpack("%32S*",$courseid.' ');
13084:
13085: my $num1=$symbchck+$symbseed+$namechck;
13086: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13087: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13088: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13089: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13090:
1.503 albertel 13091: return "$num1:$num2";
1.443 albertel 13092: }
13093: }
13094:
1.575 albertel 13095: sub rndseed_64bit4 {
13096: my ($symb,$courseid,$domain,$username)=@_;
13097: {
13098: use integer;
13099: # strings need to be an even # of cahracters long, it it is odd the
13100: # last characters gets thrown away
13101: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13102: my $symbseed=numval3($symb) << 10;
13103: my $namechck=unpack("%32S*",$username.' ');
13104:
13105: my $nameseed=numval3($username) << 21;
13106: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13107: my $courseseed=unpack("%32S*",$courseid.' ');
13108:
13109: my $num1=$symbchck+$symbseed+$namechck;
13110: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13111: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13112: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13113: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13114:
1.575 albertel 13115: return "$num1:$num2";
13116: }
13117: }
13118:
1.675 albertel 13119: sub rndseed_64bit5 {
13120: my ($symb,$courseid,$domain,$username)=@_;
13121: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13122: return "$num1:$num2";
13123: }
13124:
1.366 albertel 13125: sub rndseed_CODE_64bit {
13126: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13127: {
1.366 albertel 13128: use integer;
1.443 albertel 13129: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13130: my $symbseed=numval2($symb);
1.491 albertel 13131: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13132: my $CODEseed=numval(&getCODE());
1.443 albertel 13133: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13134: my $num1=$symbseed+$CODEchck;
13135: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13136: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13137: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13138: if ($_64bit) { $num1=(($num1<<32)>>32); }
13139: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13140: return "$num1:$num2";
1.366 albertel 13141: }
13142: }
13143:
1.575 albertel 13144: sub rndseed_CODE_64bit4 {
13145: my ($symb,$courseid,$domain,$username)=@_;
13146: {
13147: use integer;
13148: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13149: my $symbseed=numval3($symb);
13150: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13151: my $CODEseed=numval3(&getCODE());
13152: my $courseseed=unpack("%32S*",$courseid.' ');
13153: my $num1=$symbseed+$CODEchck;
13154: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13155: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13156: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13157: if ($_64bit) { $num1=(($num1<<32)>>32); }
13158: if ($_64bit) { $num2=(($num2<<32)>>32); }
13159: return "$num1:$num2";
13160: }
13161: }
13162:
1.675 albertel 13163: sub rndseed_CODE_64bit5 {
13164: my ($symb,$courseid,$domain,$username)=@_;
13165: my $code = &getCODE();
13166: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13167: return "$num1:$num2";
13168: }
13169:
1.366 albertel 13170: sub setup_random_from_rndseed {
13171: my ($rndseed)=@_;
1.503 albertel 13172: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13173: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13174: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13175: &Math::Random::random_set_seed_from_phrase($rndseed);
13176: } else {
13177: &Math::Random::random_set_seed($num1,$num2);
13178: }
1.366 albertel 13179: } else {
13180: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13181: }
1.36 albertel 13182: }
13183:
1.474 albertel 13184: sub latest_receipt_algorithm_id {
1.835 albertel 13185: return 'receipt3';
1.474 albertel 13186: }
13187:
1.480 www 13188: sub recunique {
13189: my $fucourseid=shift;
13190: my $unique;
1.835 albertel 13191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13192: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13193: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13194: } else {
13195: $unique=$perlvar{'lonReceipt'};
13196: }
13197: return unpack("%32C*",$unique);
13198: }
13199:
13200: sub recprefix {
13201: my $fucourseid=shift;
13202: my $prefix;
1.835 albertel 13203: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13204: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13205: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13206: } else {
13207: $prefix=$perlvar{'lonHostID'};
13208: }
13209: return unpack("%32C*",$prefix);
13210: }
13211:
1.76 www 13212: sub ireceipt {
1.474 albertel 13213: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13214:
13215: my $return =&recprefix($fucourseid).'-';
13216:
13217: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13218: $env{'request.state'} eq 'construct') {
13219: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13220: return $return;
13221: }
13222:
1.76 www 13223: my $cuname=unpack("%32C*",$funame);
13224: my $cudom=unpack("%32C*",$fudom);
13225: my $cucourseid=unpack("%32C*",$fucourseid);
13226: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13227: my $cunique=&recunique($fucourseid);
1.474 albertel 13228: my $cpart=unpack("%32S*",$part);
1.835 albertel 13229: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13230:
1.790 albertel 13231: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13232:
13233: $return.= ($cunique%$cuname+
13234: $cunique%$cudom+
13235: $cusymb%$cuname+
13236: $cusymb%$cudom+
13237: $cucourseid%$cuname+
13238: $cucourseid%$cudom+
13239: $cpart%$cuname+
13240: $cpart%$cudom);
13241: } else {
13242: $return.= ($cunique%$cuname+
13243: $cunique%$cudom+
13244: $cusymb%$cuname+
13245: $cusymb%$cudom+
13246: $cucourseid%$cuname+
13247: $cucourseid%$cudom);
13248: }
13249: return $return;
1.76 www 13250: }
13251:
13252: sub receipt {
1.474 albertel 13253: my ($part)=@_;
1.790 albertel 13254: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13255: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13256: }
1.260 ng 13257:
1.790 albertel 13258: sub whichuser {
13259: my ($passedsymb)=@_;
13260: my ($symb,$courseid,$domain,$name,$publicuser);
13261: if (defined($env{'form.grade_symb'})) {
13262: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13263: my $allowed=&allowed('vgr',$tmp_courseid);
13264: if (!$allowed &&
13265: exists($env{'request.course.sec'}) &&
13266: $env{'request.course.sec'} !~ /^\s*$/) {
13267: $allowed=&allowed('vgr',$tmp_courseid.
13268: '/'.$env{'request.course.sec'});
13269: }
13270: if ($allowed) {
13271: ($symb)=&get_env_multiple('form.grade_symb');
13272: $courseid=$tmp_courseid;
13273: ($domain)=&get_env_multiple('form.grade_domain');
13274: ($name)=&get_env_multiple('form.grade_username');
13275: return ($symb,$courseid,$domain,$name,$publicuser);
13276: }
13277: }
13278: if (!$passedsymb) {
13279: $symb=&symbread();
13280: } else {
13281: $symb=$passedsymb;
13282: }
13283: $courseid=$env{'request.course.id'};
13284: $domain=$env{'user.domain'};
13285: $name=$env{'user.name'};
13286: if ($name eq 'public' && $domain eq 'public') {
13287: if (!defined($env{'form.username'})) {
13288: $env{'form.username'}.=time.rand(10000000);
13289: }
13290: $name.=$env{'form.username'};
13291: }
13292: return ($symb,$courseid,$domain,$name,$publicuser);
13293:
13294: }
13295:
1.36 albertel 13296: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13297: # returns either the contents of the file or
13298: # -1 if the file doesn't exist
1.481 raeburn 13299: #
13300: # if the target is a file that was uploaded via DOCS,
13301: # a check will be made to see if a current copy exists on the local server,
13302: # if it does this will be served, otherwise a copy will be retrieved from
13303: # the home server for the course and stored in /home/httpd/html/userfiles on
13304: # the local server.
1.472 albertel 13305:
1.36 albertel 13306: sub getfile {
1.538 albertel 13307: my ($file) = @_;
1.609 banghart 13308: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13309: &repcopy($file);
13310: return &readfile($file);
13311: }
13312:
13313: sub repcopy_userfile {
13314: my ($file)=@_;
1.1142 raeburn 13315: my $londocroot = $perlvar{'lonDocRoot'};
13316: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13317: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13318: my ($cdom,$cnum,$filename) =
1.811 albertel 13319: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13320: my $uri="/uploaded/$cdom/$cnum/$filename";
13321: if (-e "$file") {
1.828 www 13322: # we already have a local copy, check it out
1.538 albertel 13323: my @fileinfo = stat($file);
1.828 www 13324: my $rtncode;
13325: my $info;
1.538 albertel 13326: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13327: if ($lwpresp ne 'ok') {
1.828 www 13328: # there is no such file anymore, even though we had a local copy
1.482 albertel 13329: if ($rtncode eq '404') {
1.538 albertel 13330: unlink($file);
1.482 albertel 13331: }
13332: return -1;
13333: }
13334: if ($info < $fileinfo[9]) {
1.828 www 13335: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13336: return 'ok';
1.828 www 13337: } else {
13338: # the file is outdated, get rid of it
13339: unlink($file);
1.482 albertel 13340: }
1.828 www 13341: }
13342: # one way or the other, at this point, we don't have the file
13343: # construct the correct path for the file
13344: my @parts = ($cdom,$cnum);
13345: if ($filename =~ m|^(.+)/[^/]+$|) {
13346: push @parts, split(/\//,$1);
13347: }
13348: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13349: foreach my $part (@parts) {
13350: $path .= '/'.$part;
13351: if (!-e $path) {
13352: mkdir($path,0770);
1.482 albertel 13353: }
13354: }
1.828 www 13355: # now the path exists for sure
13356: # get a user agent
13357: my $ua=new LWP::UserAgent;
13358: my $transferfile=$file.'.in.transfer';
13359: # FIXME: this should flock
13360: if (-e $transferfile) { return 'ok'; }
13361: my $request;
13362: $uri=~s/^\///;
1.980 raeburn 13363: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13364: my $hostname = &hostname($homeserver);
1.980 raeburn 13365: my $protocol = $protocol{$homeserver};
13366: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13367: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13368: my $response=$ua->request($request,$transferfile);
13369: # did it work?
13370: if ($response->is_error()) {
13371: unlink($transferfile);
13372: &logthis("Userfile repcopy failed for $uri");
13373: return -1;
13374: }
13375: # worked, rename the transfer file
13376: rename($transferfile,$file);
1.607 raeburn 13377: return 'ok';
1.481 raeburn 13378: }
13379:
1.517 albertel 13380: sub tokenwrapper {
13381: my $uri=shift;
1.980 raeburn 13382: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13383: $uri=~s|^/||;
1.620 albertel 13384: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13385: my $token=$1;
1.552 albertel 13386: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13387: if ($udom && $uname && $file) {
13388: $file=~s|(\?\.*)*$||;
1.949 raeburn 13389: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13390: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13391: my $hostname = &hostname($homeserver);
1.980 raeburn 13392: my $protocol = $protocol{$homeserver};
13393: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13394: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13395: (($uri=~/\?/)?'&':'?').'token='.$token.
13396: '&tokenissued='.$perlvar{'lonHostID'};
13397: } else {
13398: return '/adm/notfound.html';
13399: }
13400: }
13401:
1.828 www 13402: # call with reqtype HEAD: get last modification time
13403: # call with reqtype GET: get the file contents
13404: # Do not call this with reqtype GET for large files! It loads everything into memory
13405: #
1.481 raeburn 13406: sub getuploaded {
13407: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13408: $uri=~s/^\///;
1.980 raeburn 13409: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13410: my $hostname = &hostname($homeserver);
1.980 raeburn 13411: my $protocol = $protocol{$homeserver};
13412: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13413: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13414: my $ua=new LWP::UserAgent;
13415: my $request=new HTTP::Request($reqtype,$uri);
13416: my $response=$ua->request($request);
13417: $$rtncode = $response->code;
1.482 albertel 13418: if (! $response->is_success()) {
13419: return 'failed';
13420: }
13421: if ($reqtype eq 'HEAD') {
1.486 www 13422: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13423: } elsif ($reqtype eq 'GET') {
13424: $$info = $response->content;
1.472 albertel 13425: }
1.482 albertel 13426: return 'ok';
1.36 albertel 13427: }
13428:
1.481 raeburn 13429: sub readfile {
13430: my $file = shift;
13431: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13432: my $fh;
1.1172.2.96 raeburn 13433: open($fh,"<",$file);
1.481 raeburn 13434: my $a='';
1.800 albertel 13435: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13436: return $a;
13437: }
13438:
1.36 albertel 13439: sub filelocation {
1.590 banghart 13440: my ($dir,$file) = @_;
13441: my $location;
13442: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13443:
13444: if ($file =~ m-^/adm/-) {
13445: $file=~s-^/adm/wrapper/-/-;
13446: $file=~s-^/adm/coursedocs/showdoc/-/-;
13447: }
1.882 albertel 13448:
1.1139 www 13449: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13450: $location = $file;
1.609 banghart 13451: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13452: my ($udom,$uname,$filename)=
1.811 albertel 13453: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13454: my $home=&homeserver($uname,$udom);
13455: my $is_me=0;
13456: my @ids=¤t_machine_ids();
13457: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13458: if ($is_me) {
1.1117 foxr 13459: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13460: } else {
13461: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13462: $udom.'/'.$uname.'/'.$filename;
13463: }
1.882 albertel 13464: } elsif ($file =~ m-^/adm/-) {
13465: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13466: } else {
13467: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13468: $file=~s:^/(res|priv)/:/:;
13469: my $space=$1;
1.590 banghart 13470: if ( !( $file =~ m:^/:) ) {
13471: $location = $dir. '/'.$file;
13472: } else {
1.1142 raeburn 13473: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13474: }
1.59 albertel 13475: }
1.590 banghart 13476: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13477: while ($location=~m{/\.\./}) {
13478: if ($location =~ m{/[^/]+/\.\./}) {
13479: $location=~ s{/[^/]+/\.\./}{/}g;
13480: } else {
13481: $location=~ s{/\.\./}{/}g;
13482: }
13483: } #remove dir/..
1.590 banghart 13484: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13485: return $location;
1.46 www 13486: }
1.36 albertel 13487:
1.46 www 13488: sub hreflocation {
13489: my ($dir,$file)=@_;
1.980 raeburn 13490: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13491: $file=filelocation($dir,$file);
1.700 albertel 13492: } elsif ($file=~m-^/adm/-) {
13493: $file=~s-^/adm/wrapper/-/-;
13494: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13495: }
13496: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13497: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13498: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13499: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13500: {/uploaded/$1/$2/}x;
1.46 www 13501: }
1.913 albertel 13502: if ($file=~ m{^/userfiles/}) {
13503: $file =~ s{^/userfiles/}{/uploaded/};
13504: }
1.462 albertel 13505: return $file;
1.465 albertel 13506: }
13507:
1.1139 www 13508:
13509:
13510:
13511:
1.465 albertel 13512: sub current_machine_domains {
1.853 albertel 13513: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13514: }
13515:
13516: sub machine_domains {
13517: my ($hostname) = @_;
1.465 albertel 13518: my @domains;
1.838 albertel 13519: my %hostname = &all_hostnames();
1.465 albertel 13520: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13521: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13522: if ($hostname eq $name) {
1.844 albertel 13523: push(@domains,&host_domain($id));
1.465 albertel 13524: }
13525: }
13526: return @domains;
13527: }
13528:
13529: sub current_machine_ids {
1.853 albertel 13530: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13531: }
13532:
13533: sub machine_ids {
13534: my ($hostname) = @_;
13535: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13536: my @ids;
1.888 albertel 13537: my %name_to_host = &all_names();
1.889 albertel 13538: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13539: return @{ $name_to_host{$hostname} };
13540: }
13541: return;
1.31 www 13542: }
13543:
1.824 raeburn 13544: sub additional_machine_domains {
13545: my @domains;
1.1172.2.142 raeburn 13546: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13547: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13548: while( my $line = <$fh>) {
13549: chomp($line);
13550: $line =~ s/\s//g;
13551: push(@domains,$line);
13552: }
13553: close($fh);
13554: }
1.824 raeburn 13555: }
13556: return @domains;
13557: }
13558:
13559: sub default_login_domain {
13560: my $domain = $perlvar{'lonDefDomain'};
13561: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13562: foreach my $posdom (¤t_machine_domains(),
13563: &additional_machine_domains()) {
13564: if (lc($posdom) eq lc($testdomain)) {
13565: $domain=$posdom;
13566: last;
13567: }
13568: }
13569: return $domain;
13570: }
13571:
1.1172.2.106 raeburn 13572: sub shared_institution {
1.1172.2.136 raeburn 13573: my ($dom,$lonhost) = @_;
13574: if ($lonhost eq '') {
13575: $lonhost = $perlvar{'lonHostID'};
13576: }
1.1172.2.106 raeburn 13577: my $same_intdom;
1.1172.2.136 raeburn 13578: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13579: if ($hostintdom ne '') {
13580: my %iphost = &get_iphost();
13581: my $primary_id = &domain($dom,'primary');
13582: my $primary_ip = &get_host_ip($primary_id);
13583: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13584: foreach my $id (@{$iphost{$primary_ip}}) {
13585: my $intdom = &internet_dom($id);
13586: if ($intdom eq $hostintdom) {
13587: $same_intdom = 1;
13588: last;
13589: }
13590: }
13591: }
13592: }
13593: return $same_intdom;
13594: }
13595:
1.1172.2.120 raeburn 13596: sub uses_sts {
13597: my ($ignore_cache) = @_;
13598: my $lonhost = $perlvar{'lonHostID'};
13599: my $hostname = &hostname($lonhost);
13600: my $sts_on;
13601: if ($protocol{$lonhost} eq 'https') {
13602: my $cachetime = 12*3600;
13603: if (!$ignore_cache) {
13604: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13605: if (defined($cached)) {
13606: return $sts_on;
13607: }
13608: }
1.1172.2.121 raeburn 13609: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13610: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13611: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13612: my $response=$ua->request($request);
1.1172.2.120 raeburn 13613: if ($response->is_success) {
13614: my $has_sts = $response->header('Strict-Transport-Security');
13615: if ($has_sts eq '') {
13616: $sts_on = 0;
13617: } else {
13618: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13619: my $maxage = $1;
13620: if ($maxage) {
13621: $sts_on = 1;
13622: } else {
13623: $sts_on = 0;
13624: }
13625: } else {
13626: $sts_on = 0;
13627: }
13628: }
13629: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13630: }
13631: }
13632: return;
13633: }
13634:
1.1172.2.142 raeburn 13635: sub waf_allssl {
13636: my ($host_name) = @_;
13637: my $alias = &get_proxy_alias();
13638: if ($host_name eq '') {
13639: $host_name = $ENV{'SERVER_NAME'};
13640: }
13641: if (($host_name ne '') && ($alias eq $host_name)) {
13642: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13643: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13644: if ($defdomdefaults{'waf_sslopt'}) {
13645: return $defdomdefaults{'waf_sslopt'};
13646: }
13647: }
13648: return;
13649: }
13650:
1.1172.2.134 raeburn 13651: sub get_requestor_ip {
13652: my ($r,$nolookup,$noproxy) = @_;
13653: my $from_ip;
13654: if (ref($r)) {
1.1172.2.142 raeburn 13655: if ($r->can('useragent_ip')) {
13656: if ($noproxy && $r->can('client_ip')) {
13657: $from_ip = $r->client_ip();
13658: } else {
13659: $from_ip = $r->useragent_ip();
13660: }
13661: } elsif ($r->connection->can('remote_ip')) {
13662: $from_ip = $r->connection->remote_ip();
13663: } else {
13664: $from_ip = $r->get_remote_host($nolookup);
13665: }
1.1172.2.134 raeburn 13666: } else {
13667: $from_ip = $ENV{'REMOTE_ADDR'};
13668: }
1.1172.2.142 raeburn 13669: return $from_ip if ($noproxy);
13670: # Who controls proxy settings for server
13671: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13672: my $proxyinfo = &get_proxy_settings($dom_in_use);
13673: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13674: if ($proxyinfo->{'vpnint'}) {
13675: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13676: return $from_ip;
13677: }
13678: }
13679: if ($proxyinfo->{'trusted'}) {
13680: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13681: my $ipheader = $proxyinfo->{'ipheader'};
13682: my ($ip,$xfor);
13683: if (ref($r)) {
13684: if ($ipheader) {
13685: $ip = $r->headers_in->{$ipheader};
13686: }
13687: $xfor = $r->headers_in->{'X-Forwarded-For'};
13688: } else {
13689: if ($ipheader) {
13690: $ip = $ENV{'HTTP_'.uc($ipheader)};
13691: }
13692: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13693: }
13694: if (($ip eq '') && ($xfor ne '')) {
13695: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13696: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13697: $ip = $poss_ip;
13698: last;
13699: }
13700: }
13701: }
13702: if ($ip ne '') {
13703: return $ip;
13704: }
13705: }
13706: }
13707: }
1.1172.2.134 raeburn 13708: return $from_ip;
13709: }
13710:
1.1172.2.142 raeburn 13711: sub get_proxy_settings {
13712: my ($dom_in_use) = @_;
13713: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13714: my $proxyinfo = {
13715: ipheader => $domdefaults{'waf_ipheader'},
13716: trusted => $domdefaults{'waf_trusted'},
13717: vpnint => $domdefaults{'waf_vpnint'},
13718: vpnext => $domdefaults{'waf_vpnext'},
13719: sslopt => $domdefaults{'waf_sslopt'},
13720: };
13721: return $proxyinfo;
13722: }
13723:
13724: sub ip_match {
13725: my ($ip,$pattern_str) = @_;
13726: $ip=Net::CIDR::cidrvalidate($ip);
13727: if ($ip) {
13728: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13729: }
13730: return;
13731: }
13732:
13733: sub get_proxy_alias {
13734: my ($lonid) = @_;
13735: if ($lonid eq '') {
13736: $lonid = $perlvar{'lonHostID'};
13737: }
13738: if (!defined(&hostname($lonid))) {
13739: return;
13740: }
13741: if ($lonid ne '') {
13742: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13743: if ($cached) {
13744: return $alias;
13745: }
13746: my $dom = &Apache::lonnet::host_domain($lonid);
13747: if ($dom ne '') {
13748: my $cachetime = 60*60*24;
13749: my %domconfig =
13750: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13751: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13752: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13753: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13754: }
13755: }
13756: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13757: }
13758: }
13759: return;
13760: }
13761:
13762: sub use_proxy_alias {
13763: my ($r,$lonid) = @_;
13764: my $alias = &get_proxy_alias($lonid);
13765: if ($alias) {
13766: my $dom = &host_domain($lonid);
13767: if ($dom ne '') {
13768: my $proxyinfo = &get_proxy_settings($dom);
13769: my ($vpnint,$remote_ip);
13770: if (ref($proxyinfo) eq 'HASH') {
13771: $vpnint = $proxyinfo->{'vpnint'};
13772: if ($vpnint) {
13773: $remote_ip = &get_requestor_ip($r,1,1);
13774: }
13775: }
13776: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13777: return $alias;
13778: }
13779: }
13780: }
13781: return;
13782: }
13783:
13784: sub alias_sso {
13785: my ($lonid) = @_;
13786: if ($lonid eq '') {
13787: $lonid = $perlvar{'lonHostID'};
13788: }
13789: if (!defined(&hostname($lonid))) {
13790: return;
13791: }
13792: if ($lonid ne '') {
13793: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13794: if ($cached) {
13795: return $use_alias;
13796: }
13797: my $dom = &Apache::lonnet::host_domain($lonid);
13798: if ($dom ne '') {
13799: my $cachetime = 60*60*24;
13800: my %domconfig =
13801: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13802: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13803: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13804: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13805: }
13806: }
13807: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13808: }
13809: }
13810: return;
13811: }
13812:
13813: sub get_saml_landing {
13814: my ($lonid) = @_;
13815: if ($lonid eq '') {
13816: my $defdom = &default_login_domain();
13817: my @hosts = ¤t_machine_ids();
13818: if (@hosts > 1) {
13819: foreach my $hostid (@hosts) {
13820: if (&host_domain($hostid) eq $defdom) {
13821: $lonid = $hostid;
13822: last;
13823: }
13824: }
13825: } else {
13826: $lonid = $perlvar{'lonHostID'};
13827: }
13828: if ($lonid) {
13829: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13830: return;
13831: }
13832: } else {
13833: return;
13834: }
13835: } elsif (!defined(&hostname($lonid))) {
13836: return;
13837: }
13838: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13839: if ($cached) {
13840: return $landing;
13841: }
13842: my $dom = &Apache::lonnet::host_domain($lonid);
13843: if ($dom ne '') {
13844: my $cachetime = 60*60*24;
13845: my %domconfig =
13846: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13847: if (ref($domconfig{'login'}) eq 'HASH') {
13848: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13849: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13850: $landing = 1;
13851: }
13852: }
13853: }
13854: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13855: }
13856: return;
13857: }
13858:
1.31 www 13859: # ------------------------------------------------------------- Declutters URLs
13860:
13861: sub declutter {
13862: my $thisfn=shift;
1.569 albertel 13863: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13864: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13865: $thisfn=~s{^/home/httpd/html}{};
13866: }
1.31 www 13867: $thisfn=~s/^\///;
1.697 albertel 13868: $thisfn=~s|^adm/wrapper/||;
13869: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13870: $thisfn=~s/^res\///;
1.1172 bisitz 13871: $thisfn=~s/^priv\///;
1.1032 raeburn 13872: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13873: $thisfn=~s/\?.+$//;
13874: }
1.268 www 13875: return $thisfn;
13876: }
13877:
13878: # ------------------------------------------------------------- Clutter up URLs
13879:
13880: sub clutter {
13881: my $thisfn='/'.&declutter(shift);
1.887 albertel 13882: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13883: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13884: $thisfn='/res'.$thisfn;
13885: }
1.1031 raeburn 13886: if ($thisfn !~m|^/adm|) {
13887: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13888: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13889: } else {
13890: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13891: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13892: if ($embstyle eq 'ssi'
13893: || ($embstyle eq 'hdn')
13894: || ($embstyle eq 'rat')
13895: || ($embstyle eq 'prv')
13896: || ($embstyle eq 'ign')) {
13897: #do nothing with these
13898: } elsif (($embstyle eq 'img')
1.695 albertel 13899: || ($embstyle eq 'emb')
13900: || ($embstyle eq 'wrp')) {
13901: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13902: } elsif ($embstyle eq 'unk'
13903: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13904: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13905: } else {
1.718 www 13906: # &logthis("Got a blank emb style");
1.695 albertel 13907: }
1.694 albertel 13908: }
13909: }
1.31 www 13910: return $thisfn;
1.12 www 13911: }
13912:
1.787 albertel 13913: sub clutter_with_no_wrapper {
13914: my $uri = &clutter(shift);
13915: if ($uri =~ m-^/adm/-) {
13916: $uri =~ s-^/adm/wrapper/-/-;
13917: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13918: }
13919: return $uri;
13920: }
13921:
1.557 albertel 13922: sub freeze_escape {
13923: my ($value)=@_;
13924: if (ref($value)) {
13925: $value=&nfreeze($value);
13926: return '__FROZEN__'.&escape($value);
13927: }
13928: return &escape($value);
13929: }
13930:
1.11 www 13931:
1.557 albertel 13932: sub thaw_unescape {
13933: my ($value)=@_;
13934: if ($value =~ /^__FROZEN__/) {
13935: substr($value,0,10,undef);
13936: $value=&unescape($value);
13937: return &thaw($value);
13938: }
13939: return &unescape($value);
13940: }
13941:
1.436 albertel 13942: sub correct_line_ends {
13943: my ($result)=@_;
13944: $$result =~s/\r\n/\n/mg;
13945: $$result =~s/\r/\n/mg;
1.415 albertel 13946: }
1.1 albertel 13947: # ================================================================ Main Program
13948:
1.184 www 13949: sub goodbye {
1.204 albertel 13950: &logthis("Starting Shut down");
1.443 albertel 13951: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13952: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13953: #converted
1.599 albertel 13954: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13955: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13956: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13957: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13958: #1.1 only
1.870 albertel 13959: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13960: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13961: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13962: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13963: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13964: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13965: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13966: &flushcourselogs();
13967: &logthis("Shutting down");
13968: }
13969:
1.852 albertel 13970: sub get_dns {
1.1172.2.17 raeburn 13971: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13972: if (!$ignore_cache) {
13973: my ($content,$cached)=
13974: &Apache::lonnet::is_cached_new('dns',$url);
13975: if ($cached) {
1.1172.2.17 raeburn 13976: &$func($content,$hashref);
1.869 albertel 13977: return;
13978: }
13979: }
13980:
13981: my %alldns;
1.1172.2.96 raeburn 13982: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13983: foreach my $dns (<$config>) {
13984: next if ($dns !~ /^\^(\S*)/x);
13985: my $line = $1;
13986: my ($host,$protocol) = split(/:/,$line);
13987: if ($protocol ne 'https') {
13988: $protocol = 'http';
13989: }
13990: $alldns{$host} = $protocol;
1.979 raeburn 13991: }
1.1172.2.96 raeburn 13992: close($config);
1.869 albertel 13993: }
13994: while (%alldns) {
1.1172.2.52 raeburn 13995: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13996: my @content;
13997: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13998: my $command = (split('/',$url))[3];
13999: my ($dir,$file) = &parse_getdns_url($command,$url);
14000: delete($alldns{$dns});
14001: next if (($dir eq '') || ($file eq ''));
14002: if (open(my $config,'<',"$dir/$file")) {
14003: @content = <$config>;
14004: close($config);
14005: }
14006: } else {
14007: my $ua=new LWP::UserAgent;
14008: $ua->timeout(30);
14009: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14010: my $response=$ua->request($request);
14011: delete($alldns{$dns});
14012: next if ($response->is_error());
14013: @content = split("\n",$response->content);
14014: }
1.1172.2.17 raeburn 14015: unless ($nocache) {
1.1172.2.23 raeburn 14016: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 14017: }
14018: &$func(\@content,$hashref);
1.869 albertel 14019: return;
1.852 albertel 14020: }
1.871 albertel 14021: my $which = (split('/',$url))[3];
14022: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14023: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14024: my @content = <$config>;
14025: &$func(\@content,$hashref);
14026: }
1.1172.2.17 raeburn 14027: return;
14028: }
14029:
14030: # ------------------------------------------------------Get DNS checksums file
14031: sub parse_dns_checksums_tab {
14032: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14033: my $lonhost = $perlvar{'lonHostID'};
14034: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14035: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14036: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14037: my $webconfdir = '/etc/httpd/conf';
14038: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14039: $webconfdir = '/etc/apache2';
14040: } elsif ($distro =~ /^sles(\d+)$/) {
14041: if ($1 >= 10) {
14042: $webconfdir = '/etc/apache2';
14043: }
14044: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14045: if ($1 >= 10.0) {
14046: $webconfdir = '/etc/apache2';
14047: }
14048: }
1.1172.2.17 raeburn 14049: my ($release,$timestamp) = split(/\-/,$loncaparev);
14050: my (%chksum,%revnum);
14051: if (ref($lines) eq 'ARRAY') {
14052: chomp(@{$lines});
1.1172.2.34 raeburn 14053: my $version = shift(@{$lines});
14054: if ($version eq $release) {
1.1172.2.17 raeburn 14055: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14056: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14057: if ($file =~ m{^/etc/httpd/conf}) {
14058: if ($webconfdir eq '/etc/apache2') {
14059: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14060: }
14061: }
1.1172.2.34 raeburn 14062: $chksum{$file} = $shasum;
14063: $revnum{$file} = $version;
1.1172.2.17 raeburn 14064: }
14065: if (ref($hashref) eq 'HASH') {
14066: %{$hashref} = (
14067: sums => \%chksum,
14068: versions => \%revnum,
14069: );
14070: }
14071: }
14072: }
1.869 albertel 14073: return;
1.852 albertel 14074: }
1.1172.2.17 raeburn 14075:
14076: sub fetch_dns_checksums {
14077: my %checksums;
1.1172.2.34 raeburn 14078: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14079: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14080: my ($release,$timestamp) = split(/\-/,$loncaparev);
14081: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14082: \%checksums);
14083: return \%checksums;
14084: }
14085:
1.1172.2.142 raeburn 14086: sub parse_getdns_url {
14087: my ($command,$url) = @_;
14088: my $dir = $perlvar{'lonTabDir'};
14089: my $file;
14090: if ($command eq 'hosts') {
14091: $file = 'dns_hosts.tab';
14092: } elsif ($command eq 'domain') {
14093: $file = 'dns_domain.tab';
14094: } elsif ($command eq 'checksums') {
14095: my $version = (split('/',$url))[4];
14096: $file = "dns_checksums/$version.tab",
14097: }
14098: return ($dir,$file);
14099: }
14100:
1.327 albertel 14101: # ------------------------------------------------------------ Read domain file
14102: {
1.852 albertel 14103: my $loaded;
1.846 albertel 14104: my %domain;
14105:
1.852 albertel 14106: sub parse_domain_tab {
14107: my ($lines) = @_;
14108: foreach my $line (@$lines) {
14109: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14110:
1.846 albertel 14111: chomp($line);
1.852 albertel 14112: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14113: my %this_domain;
14114: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14115: 'lang_def', 'city', 'longi', 'lati',
14116: 'primary') {
14117: $this_domain{$field} = shift(@elements);
14118: }
14119: $domain{$name} = \%this_domain;
1.852 albertel 14120: }
14121: }
1.864 albertel 14122:
14123: sub reset_domain_info {
14124: undef($loaded);
14125: undef(%domain);
14126: }
14127:
1.852 albertel 14128: sub load_domain_tab {
1.1172.2.70 raeburn 14129: my ($ignore_cache,$nocache) = @_;
14130: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14131: my $fh;
1.1172.2.96 raeburn 14132: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14133: my @lines = <$fh>;
14134: &parse_domain_tab(\@lines);
1.448 albertel 14135: }
1.852 albertel 14136: close($fh);
14137: $loaded = 1;
1.327 albertel 14138: }
1.846 albertel 14139:
14140: sub domain {
1.852 albertel 14141: &load_domain_tab() if (!$loaded);
14142:
1.846 albertel 14143: my ($name,$what) = @_;
14144: return if ( !exists($domain{$name}) );
14145:
14146: if (!$what) {
14147: return $domain{$name}{'description'};
14148: }
14149: return $domain{$name}{$what};
14150: }
1.974 raeburn 14151:
14152: sub domain_info {
14153: &load_domain_tab() if (!$loaded);
14154: return %domain;
14155: }
14156:
1.327 albertel 14157: }
14158:
14159:
1.1 albertel 14160: # ------------------------------------------------------------- Read hosts file
14161: {
1.838 albertel 14162: my %hostname;
1.844 albertel 14163: my %hostdom;
1.845 albertel 14164: my %libserv;
1.852 albertel 14165: my $loaded;
1.888 albertel 14166: my %name_to_host;
1.1074 raeburn 14167: my %internetdom;
1.1107 raeburn 14168: my %LC_dns_serv;
1.852 albertel 14169:
14170: sub parse_hosts_tab {
14171: my ($file) = @_;
14172: foreach my $configline (@$file) {
14173: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14174: chomp($configline);
14175: if ($configline =~ /^\^/) {
14176: if ($configline =~ /^\^([\w.\-]+)/) {
14177: $LC_dns_serv{$1} = 1;
14178: }
14179: next;
14180: }
1.1074 raeburn 14181: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14182: $name=~s/\s//g;
14183: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14184: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14185: my $curr = $hostname{$id};
14186: my $skip;
14187: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14188: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14189: $skip = 1;
14190: } else {
14191: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14192: }
14193: }
14194: unless ($skip) {
14195: push(@{$name_to_host{$name}},$id);
14196: }
14197: } else {
14198: push(@{$name_to_host{$name}},$id);
14199: }
1.852 albertel 14200: $hostname{$id}=$name;
14201: $hostdom{$id}=$domain;
14202: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14203: if (defined($protocol)) {
14204: if ($protocol eq 'https') {
14205: $protocol{$id} = $protocol;
14206: } else {
14207: $protocol{$id} = 'http';
14208: }
1.968 raeburn 14209: } else {
1.969 raeburn 14210: $protocol{$id} = 'http';
1.968 raeburn 14211: }
1.1074 raeburn 14212: if (defined($intdom)) {
14213: $internetdom{$id} = $intdom;
14214: }
1.852 albertel 14215: }
14216: }
14217: }
1.864 albertel 14218:
14219: sub reset_hosts_info {
1.897 albertel 14220: &purge_remembered();
1.864 albertel 14221: &reset_domain_info();
14222: &reset_hosts_ip_info();
1.892 albertel 14223: undef(%name_to_host);
1.864 albertel 14224: undef(%hostname);
14225: undef(%hostdom);
14226: undef(%libserv);
14227: undef($loaded);
14228: }
1.1 albertel 14229:
1.852 albertel 14230: sub load_hosts_tab {
1.1172.2.70 raeburn 14231: my ($ignore_cache,$nocache) = @_;
14232: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14233: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14234: my @config = <$config>;
14235: &parse_hosts_tab(\@config);
14236: close($config);
14237: $loaded=1;
1.1 albertel 14238: }
1.852 albertel 14239:
1.838 albertel 14240: sub hostname {
1.852 albertel 14241: &load_hosts_tab() if (!$loaded);
14242:
1.838 albertel 14243: my ($lonid) = @_;
14244: return $hostname{$lonid};
14245: }
1.845 albertel 14246:
1.838 albertel 14247: sub all_hostnames {
1.852 albertel 14248: &load_hosts_tab() if (!$loaded);
14249:
1.838 albertel 14250: return %hostname;
14251: }
1.845 albertel 14252:
1.888 albertel 14253: sub all_names {
1.1172.2.70 raeburn 14254: my ($ignore_cache,$nocache) = @_;
14255: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14256:
14257: return %name_to_host;
14258: }
14259:
1.974 raeburn 14260: sub all_host_domain {
14261: &load_hosts_tab() if (!$loaded);
14262: return %hostdom;
14263: }
14264:
1.845 albertel 14265: sub is_library {
1.852 albertel 14266: &load_hosts_tab() if (!$loaded);
14267:
1.845 albertel 14268: return exists($libserv{$_[0]});
14269: }
14270:
14271: sub all_library {
1.852 albertel 14272: &load_hosts_tab() if (!$loaded);
14273:
1.845 albertel 14274: return %libserv;
14275: }
14276:
1.1062 droeschl 14277: sub unique_library {
14278: #2x reverse removes all hostnames that appear more than once
14279: my %unique = reverse &all_library();
14280: return reverse %unique;
14281: }
14282:
1.841 albertel 14283: sub get_servers {
1.852 albertel 14284: &load_hosts_tab() if (!$loaded);
14285:
1.841 albertel 14286: my ($domain,$type) = @_;
14287: my %possible_hosts = ($type eq 'library') ? %libserv
14288: : %hostname;
14289: my %result;
1.842 albertel 14290: if (ref($domain) eq 'ARRAY') {
14291: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14292: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14293: $result{$host} = $hostname;
14294: }
14295: }
14296: } else {
14297: while ( my ($host,$hostname) = each(%possible_hosts)) {
14298: if ($hostdom{$host} eq $domain) {
14299: $result{$host} = $hostname;
14300: }
1.841 albertel 14301: }
14302: }
14303: return %result;
14304: }
1.845 albertel 14305:
1.1062 droeschl 14306: sub get_unique_servers {
14307: my %unique = reverse &get_servers(@_);
14308: return reverse %unique;
14309: }
14310:
1.844 albertel 14311: sub host_domain {
1.852 albertel 14312: &load_hosts_tab() if (!$loaded);
14313:
1.844 albertel 14314: my ($lonid) = @_;
14315: return $hostdom{$lonid};
14316: }
14317:
1.841 albertel 14318: sub all_domains {
1.852 albertel 14319: &load_hosts_tab() if (!$loaded);
14320:
1.841 albertel 14321: my %seen;
14322: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14323: return @uniq;
14324: }
1.1074 raeburn 14325:
14326: sub internet_dom {
14327: &load_hosts_tab() if (!$loaded);
14328:
14329: my ($lonid) = @_;
14330: return $internetdom{$lonid};
14331: }
1.1107 raeburn 14332:
14333: sub is_LC_dns {
14334: &load_hosts_tab() if (!$loaded);
14335:
14336: my ($hostname) = @_;
14337: return exists($LC_dns_serv{$hostname});
14338: }
14339:
1.1 albertel 14340: }
14341:
1.847 albertel 14342: {
14343: my %iphost;
1.856 albertel 14344: my %name_to_ip;
14345: my %lonid_to_ip;
1.869 albertel 14346:
1.847 albertel 14347: sub get_hosts_from_ip {
14348: my ($ip) = @_;
14349: my %iphosts = &get_iphost();
14350: if (ref($iphosts{$ip})) {
14351: return @{$iphosts{$ip}};
14352: }
14353: return;
1.839 albertel 14354: }
1.864 albertel 14355:
14356: sub reset_hosts_ip_info {
14357: undef(%iphost);
14358: undef(%name_to_ip);
14359: undef(%lonid_to_ip);
14360: }
1.856 albertel 14361:
14362: sub get_host_ip {
14363: my ($lonid) = @_;
14364: if (exists($lonid_to_ip{$lonid})) {
14365: return $lonid_to_ip{$lonid};
14366: }
14367: my $name=&hostname($lonid);
14368: my $ip = gethostbyname($name);
14369: return if (!$ip || length($ip) ne 4);
14370: $ip=inet_ntoa($ip);
14371: $name_to_ip{$name} = $ip;
14372: $lonid_to_ip{$lonid} = $ip;
14373: return $ip;
14374: }
1.847 albertel 14375:
14376: sub get_iphost {
1.1172.2.70 raeburn 14377: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14378:
1.869 albertel 14379: if (!$ignore_cache) {
14380: if (%iphost) {
14381: return %iphost;
14382: }
14383: my ($ip_info,$cached)=
14384: &Apache::lonnet::is_cached_new('iphost','iphost');
14385: if ($cached) {
14386: %iphost = %{$ip_info->[0]};
14387: %name_to_ip = %{$ip_info->[1]};
14388: %lonid_to_ip = %{$ip_info->[2]};
14389: return %iphost;
14390: }
14391: }
1.894 albertel 14392:
14393: # get yesterday's info for fallback
14394: my %old_name_to_ip;
14395: my ($ip_info,$cached)=
14396: &Apache::lonnet::is_cached_new('iphost','iphost');
14397: if ($cached) {
14398: %old_name_to_ip = %{$ip_info->[1]};
14399: }
14400:
1.1172.2.70 raeburn 14401: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14402: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14403: my $ip;
14404: if (!exists($name_to_ip{$name})) {
14405: $ip = gethostbyname($name);
14406: if (!$ip || length($ip) ne 4) {
1.894 albertel 14407: if (defined($old_name_to_ip{$name})) {
14408: $ip = $old_name_to_ip{$name};
14409: &logthis("Can't find $name defaulting to old $ip");
14410: } else {
14411: &logthis("Name $name no IP found");
14412: next;
14413: }
14414: } else {
14415: $ip=inet_ntoa($ip);
1.847 albertel 14416: }
14417: $name_to_ip{$name} = $ip;
14418: } else {
14419: $ip = $name_to_ip{$name};
1.653 albertel 14420: }
1.888 albertel 14421: foreach my $id (@{ $name_to_host{$name} }) {
14422: $lonid_to_ip{$id} = $ip;
14423: }
14424: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14425: }
1.1172.2.70 raeburn 14426: unless ($nocache) {
14427: &do_cache_new('iphost','iphost',
14428: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14429: 48*60*60);
14430: }
1.869 albertel 14431:
1.847 albertel 14432: return %iphost;
1.598 albertel 14433: }
14434:
1.992 raeburn 14435: #
14436: # Given a DNS returns the loncapa host name for that DNS
14437: #
14438: sub host_from_dns {
14439: my ($dns) = @_;
14440: my @hosts;
14441: my $ip;
14442:
1.993 raeburn 14443: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14444: $ip = $name_to_ip{$dns};
14445: }
14446: if (!$ip) {
14447: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14448: if (length($ip) == 4) {
14449: $ip = &IO::Socket::inet_ntoa($ip);
14450: }
14451: }
14452: if ($ip) {
14453: @hosts = get_hosts_from_ip($ip);
14454: return $hosts[0];
14455: }
14456: return undef;
1.986 foxr 14457: }
1.992 raeburn 14458:
1.1074 raeburn 14459: sub get_internet_names {
14460: my ($lonid) = @_;
14461: return if ($lonid eq '');
14462: my ($idnref,$cached)=
14463: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14464: if ($cached) {
14465: return $idnref;
14466: }
14467: my $ip = &get_host_ip($lonid);
14468: my @hosts = &get_hosts_from_ip($ip);
14469: my %iphost = &get_iphost();
14470: my (@idns,%seen);
14471: foreach my $id (@hosts) {
14472: my $dom = &host_domain($id);
14473: my $prim_id = &domain($dom,'primary');
14474: my $prim_ip = &get_host_ip($prim_id);
14475: next if ($seen{$prim_ip});
14476: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14477: foreach my $id (@{$iphost{$prim_ip}}) {
14478: my $intdom = &internet_dom($id);
14479: unless (grep(/^\Q$intdom\E$/,@idns)) {
14480: push(@idns,$intdom);
14481: }
14482: }
14483: }
14484: $seen{$prim_ip} = 1;
14485: }
1.1172.2.23 raeburn 14486: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14487: }
14488:
1.986 foxr 14489: }
14490:
1.1079 raeburn 14491: sub all_loncaparevs {
1.1172.2.39 raeburn 14492: 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 14493: }
14494:
1.1172.2.27 raeburn 14495: # ------------------------------------------------------- Read loncaparev table
14496: {
14497: sub load_loncaparevs {
14498: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14499: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14500: while (my $configline=<$config>) {
14501: chomp($configline);
14502: my ($hostid,$loncaparev)=split(/:/,$configline);
14503: $loncaparevs{$hostid}=$loncaparev;
14504: }
14505: close($config);
14506: }
14507: }
14508: }
14509: }
14510:
14511: # ----------------------------------------------------- Read serverhostID table
14512: {
14513: sub load_serverhomeIDs {
14514: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14515: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14516: while (my $configline=<$config>) {
14517: chomp($configline);
14518: my ($name,$id)=split(/:/,$configline);
14519: $serverhomeIDs{$name}=$id;
14520: }
14521: close($config);
14522: }
14523: }
14524: }
14525: }
14526:
14527:
1.862 albertel 14528: BEGIN {
14529:
14530: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14531: unless ($readit) {
14532: {
14533: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14534: %perlvar = (%perlvar,%{$configvars});
14535: }
14536:
14537:
1.1 albertel 14538: # ------------------------------------------------------ Read spare server file
14539: {
1.1172.2.96 raeburn 14540: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14541:
14542: while (my $configline=<$config>) {
14543: chomp($configline);
1.284 matthew 14544: if ($configline) {
1.784 albertel 14545: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14546: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14547: push(@{ $spareid{$type} }, $host);
1.1 albertel 14548: }
14549: }
1.448 albertel 14550: close($config);
1.1 albertel 14551: }
1.11 www 14552: # ------------------------------------------------------------ Read permissions
14553: {
1.1172.2.96 raeburn 14554: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14555:
14556: while (my $configline=<$config>) {
1.448 albertel 14557: chomp($configline);
14558: if ($configline) {
14559: my ($role,$perm)=split(/ /,$configline);
14560: if ($perm ne '') { $pr{$role}=$perm; }
14561: }
1.11 www 14562: }
1.448 albertel 14563: close($config);
1.11 www 14564: }
14565:
14566: # -------------------------------------------- Read plain texts for permissions
14567: {
1.1172.2.96 raeburn 14568: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14569:
14570: while (my $configline=<$config>) {
1.448 albertel 14571: chomp($configline);
14572: if ($configline) {
1.742 raeburn 14573: my ($short,@plain)=split(/:/,$configline);
14574: %{$prp{$short}} = ();
14575: if (@plain > 0) {
14576: $prp{$short}{'std'} = $plain[0];
14577: for (my $i=1; $i<@plain; $i++) {
14578: $prp{$short}{'alt'.$i} = $plain[$i];
14579: }
14580: }
1.448 albertel 14581: }
1.135 www 14582: }
1.448 albertel 14583: close($config);
1.135 www 14584: }
14585:
14586: # ---------------------------------------------------------- Read package table
14587: {
1.1172.2.96 raeburn 14588: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14589:
14590: while (my $configline=<$config>) {
1.483 albertel 14591: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14592: chomp($configline);
14593: my ($short,$plain)=split(/:/,$configline);
14594: my ($pack,$name)=split(/\&/,$short);
14595: if ($plain ne '') {
14596: $packagetab{$pack.'&'.$name.'&name'}=$name;
14597: $packagetab{$short}=$plain;
14598: }
1.11 www 14599: }
1.448 albertel 14600: close($config);
1.329 matthew 14601: }
14602:
1.1172.2.27 raeburn 14603: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14604:
1.1172.2.27 raeburn 14605: &load_loncaparevs();
14606:
14607: # ------------------------------------------------------- Read serverhostID table
14608:
14609: &load_serverhomeIDs();
1.1074 raeburn 14610:
1.1172.2.27 raeburn 14611: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14612: {
14613: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14614: if (-e $file) {
14615: my $parser = HTML::LCParser->new($file);
14616: while (my $token = $parser->get_token()) {
14617: if ($token->[0] eq 'S') {
14618: my $item = $token->[1];
14619: my $name = $token->[2]{'name'};
14620: my $value = $token->[2]{'value'};
14621: if ($item ne '' && $name ne '' && $value ne '') {
14622: my $release = $parser->get_text();
14623: $release =~ s/(^\s*|\s*$ )//gx;
14624: $needsrelease{$item.':'.$name.':'.$value} = $release;
14625: }
14626: }
14627: }
14628: }
1.1073 raeburn 14629: }
14630:
1.1138 raeburn 14631: # ---------------------------------------------------------- Read managers table
14632: {
14633: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14634: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14635: while (my $configline=<$config>) {
14636: chomp($configline);
14637: next if ($configline =~ /^\#/);
14638: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14639: $managerstab{$configline} = 1;
14640: }
14641: }
14642: close($config);
14643: }
14644: }
14645: }
14646:
1.329 matthew 14647: # ------------- set up temporary directory
14648: {
1.1117 foxr 14649: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14650:
1.11 www 14651: }
14652:
1.1172.2.104 raeburn 14653: # ------------- set default texengine (domain default overrides this)
14654: {
14655: $deftex = LONCAPA::texengine();
14656: }
14657:
1.1172.2.114 raeburn 14658: # ------------- set default minimum length for passwords for internal auth users
14659: {
14660: $passwdmin = LONCAPA::passwd_min();
14661: }
14662:
1.794 albertel 14663: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14664: 'compress_threshold'=> 20_000,
14665: });
1.185 www 14666:
1.281 www 14667: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14668: $dumpcount=0;
1.958 www 14669: $locknum=0;
1.22 www 14670:
1.163 harris41 14671: &logtouch();
1.672 albertel 14672: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14673: $readit=1;
1.564 albertel 14674: {
14675: use integer;
14676: my $test=(2**32)+1;
1.568 albertel 14677: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14678: &logthis(" Detected 64bit platform ($_64bit)");
14679: }
1.195 www 14680: }
1.1 albertel 14681: }
1.179 www 14682:
1.1 albertel 14683: 1;
1.191 harris41 14684: __END__
14685:
1.243 albertel 14686: =pod
14687:
1.191 harris41 14688: =head1 NAME
14689:
1.243 albertel 14690: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14691:
14692: =head1 SYNOPSIS
14693:
1.243 albertel 14694: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14695:
14696: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14697:
1.243 albertel 14698: Common parameters:
14699:
14700: =over 4
14701:
14702: =item *
14703:
14704: $uname : an internal username (if $cname expecting a course Id specifically)
14705:
14706: =item *
14707:
14708: $udom : a domain (if $cdom expecting a course's domain specifically)
14709:
14710: =item *
14711:
14712: $symb : a resource instance identifier
14713:
14714: =item *
14715:
14716: $namespace : the name of a .db file that contains the data needed or
14717: being set.
14718:
14719: =back
14720:
1.394 bowersj2 14721: =head1 OVERVIEW
1.191 harris41 14722:
1.394 bowersj2 14723: lonnet provides subroutines which interact with the
14724: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14725: about classes, users, and resources.
1.243 albertel 14726:
14727: For many of these objects you can also use this to store data about
14728: them or modify them in various ways.
1.191 harris41 14729:
1.394 bowersj2 14730: =head2 Symbs
1.191 harris41 14731:
1.394 bowersj2 14732: To identify a specific instance of a resource, LON-CAPA uses symbols
14733: or "symbs"X<symb>. These identifiers are built from the URL of the
14734: map, the resource number of the resource in the map, and the URL of
14735: the resource itself. The latter is somewhat redundant, but might help
14736: if maps change.
14737:
14738: An example is
14739:
14740: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14741:
14742: The respective map entry is
14743:
14744: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14745: title="Problem 2">
14746: </resource>
14747:
14748: Symbs are used by the random number generator, as well as to store and
14749: restore data specific to a certain instance of for example a problem.
14750:
14751: =head2 Storing And Retrieving Data
14752:
14753: X<store()>X<cstore()>X<restore()>Three of the most important functions
14754: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14755: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14756: is is the non-critical message twin of cstore. These functions are for
14757: handlers to store a perl hash to a user's permanent data space in an
14758: easy manner, and to retrieve it again on another call. It is expected
14759: that a handler would use this once at the beginning to retrieve data,
14760: and then again once at the end to send only the new data back.
14761:
14762: The data is stored in the user's data directory on the user's
14763: homeserver under the ID of the course.
14764:
14765: The hash that is returned by restore will have all of the previous
14766: value for all of the elements of the hash.
14767:
14768: Example:
14769:
14770: #creating a hash
14771: my %hash;
14772: $hash{'foo'}='bar';
14773:
14774: #storing it
14775: &Apache::lonnet::cstore(\%hash);
14776:
14777: #changing a value
14778: $hash{'foo'}='notbar';
14779:
14780: #adding a new value
14781: $hash{'bar'}='foo';
14782: &Apache::lonnet::cstore(\%hash);
14783:
14784: #retrieving the hash
14785: my %history=&Apache::lonnet::restore();
14786:
14787: #print the hash
14788: foreach my $key (sort(keys(%history))) {
14789: print("\%history{$key} = $history{$key}");
14790: }
14791:
14792: Will print out:
1.191 harris41 14793:
1.394 bowersj2 14794: %history{1:foo} = bar
14795: %history{1:keys} = foo:timestamp
14796: %history{1:timestamp} = 990455579
14797: %history{2:bar} = foo
14798: %history{2:foo} = notbar
14799: %history{2:keys} = foo:bar:timestamp
14800: %history{2:timestamp} = 990455580
14801: %history{bar} = foo
14802: %history{foo} = notbar
14803: %history{timestamp} = 990455580
14804: %history{version} = 2
14805:
14806: Note that the special hash entries C<keys>, C<version> and
14807: C<timestamp> were added to the hash. C<version> will be equal to the
14808: total number of versions of the data that have been stored. The
14809: C<timestamp> attribute will be the UNIX time the hash was
14810: stored. C<keys> is available in every historical section to list which
14811: keys were added or changed at a specific historical revision of a
14812: hash.
14813:
14814: B<Warning>: do not store the hash that restore returns directly. This
14815: will cause a mess since it will restore the historical keys as if the
14816: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14817:
1.394 bowersj2 14818: Calling convention:
1.191 harris41 14819:
1.1172.2.27 raeburn 14820: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14821: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14822:
1.394 bowersj2 14823: For more detailed information, see lonnet specific documentation.
1.191 harris41 14824:
1.394 bowersj2 14825: =head1 RETURN MESSAGES
1.191 harris41 14826:
1.394 bowersj2 14827: =over 4
1.191 harris41 14828:
1.394 bowersj2 14829: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14830:
1.394 bowersj2 14831: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14832: when the connection is brought back up
1.191 harris41 14833:
1.394 bowersj2 14834: =item * B<con_failed>: unable to contact remote host and unable to save message
14835: for later delivery
1.191 harris41 14836:
1.967 bisitz 14837: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14838:
1.394 bowersj2 14839: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14840: that was requested
1.191 harris41 14841:
1.243 albertel 14842: =back
1.191 harris41 14843:
1.243 albertel 14844: =head1 PUBLIC SUBROUTINES
1.191 harris41 14845:
1.243 albertel 14846: =head2 Session Environment Functions
1.191 harris41 14847:
1.243 albertel 14848: =over 4
1.191 harris41 14849:
1.394 bowersj2 14850: =item *
14851: X<appenv()>
1.949 raeburn 14852: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14853: the user envirnoment file, and will be restored for each access this
1.620 albertel 14854: user makes during this session, also modifies the %env for the current
1.949 raeburn 14855: process. Optional rolesarrayref - if defined contains a reference to an array
14856: of roles which are exempt from the restriction on modifying user.role entries
14857: in the user's environment.db and in %env.
1.191 harris41 14858:
14859: =item *
1.394 bowersj2 14860: X<delenv()>
1.987 raeburn 14861: B<delenv($delthis,$regexp)>: removes all items from the session
14862: environment file that begin with $delthis. If the
14863: optional second arg - $regexp - is true, $delthis is treated as a
14864: regular expression, otherwise \Q$delthis\E is used.
14865: The values are also deleted from the current processes %env.
1.191 harris41 14866:
1.795 albertel 14867: =item * get_env_multiple($name)
14868:
14869: gets $name from the %env hash, it seemlessly handles the cases where multiple
14870: values may be defined and end up as an array ref.
14871:
14872: returns an array of values
14873:
1.243 albertel 14874: =back
14875:
14876: =head2 User Information
1.191 harris41 14877:
1.243 albertel 14878: =over 4
1.191 harris41 14879:
14880: =item *
1.394 bowersj2 14881: X<queryauthenticate()>
14882: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14883: authentication scheme
14884:
14885: =item *
1.394 bowersj2 14886: X<authenticate()>
1.1073 raeburn 14887: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14888: authenticate user from domain's lib servers (first use the current
14889: one). C<$upass> should be the users password.
1.1073 raeburn 14890: $checkdefauth is optional (value is 1 if a check should be made to
14891: authenticate user using default authentication method, and allow
14892: account creation if username does not have account in the domain).
14893: $clientcancheckhost is optional (value is 1 if checking whether the
14894: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14895:
14896: =item *
1.394 bowersj2 14897: X<homeserver()>
14898: B<homeserver($uname,$udom)>: find the server which has
14899: the user's directory and files (there must be only one), this caches
14900: the answer, and also caches if there is a borken connection.
1.191 harris41 14901:
14902: =item *
1.394 bowersj2 14903: X<idget()>
14904: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14905: (IDs are a unique resource in a domain, there must be only 1 ID per
14906: username, and only 1 username per ID in a specific domain) (returns
14907: hash: id=>name,id=>name)
1.191 harris41 14908:
14909: =item *
1.394 bowersj2 14910: X<idrget()>
14911: B<idrget($udom,@unames)>: find the IDs behind a list of
14912: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14913:
14914: =item *
1.394 bowersj2 14915: X<idput()>
14916: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14917:
14918: =item *
1.394 bowersj2 14919: X<rolesinit()>
1.1169 droeschl 14920: B<rolesinit($udom,$username)>: get user privileges.
14921: returns user role, first access and timer interval hashes
1.243 albertel 14922:
14923: =item *
1.1171 droeschl 14924: X<privileged()>
14925: B<privileged($username,$domain)>: returns a true if user has a
14926: privileged and active role (i.e. su or dc), false otherwise.
14927:
14928: =item *
1.551 albertel 14929: X<getsection()>
14930: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14931: course $cname, return section name/number or '' for "not in course"
14932: and '-1' for "no section"
14933:
14934: =item *
1.394 bowersj2 14935: X<userenvironment()>
14936: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14937: passed in @what from the requested user's environment, returns a hash
14938:
1.858 raeburn 14939: =item *
14940: X<userlog_query()>
1.859 albertel 14941: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14942: activity.log file. %filters defines filters applied when parsing the
14943: log file. These can be start or end timestamps, or the type of action
14944: - log to look for Login or Logout events, check for Checkin or
14945: Checkout, role for role selection. The response is in the form
14946: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14947: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14948:
1.243 albertel 14949: =back
14950:
14951: =head2 User Roles
14952:
14953: =over 4
14954:
14955: =item *
14956:
1.1172.2.65 raeburn 14957: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14958: returns codes for allowed actions.
14959:
14960: The first argument is required, all others are optional.
14961:
14962: $priv is the privilege being checked.
14963: $uri contains additional information about what is being checked for access (e.g.,
14964: URL, course ID etc.).
14965: $symb is the unique resource instance identifier in a course; if needed,
14966: but not provided, it will be retrieved via a call to &symbread().
14967: $role is the role for which a priv is being checked (only used if priv is evb).
14968: $clientip is the user's IP address (only used when checking for access to portfolio
14969: files).
14970: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14971: prevents recursive calls to &allowed.
14972:
1.243 albertel 14973: F: full access
14974: U,I,K: authentication modes (cxx only)
14975: '': forbidden
14976: 1: user needs to choose course
14977: 2: browse allowed
1.766 albertel 14978: A: passphrase authentication needed
1.1172.2.65 raeburn 14979: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14980:
14981: =item *
14982:
1.1172.2.13 raeburn 14983: constructaccess($url,$setpriv) : check for access to construction space URL
14984:
14985: See if the owner domain and name in the URL match those in the
14986: expected environment. If so, return three element list
14987: ($ownername,$ownerdomain,$ownerhome).
14988:
14989: Otherwise return the null string.
14990:
14991: If second argument 'setpriv' is true, it assigns the privileges,
14992: and returns the same three element list, unless the owner has
14993: blocked "ad hoc" Domain Coordinator access to the Author Space,
14994: in which case the null string is returned.
14995:
14996: =item *
14997:
1.1172.2.84 raeburn 14998: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14999: define a custom role rolename set privileges in format of lonTabs/roles.tab
15000: for system, domain, and course level. $uname and $udom are optional (current
15001: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15002:
15003: =item *
15004:
1.988 raeburn 15005: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15006: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15007: $type is Course (default) or Community.
1.988 raeburn 15008: If $forcedefault evaluates to true, text returned will be default
15009: text for $type. Otherwise, if this is a course, the text returned
15010: will be a custom name for the role (if defined in the course's
15011: environment). If no custom name is defined the default is returned.
15012:
1.832 raeburn 15013: =item *
15014:
1.1172.2.23 raeburn 15015: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15016: All arguments are optional. Returns a hash of a roles, either for
15017: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15018: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15019: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15020: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15021: For each key, value is set to colon-separated start and end times for
15022: the role. If no username and domain are specified, will default to
1.934 raeburn 15023: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15024: of role statuses (active, future or previous), roles
15025: (e.g., cc,in, st etc.) and domains of the roles which can be used
15026: to restrict the list of roles reported. If no array ref is
15027: provided for types, will default to return only active roles.
1.834 albertel 15028:
1.1172.2.13 raeburn 15029: =item *
15030:
15031: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15032: user: $uname:$udom has a role in the course: $cdom_$cnum.
15033:
15034: Additional optional arguments are: $type (if role checking is to be restricted
15035: to certain user status types -- previous (expired roles), active (currently
15036: available roles) or future (roles available in the future), and
15037: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15038: have active Domain Coordinator role in course's domain or in additional
15039: domains (specified in 'Domains to check for privileged users' in course
15040: environment -- set via: Course Settings -> Classlists and staff listing).
15041:
15042: =item *
15043:
15044: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15045: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15046: $possdomains and $possroles are optional array refs -- to domains to check and
15047: roles to check. If $possdomains is not specified, a dump will be done of the
15048: users' roles.db to check for a dc or su role in any domain. This can be
15049: time consuming if &privileged is called repeatedly (e.g., when displaying a
15050: classlist), so in such cases, supplying a $possdomains array is preferred, as
15051: this then allows &privileged_by_domain() to be used, which caches the identity
15052: of privileged users, eliminating the need for repeated calls to &dump().
15053:
15054: =item *
15055:
15056: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15057: where the outer hash keys are domains specified in the $possdomains array ref,
15058: next inner hash keys are privileged roles specified in the $roles array ref,
15059: and the innermost hash contains key = value pairs for username:domain = end:start
15060: for active or future "privileged" users with that role in that domain. To avoid
15061: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15062: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15063:
1.243 albertel 15064: =back
15065:
15066: =head2 User Modification
15067:
15068: =over 4
15069:
15070: =item *
15071:
1.957 raeburn 15072: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15073: user for the level given by URL. Optional start and end dates (leave empty
15074: string or zero for "no date")
1.191 harris41 15075:
15076: =item *
15077:
1.243 albertel 15078: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15079: change a users, password, possible return values are: ok,
15080: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15081: refused
1.191 harris41 15082:
15083: =item *
15084:
1.243 albertel 15085: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15086:
15087: =item *
15088:
1.1058 raeburn 15089: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15090: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15091:
15092: will update user information (firstname,middlename,lastname,generation,
15093: permanentemail), and if forceid is true, student/employee ID also.
15094: A user's institutional affiliation(s) can also be updated.
15095: User information fields will not be overwritten with empty entries
15096: unless the field is included in the $candelete array reference.
15097: This array is included when a single user is modified via "Manage Users",
15098: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15099:
15100: =item *
15101:
1.286 matthew 15102: modifystudent
15103:
1.957 raeburn 15104: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15105: The course id is resolved based on the current user's environment.
15106: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15107: associated with a course.
15108:
1.297 matthew 15109: This call is essentially a wrapper for lonnet::modifyuser and
15110: lonnet::modify_student_enrollment
1.286 matthew 15111:
15112: Inputs:
15113:
15114: =over 4
15115:
1.957 raeburn 15116: =item B<$udom> Student's loncapa domain
1.286 matthew 15117:
1.957 raeburn 15118: =item B<$uname> Student's loncapa login name
1.286 matthew 15119:
1.964 bisitz 15120: =item B<$uid> Student/Employee ID
1.286 matthew 15121:
1.957 raeburn 15122: =item B<$umode> Student's authentication mode
1.286 matthew 15123:
1.957 raeburn 15124: =item B<$upass> Student's password
1.286 matthew 15125:
1.957 raeburn 15126: =item B<$first> Student's first name
1.286 matthew 15127:
1.957 raeburn 15128: =item B<$middle> Student's middle name
1.286 matthew 15129:
1.957 raeburn 15130: =item B<$last> Student's last name
1.286 matthew 15131:
1.957 raeburn 15132: =item B<$gene> Student's generation
1.286 matthew 15133:
1.957 raeburn 15134: =item B<$usec> Student's section in course
1.286 matthew 15135:
15136: =item B<$end> Unix time of the roles expiration
15137:
15138: =item B<$start> Unix time of the roles start date
15139:
15140: =item B<$forceid> If defined, allow $uid to be changed
15141:
15142: =item B<$desiredhome> server to use as home server for student
15143:
1.957 raeburn 15144: =item B<$email> Student's permanent e-mail address
15145:
15146: =item B<$type> Type of enrollment (auto or manual)
15147:
1.963 raeburn 15148: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15149:
15150: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15151:
1.963 raeburn 15152: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15153:
1.963 raeburn 15154: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15155:
1.1172.2.19 raeburn 15156: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15157:
15158: =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 15159:
1.286 matthew 15160: =back
1.297 matthew 15161:
15162: =item *
15163:
15164: modify_student_enrollment
15165:
1.1172.2.31 raeburn 15166: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15167: 'role.request.course' must be defined for this function to proceed.
15168:
15169: Inputs:
15170:
15171: =over 4
15172:
1.1172.2.31 raeburn 15173: =item $udom, student's domain
1.297 matthew 15174:
1.1172.2.31 raeburn 15175: =item $uname, student's name
1.297 matthew 15176:
1.1172.2.31 raeburn 15177: =item $uid, student's user id
1.297 matthew 15178:
1.1172.2.31 raeburn 15179: =item $first, student's first name
1.297 matthew 15180:
15181: =item $middle
15182:
15183: =item $last
15184:
15185: =item $gene
15186:
15187: =item $usec
15188:
15189: =item $end
15190:
15191: =item $start
15192:
1.957 raeburn 15193: =item $type
15194:
15195: =item $locktype
15196:
15197: =item $cid
15198:
15199: =item $selfenroll
15200:
15201: =item $context
15202:
1.1172.2.19 raeburn 15203: =item $credits, number of credits student will earn from this class
15204:
1.1172.2.76 raeburn 15205: =item $instsec, institutional course section code for student
15206:
1.297 matthew 15207: =back
15208:
1.191 harris41 15209:
15210: =item *
15211:
1.243 albertel 15212: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15213: custom role; give a custom role to a user for the level given by URL. Specify
15214: name and domain of role author, and role name
1.191 harris41 15215:
15216: =item *
15217:
1.243 albertel 15218: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15219:
15220: =item *
15221:
1.243 albertel 15222: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15223:
15224: =back
15225:
15226: =head2 Course Infomation
15227:
15228: =over 4
1.191 harris41 15229:
15230: =item *
15231:
1.1118 foxr 15232: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15233: specified course id, including all environment settings for the
15234: course, the description of the course will be in the hash under the
15235: key 'description'
1.191 harris41 15236:
1.1118 foxr 15237: $options is an optional parameter that if supplied is a hash reference that controls
15238: what how this function works. It has the following key/values:
15239:
15240: =over 4
15241:
15242: =item freshen_cache
15243:
15244: If defined, and the environment cache for the course is valid, it is
15245: returned in the returned hash.
15246:
15247: =item one_time
15248:
15249: If defined, the last cache time is set to _now_
15250:
15251: =item user
15252:
15253: If defined, the supplied username is used instead of the current user.
15254:
15255:
15256: =back
15257:
1.191 harris41 15258: =item *
15259:
1.624 albertel 15260: resdata($name,$domain,$type,@which) : request for current parameter
15261: setting for a specific $type, where $type is either 'course' or 'user',
15262: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15263: answers for 10 minutes.
1.243 albertel 15264:
1.877 foxr 15265: =item *
15266:
15267: get_courseresdata($courseid, $domain) : dump the entire course resource
15268: data base, returning a hash that is keyed by the resource name and has
15269: values that are the resource value. I believe that the timestamps and
15270: versions are also returned.
15271:
1.1172.2.31 raeburn 15272: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15273: supplemental content area. This routine caches the number of files for
15274: 10 minutes.
15275:
1.243 albertel 15276: =back
15277:
15278: =head2 Course Modification
15279:
15280: =over 4
1.191 harris41 15281:
15282: =item *
15283:
1.243 albertel 15284: writecoursepref($courseid,%prefs) : write preferences (environment
15285: database) for a course
1.191 harris41 15286:
15287: =item *
15288:
1.1011 raeburn 15289: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15290:
15291: =item *
15292:
1.1038 raeburn 15293: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15294:
1.1167 droeschl 15295: =item *
15296:
15297: is_course($courseid), is_course($cdom, $cnum)
15298:
15299: Accepts either a combined $courseid (in the form of domain_courseid) or the
15300: two component version $cdom, $cnum. It checks if the specified course exists.
15301:
15302: Returns:
15303: undef if the course doesn't exist, otherwise
15304: in scalar context the combined courseid.
15305: in list context the two components of the course identifier, domain and
15306: courseid.
15307:
1.243 albertel 15308: =back
15309:
1.1172.2.109 raeburn 15310: =head2 Bubblesheet Configuration
15311:
15312: =over 4
15313:
15314: =item *
15315:
15316: get_scantron_config($which)
15317:
15318: $which - the name of the configuration to parse from the file.
15319:
15320: Parses and returns the bubblesheet configuration line selected as a
15321: hash of configuration file fields.
15322:
15323:
15324: Returns:
15325: If the named configuration is not in the file, an empty
15326: hash is returned.
15327:
15328: a hash with the fields
15329: name - internal name for the this configuration setup
15330: description - text to display to operator that describes this config
15331: CODElocation - if 0 or the string 'none'
15332: - no CODE exists for this config
15333: if -1 || the string 'letter'
15334: - a CODE exists for this config and is
15335: a string of letters
15336: Unsupported value (but planned for future support)
15337: if a positive integer
15338: - The CODE exists as the first n items from
15339: the question section of the form
15340: if the string 'number'
15341: - The CODE exists for this config and is
15342: a string of numbers
15343: CODEstart - (only matter if a CODE exists) column in the line where
15344: the CODE starts
15345: CODElength - length of the CODE
15346: IDstart - column where the student/employee ID starts
15347: IDlength - length of the student/employee ID info
15348: Qstart - column where the information from the bubbled
15349: 'questions' start
15350: Qlength - number of columns comprising a single bubble line from
15351: the sheet. (usually either 1 or 10)
15352: Qon - either a single character representing the character used
15353: to signal a bubble was chosen in the positional setup, or
15354: the string 'letter' if the letter of the chosen bubble is
15355: in the final, or 'number' if a number representing the
15356: chosen bubble is in the file (1->A 0->J)
15357: Qoff - the character used to represent that a bubble was
15358: left blank
15359: PaperID - if the scanning process generates a unique number for each
15360: sheet scanned the column that this ID number starts in
15361: PaperIDlength - number of columns that comprise the unique ID number
15362: for the sheet of paper
15363: FirstName - column that the first name starts in
15364: FirstNameLength - number of columns that the first name spans
15365: LastName - column that the last name starts in
15366: LastNameLength - number of columns that the last name spans
15367: BubblesPerRow - number of bubbles available in each row used to
15368: bubble an answer. (If not specified, 10 assumed).
15369:
15370:
15371: =item *
15372:
15373: get_scantronformat_file($cdom)
15374:
15375: $cdom - the course's domain (optional); if not supplied, uses
15376: domain for current $env{'request.course.id'}.
15377:
15378: Returns an array containing lines from the scantron format file for
15379: the domain of the course.
15380:
15381: If a url for a custom.tab file is listed in domain's configuration.db,
15382: lines are from this file.
15383:
15384: Otherwise, if a default.tab has been published in RES space by the
15385: domainconfig user, lines are from this file.
15386:
15387: Otherwise, fall back to getting lines from the legacy file on the
15388: local server: /home/httpd/lonTabs/default_scantronformat.tab
15389:
15390: =back
15391:
1.243 albertel 15392: =head2 Resource Subroutines
15393:
15394: =over 4
1.191 harris41 15395:
15396: =item *
15397:
1.243 albertel 15398: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15399:
15400: =item *
15401:
1.243 albertel 15402: repcopy($filename) : subscribes to the requested file, and attempts to
15403: replicate from the owning library server, Might return
1.607 raeburn 15404: 'unavailable', 'not_found', 'forbidden', 'ok', or
15405: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15406: resource. Expects the local filesystem pathname
15407: (/home/httpd/html/res/....)
15408:
15409: =back
15410:
15411: =head2 Resource Information
15412:
15413: =over 4
1.191 harris41 15414:
15415: =item *
15416:
1.1172.2.28 raeburn 15417: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15418: and returns the value of a variety of different possible values,
15419: $varname should be a request string, and the other parameters can be
15420: used to specify who and what one is asking about. Ordinarily, $cid
15421: does not need to be specified, as it is retrived from
15422: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15423: within lonuserstate::loadmap() when initializing a course, before
15424: $env{'request.course.id'} has been set, so it needs to be provided
15425: in that one case.
1.243 albertel 15426:
15427: Possible values for $varname are environment.lastname (or other item
15428: from the envirnment hash), user.name (or someother aspect about the
15429: user), resource.0.maxtries (or some other part and parameter of a
15430: resource)
1.204 albertel 15431:
15432: =item *
15433:
1.243 albertel 15434: directcondval($number) : get current value of a condition; reads from a state
15435: string
1.204 albertel 15436:
15437: =item *
15438:
1.243 albertel 15439: condval($condidx) : value of condition index based on state
1.204 albertel 15440:
15441: =item *
15442:
1.243 albertel 15443: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15444: resource's metadata, $what should be either a specific key, or either
15445: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15446: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15447:
15448: this function automatically caches all requests
1.191 harris41 15449:
15450: =item *
15451:
1.243 albertel 15452: metadata_query($query,$custom,$customshow) : make a metadata query against the
15453: network of library servers; returns file handle of where SQL and regex results
15454: will be stored for query
1.191 harris41 15455:
15456: =item *
15457:
1.1172.2.66 raeburn 15458: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15459: return symbolic list entry (all arguments optional).
15460:
15461: Args: filename is the filename (including path) for the file for which a symb
15462: is required; donotrecurse, if true will prevent calls to allowed() being made
15463: to check access status if more than one resource was found in the bighash
15464: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15465: a randompick); ignorecachednull, if true will prevent a symb of '' being
15466: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15467: cause possible symbs to be checked to determine if they are subject to content
15468: blocking, if so they will not be included as possible symbs; possibles is a
15469: ref to a hash, which, as a side effect, will be populated with all possible
15470: symbs (content blocking not tested).
15471:
1.243 albertel 15472: returns the data handle
1.191 harris41 15473:
15474: =item *
15475:
1.1172.2.17 raeburn 15476: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15477: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15478: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15479: on failure, user must be in a course, as it assumes the existence of
15480: the course initial hash, and uses $env('request.course.id'}. The third
15481: arg is an optional reference to a scalar. If this arg is passed in the
15482: call to symbverify, it will be set to 1 if the symb has been set to be
15483: encrypted; otherwise it will be null.
1.243 albertel 15484:
1.191 harris41 15485: =item *
15486:
1.243 albertel 15487: symbclean($symb) : removes versions numbers from a symb, returns the
15488: cleaned symb
1.191 harris41 15489:
15490: =item *
15491:
1.243 albertel 15492: is_on_map($uri) : checks if the $uri is somewhere on the current
15493: course map, user must be in a course for it to work.
1.191 harris41 15494:
15495: =item *
15496:
1.243 albertel 15497: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15498:
15499: =item *
15500:
1.243 albertel 15501: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15502: a random seed, all arguments are optional, if they aren't sent it uses the
15503: environment to derive them. Note: if symb isn't sent and it can't get one
15504: from &symbread it will use the current time as its return value
1.191 harris41 15505:
15506: =item *
15507:
1.243 albertel 15508: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15509: unfakeable, receipt
1.191 harris41 15510:
15511: =item *
15512:
1.620 albertel 15513: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15514:
15515: =item *
15516:
1.243 albertel 15517: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15518:
15519: =item *
15520:
1.243 albertel 15521: 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 15522:
15523: =item *
15524:
1.243 albertel 15525: 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 15526:
15527: =item *
15528:
1.243 albertel 15529: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15530:
15531: =item *
15532:
1.243 albertel 15533: devalidate($symb) : devalidate temporary spreadsheet calculations,
15534: forcing spreadsheet to reevaluate the resource scores next time.
15535:
1.1172.2.13 raeburn 15536: =item *
15537:
15538: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15539: when viewing in course context.
15540:
15541: input: six args -- filename (decluttered), course number, course domain,
15542: url, symb (if registered) and group (if this is a
15543: group item -- e.g., bulletin board, group page etc.).
15544:
15545: output: array of five scalars --
15546: $cfile -- url for file editing if editable on current server
15547: $home -- homeserver of resource (i.e., for author if published,
15548: or course if uploaded.).
15549: $switchserver -- 1 if server switch will be needed.
15550: $forceedit -- 1 if icon/link should be to go to edit mode
15551: $forceview -- 1 if icon/link should be to go to view mode
15552:
15553: =item *
15554:
15555: is_course_upload($file,$cnum,$cdom)
15556:
15557: Used in course context to determine if current file was uploaded to
15558: the course (i.e., would be found in /userfiles/docs on the course's
15559: homeserver.
15560:
15561: input: 3 args -- filename (decluttered), course number and course domain.
15562: output: boolean -- 1 if file was uploaded.
15563:
1.243 albertel 15564: =back
15565:
15566: =head2 Storing/Retreiving Data
15567:
15568: =over 4
1.191 harris41 15569:
15570: =item *
15571:
1.1172.2.64 raeburn 15572: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15573: permanently for this url; hashref needs to be given and should be a \%hashname;
15574: the remaining args aren't required and if they aren't passed or are '' they will
15575: be derived from the env (with the exception of $laststore, which is an
15576: optional arg used when a user's submission is stored in grading).
15577: $laststore is $version=$timestamp, where $version is the most recent version
15578: number retrieved for the corresponding $symb in the $namespace db file, and
15579: $timestamp is the timestamp for that transaction (UNIX time).
15580: $laststore is currently only passed when cstore() is called by
15581: structuretags::finalize_storage().
1.191 harris41 15582:
15583: =item *
15584:
1.1172.2.64 raeburn 15585: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15586: but uses critical subroutine
1.191 harris41 15587:
15588: =item *
15589:
1.243 albertel 15590: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15591: all args are optional
1.191 harris41 15592:
15593: =item *
15594:
1.717 albertel 15595: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15596: dumps the complete (or key matching regexp) namespace into a hash
15597: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15598: normally &store()ed into
15599:
15600: $range should be either an integer '100' (give me the first 100
15601: matching records)
15602: or be two integers sperated by a - with no spaces
15603: '30-50' (give me the 30th through the 50th matching
15604: records)
15605:
15606:
15607: =item *
15608:
1.1172.2.59 raeburn 15609: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15610: replaces a &store() version of data with a replacement set of data
15611: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15612: reference. If $tolog is true, the transaction is logged in the courselog
15613: with an action=PUTSTORE.
1.717 albertel 15614:
15615: =item *
15616:
1.243 albertel 15617: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15618: works very similar to store/cstore, but all data is stored in a
15619: temporary location and can be reset using tmpreset, $storehash should
15620: be a hash reference, returns nothing on success
1.191 harris41 15621:
15622: =item *
15623:
1.243 albertel 15624: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15625: similar to restore, but all data is stored in a temporary location and
15626: can be reset using tmpreset. Returns a hash of values on success,
15627: error string otherwise.
1.191 harris41 15628:
15629: =item *
15630:
1.243 albertel 15631: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15632: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15633:
15634: =item *
15635:
1.243 albertel 15636: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15637: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15638:
15639: =item *
15640:
1.243 albertel 15641: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15642: namesp ($udom and $uname are optional)
1.191 harris41 15643:
15644: =item *
15645:
1.702 albertel 15646: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15647: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15648: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15649:
1.702 albertel 15650: $range should be either an integer '100' (give me the first 100
15651: matching records)
15652: or be two integers sperated by a - with no spaces
15653: '30-50' (give me the 30th through the 50th matching
15654: records)
1.449 matthew 15655: =item *
15656:
15657: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15658: $store can be a scalar, an array reference, or if the amount to be
15659: incremented is > 1, a hash reference.
15660:
15661: ($udom and $uname are optional)
1.191 harris41 15662:
15663: =item *
15664:
1.243 albertel 15665: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15666: ($udom and $uname are optional)
1.191 harris41 15667:
15668: =item *
15669:
1.243 albertel 15670: cput($namespace,$storehash,$udom,$uname) : critical put
15671: ($udom and $uname are optional)
1.191 harris41 15672:
15673: =item *
15674:
1.748 albertel 15675: newput($namespace,$storehash,$udom,$uname) :
15676:
15677: Attempts to store the items in the $storehash, but only if they don't
15678: currently exist, if this succeeds you can be certain that you have
15679: successfully created a new key value pair in the $namespace db.
15680:
15681:
15682: Args:
15683: $namespace: name of database to store values to
15684: $storehash: hashref to store to the db
15685: $udom: (optional) domain of user containing the db
15686: $uname: (optional) name of user caontaining the db
15687:
15688: Returns:
15689: 'ok' -> succeeded in storing all keys of $storehash
15690: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15691: least <key> already existed in the db (other
15692: requested keys may also already exist)
1.967 bisitz 15693: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15694: 'con_lost' -> unable to contact request server
15695: 'refused' -> action was not allowed by remote machine
15696:
15697:
15698: =item *
15699:
1.243 albertel 15700: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15701: reference filled in from namesp (encrypts the return communication)
15702: ($udom and $uname are optional)
1.191 harris41 15703:
15704: =item *
15705:
1.243 albertel 15706: log($udom,$name,$home,$message) : write to permanent log for user; use
15707: critical subroutine
15708:
1.806 raeburn 15709: =item *
15710:
1.860 raeburn 15711: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15712: array reference filled in from namespace found in domain level on either
15713: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15714:
15715: =item *
15716:
1.860 raeburn 15717: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15718: domain level either on specified domain server ($uhome) or primary domain
15719: server ($udom and $uhome are optional)
1.806 raeburn 15720:
1.943 raeburn 15721: =item *
15722:
1.1172.2.35 raeburn 15723: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15724: for: authentication, language, quotas, timezone, date locale, and portal URL in
15725: the target domain.
15726:
15727: May also include additional key => value pairs for the following groups:
15728:
15729: =over
15730:
15731: =item
15732: disk quotas (MB allocated by default to portfolios and authoring spaces).
15733:
15734: =over
15735:
15736: =item defaultquota, authorquota
15737:
15738: =back
15739:
15740: =item
15741: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15742: portfolio for users).
15743:
15744: =over
15745:
15746: =item
15747: aboutme, blog, webdav, portfolio
15748:
15749: =back
15750:
15751: =item
15752: requestcourses: ability to request courses, and how requests are processed.
15753:
15754: =over
15755:
15756: =item
1.1172.2.37 raeburn 15757: official, unofficial, community, textbook
1.1172.2.35 raeburn 15758:
15759: =back
15760:
15761: =item
15762: inststatus: types of institutional affiliation, and order in which they are displayed.
15763:
15764: =over
15765:
15766: =item
1.1172.2.44 raeburn 15767: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15768:
15769: =back
15770:
15771: =item
15772: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15773: for course's uploaded content.
15774:
15775: =over
15776:
15777: =item
1.1172.2.68 raeburn 15778: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15779: communityquota, textbookquota
1.1172.2.35 raeburn 15780:
15781: =back
15782:
15783: =item
15784: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15785: on your servers.
15786:
15787: =over
15788:
15789: =item
15790: remotesessions, hostedsessions
15791:
15792: =back
15793:
15794: =back
15795:
15796: In cases where a domain coordinator has never used the "Set Domain Configuration"
15797: utility to create a configuration.db file on a domain's primary library server
15798: only the following domain defaults: auth_def, auth_arg_def, lang_def
15799: -- corresponding values are authentication type (internal, krb4, krb5,
15800: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15801: will be available. Values are retrieved from cache (if current), unless the
15802: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15803: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15804:
15805: Typical usage:
1.943 raeburn 15806:
1.1172.2.35 raeburn 15807: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15808:
1.243 albertel 15809: =back
15810:
15811: =head2 Network Status Functions
15812:
15813: =over 4
1.191 harris41 15814:
15815: =item *
15816:
1.1137 raeburn 15817: dirlist() : return directory list based on URI (first arg).
15818:
15819: Inputs: 1 required, 5 optional.
15820:
15821: =over
15822:
15823: =item
15824: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15825:
15826: =item
15827: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15828:
15829: =item
15830: $username - username of user/course to be listed. Extracted from $uri if absent.
15831:
15832: =item
15833: $getpropath - boolean: 1 if prepend path using &propath().
15834:
15835: =item
15836: $getuserdir - boolean: 1 if prepend path for "userfiles".
15837:
15838: =item
15839: $alternateRoot - path to prepend in place of path from $uri.
15840:
15841: =back
15842:
15843: Returns: Array of up to two items.
15844:
15845: =over
15846:
15847: a reference to an array of files/subdirectories
15848:
15849: =over
15850:
15851: Each element in the array of files/subdirectories is a & separated list of
15852: item name and the result of running stat on the item. If dirlist was requested
15853: for a file instead of a directory, the item name will be ''. For a directory
15854: listing, if the item is a metadata file, the element will end &N&M
15855: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15856: default copyright set (1).
15857:
15858: =back
15859:
15860: a scalar containing error condition (if encountered).
15861:
15862: =over
15863:
15864: =item
15865: no_host (no homeserver identified for $username:$domain).
15866:
15867: =item
15868: no_such_host (server contacted for listing not identified as valid host).
15869:
15870: =item
15871: con_lost (connection to remote server failed).
15872:
15873: =item
15874: refused (invalid $username:$domain received on lond side).
15875:
15876: =item
15877: no_such_dir (directory at specified path on lond side does not exist).
15878:
15879: =item
15880: empty (directory at specified path on lond side is empty).
15881:
15882: =over
15883:
15884: This is currently not encountered because the &ls3, &ls2,
15885: &ls (_handler) routines on the lond side do not filter out
15886: . and .. from a directory listing.
15887:
15888: =back
15889:
15890: =back
15891:
15892: =back
1.191 harris41 15893:
15894: =item *
15895:
1.243 albertel 15896: spareserver() : find server with least workload from spare.tab
15897:
1.986 foxr 15898:
15899: =item *
15900:
15901: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15902: if there is no corresponding loncapa host.
15903:
1.243 albertel 15904: =back
15905:
1.986 foxr 15906:
1.243 albertel 15907: =head2 Apache Request
15908:
15909: =over 4
1.191 harris41 15910:
15911: =item *
15912:
1.243 albertel 15913: ssi($url,%hash) : server side include, does a complete request cycle on url to
15914: localhost, posts hash
15915:
15916: =back
15917:
15918: =head2 Data to String to Data
15919:
15920: =over 4
1.191 harris41 15921:
15922: =item *
15923:
1.243 albertel 15924: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15925: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15926:
15927: =item *
15928:
1.243 albertel 15929: hashref2str($hashref) : convert a hashref into a string complete with
15930: escaping and '=' and '&' separators, supports elements that are
15931: arrayrefs and hashrefs
1.191 harris41 15932:
15933: =item *
15934:
1.243 albertel 15935: arrayref2str($arrayref) : convert an arrayref into a string complete
15936: with escaping and '&' separators, supports elements that are arrayrefs
15937: and hashrefs
1.191 harris41 15938:
15939: =item *
15940:
1.243 albertel 15941: str2hash($string) : convert string to hash using unescaping and
15942: splitting on '=' and '&', supports elements that are arrayrefs and
15943: hashrefs
1.191 harris41 15944:
15945: =item *
15946:
1.243 albertel 15947: str2array($string) : convert string to hash using unescaping and
15948: splitting on '&', supports elements that are arrayrefs and hashrefs
15949:
15950: =back
15951:
15952: =head2 Logging Routines
15953:
15954:
15955: These routines allow one to make log messages in the lonnet.log and
15956: lonnet.perm logfiles.
1.191 harris41 15957:
1.1119 foxr 15958: =over 4
15959:
1.191 harris41 15960: =item *
15961:
1.243 albertel 15962: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15963:
15964: =item *
15965:
1.243 albertel 15966: logthis() : append message to the normal lonnet.log file, it gets
15967: preiodically rolled over and deleted.
1.191 harris41 15968:
15969: =item *
15970:
1.243 albertel 15971: logperm() : append a permanent message to lonnet.perm.log, this log
15972: file never gets deleted by any automated portion of the system, only
15973: messages of critical importance should go in here.
15974:
1.1119 foxr 15975:
1.243 albertel 15976: =back
15977:
15978: =head2 General File Helper Routines
15979:
15980: =over 4
1.191 harris41 15981:
15982: =item *
15983:
1.481 raeburn 15984: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15985: (a) files in /uploaded
15986: (i) If a local copy of the file exists -
15987: compares modification date of local copy with last-modified date for
15988: definitive version stored on home server for course. If local copy is
15989: stale, requests a new version from the home server and stores it.
15990: If the original has been removed from the home server, then local copy
15991: is unlinked.
15992: (ii) If local copy does not exist -
15993: requests the file from the home server and stores it.
15994:
15995: If $caller is 'uploadrep':
15996: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15997: for request for files originally uploaded via DOCS.
15998: - returns 'ok' if fresh local copy now available, -1 otherwise.
15999:
16000: Otherwise:
16001: This indicates a call from the content generation phase of the request.
16002: - returns the entire contents of the file or -1.
16003:
16004: (b) files in /res
16005: - returns the entire contents of a file or -1;
16006: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16007:
1.712 albertel 16008:
16009: =item *
16010:
16011: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16012: reference
16013:
16014: returns either a stat() list of data about the file or an empty list
16015: if the file doesn't exist or couldn't find out about it (connection
16016: problems or user unknown)
16017:
1.191 harris41 16018: =item *
16019:
1.243 albertel 16020: filelocation($dir,$file) : returns file system location of a file
16021: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16022: directory that relative $file lookups are to looked in ($dir of /a/dir
16023: and a file of ../bob will become /a/bob)
1.191 harris41 16024:
16025: =item *
16026:
16027: hreflocation($dir,$file) : returns file system location or a URL; same as
16028: filelocation except for hrefs
16029:
16030: =item *
16031:
1.1172.2.49 raeburn 16032: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16033: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16034:
1.243 albertel 16035: =back
16036:
1.608 albertel 16037: =head2 Usererfile file routines (/uploaded*)
16038:
16039: =over 4
16040:
16041: =item *
16042:
16043: userfileupload(): main rotine for putting a file in a user or course's
16044: filespace, arguments are,
16045:
1.620 albertel 16046: formname - required - this is the name of the element in $env where the
1.608 albertel 16047: filename, and the contents of the file to create/modifed exist
1.620 albertel 16048: the filename is in $env{'form.'.$formname.'.filename'} and the
16049: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16050: context - if coursedoc, store the file in the course of the active role
16051: of the current user;
16052: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16053: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16054: subdir - required - subdirectory to put the file in under ../userfiles/
16055: if undefined, it will be placed in "unknown"
16056:
16057: (This routine calls clean_filename() to remove any dangerous
16058: characters from the filename, and then calls finuserfileupload() to
16059: complete the transaction)
16060:
16061: returns either the url of the uploaded file (/uploaded/....) if successful
16062: and /adm/notfound.html if unsuccessful
16063:
16064: =item *
16065:
16066: clean_filename(): routine for cleaing a filename up for storage in
16067: userfile space, argument is:
16068:
16069: filename - proposed filename
16070:
16071: returns: the new clean filename
16072:
16073: =item *
16074:
1.1090 raeburn 16075: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16076: userspace, probably shouldn't be called directly
16077:
16078: docuname: username or courseid of destination for the file
16079: docudom: domain of user/course of destination for the file
16080: formname: same as for userfileupload()
1.1090 raeburn 16081: fname: filename (including subdirectories) for the file
16082: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16083: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16084: allfiles: reference to hash used to store objects found by parser
16085: codebase: reference to hash used for codebases of java objects found by parser
16086: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16087: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16088: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16089: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16090: context: if 'overwrite', will move the uploaded file from its temporary location to
16091: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16092: mimetype: reference to scalar to accommodate mime type determined
16093: from File::MMagic if $parser = parse.
1.608 albertel 16094:
16095: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16096: and /adm/notfound.html if unsuccessful (or an error message if context
16097: was 'overwrite').
16098:
1.608 albertel 16099:
16100: =item *
16101:
16102: renameuserfile(): renames an existing userfile to a new name
16103:
16104: Args:
16105: docuname: username or courseid of destination for the file
16106: docudom: domain of user/course of destination for the file
16107: old: current file name (including any subdirs under userfiles)
16108: new: desired file name (including any subdirs under userfiles)
16109:
16110: =item *
16111:
16112: mkdiruserfile(): creates a directory is a userfiles dir
16113:
16114: Args:
16115: docuname: username or courseid of destination for the file
16116: docudom: domain of user/course of destination for the file
16117: dir: dir to create (including any subdirs under userfiles)
16118:
16119: =item *
16120:
16121: removeuserfile(): removes a file that exists in userfiles
16122:
16123: Args:
16124: docuname: username or courseid of destination for the file
16125: docudom: domain of user/course of destination for the file
16126: fname: filname to delete (including any subdirs under userfiles)
16127:
16128: =item *
16129:
16130: removeuploadedurl(): convience function for removeuserfile()
16131:
16132: Args:
16133: url: a full /uploaded/... url to delete
16134:
1.747 albertel 16135: =item *
16136:
16137: get_portfile_permissions():
16138: Args:
16139: domain: domain of user or course contain the portfolio files
16140: user: name of user or num of course contain the portfolio files
16141: Returns:
16142: hashref of a dump of the proper file_permissions.db
16143:
16144:
16145: =item *
16146:
16147: get_access_controls():
16148:
16149: Args:
16150: current_permissions: the hash ref returned from get_portfile_permissions()
16151: group: (optional) the group you want the files associated with
16152: file: (optional) the file you want access info on
16153:
16154: Returns:
1.749 raeburn 16155: a hash (keys are file names) of hashes containing
16156: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16157: values are XML containing access control settings (see below)
1.747 albertel 16158:
16159: Internal notes:
16160:
1.749 raeburn 16161: access controls are stored in file_permissions.db as key=value pairs.
16162: key -> path to file/file_name\0uniqueID:scope_end_start
16163: where scope -> public,guest,course,group,domains or users.
16164: end -> UNIX time for end of access (0 -> no end date)
16165: start -> UNIX time for start of access
16166:
16167: value -> XML description of access control
16168: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16169: <start></start>
16170: <end></end>
16171:
16172: <password></password> for scope type = guest
16173:
16174: <domain></domain> for scope type = course or group
16175: <number></number>
16176: <roles id="">
16177: <role></role>
16178: <access></access>
16179: <section></section>
16180: <group></group>
16181: </roles>
16182:
16183: <dom></dom> for scope type = domains
16184:
16185: <users> for scope type = users
16186: <user>
16187: <uname></uname>
16188: <udom></udom>
16189: </user>
16190: </users>
16191: </scope>
16192:
16193: Access data is also aggregated for each file in an additional key=value pair:
16194: key -> path to file/file_name\0accesscontrol
16195: value -> reference to hash
16196: hash contains key = value pairs
16197: where key = uniqueID:scope_end_start
16198: value = UNIX time record was last updated
16199:
16200: Used to improve speed of look-ups of access controls for each file.
16201:
16202: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16203:
1.1172.2.13 raeburn 16204: =item *
16205:
1.749 raeburn 16206: modify_access_controls():
16207:
16208: Modifies access controls for a portfolio file
16209: Args
16210: 1. file name
16211: 2. reference to hash of required changes,
16212: 3. domain
16213: 4. username
16214: where domain,username are the domain of the portfolio owner
16215: (either a user or a course)
16216:
16217: Returns:
16218: 1. result of additions or updates ('ok' or 'error', with error message).
16219: 2. result of deletions ('ok' or 'error', with error message).
16220: 3. reference to hash of any new or updated access controls.
16221: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16222: key = integer (inbound ID)
1.1172.2.13 raeburn 16223: value = uniqueID
16224:
16225: =item *
16226:
16227: get_timebased_id():
16228:
16229: Attempts to get a unique timestamp-based suffix for use with items added to a
16230: course via the Course Editor (e.g., folders, composite pages,
16231: group bulletin boards).
16232:
16233: Args: (first three required; six others optional)
16234:
16235: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16236: docssequence, or name of group
16237:
16238: 2. keyid (alphanumeric): name of temporary locking key in hash,
16239: e.g., num, boardids
16240:
16241: 3. namespace: name of gdbm file used to store suffixes already assigned;
16242: file will be named nohist_namespace.db
16243:
16244: 4. cdom: domain of course; default is current course domain from %env
16245:
16246: 5. cnum: course number; default is current course number from %env
16247:
16248: 6. idtype: set to concat if an additional digit is to be appended to the
16249: unix timestamp to form the suffix, if the plain timestamp is already
16250: in use. Default is to not do this, but simply increment the unix
16251: timestamp by 1 until a unique key is obtained.
16252:
16253: 7. who: holder of locking key; defaults to user:domain for user.
16254:
16255: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16256: retrying); default is 3.
16257:
16258: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16259:
16260: Returns:
16261:
16262: 1. suffix obtained (numeric)
16263:
16264: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16265:
16266: 3. error: contains (localized) error message if an error occurred.
16267:
1.747 albertel 16268:
1.608 albertel 16269: =back
16270:
1.243 albertel 16271: =head2 HTTP Helper Routines
16272:
16273: =over 4
16274:
1.191 harris41 16275: =item *
16276:
16277: escape() : unpack non-word characters into CGI-compatible hex codes
16278:
16279: =item *
16280:
16281: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16282:
1.243 albertel 16283: =back
16284:
16285: =head1 PRIVATE SUBROUTINES
16286:
16287: =head2 Underlying communication routines (Shouldn't call)
16288:
16289: =over 4
16290:
16291: =item *
16292:
16293: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16294:
16295: =item *
16296:
16297: reply() : uses subreply to send a message to remote machine, logs all failures
16298:
16299: =item *
16300:
16301: critical() : passes a critical message to another server; if cannot
16302: get through then place message in connection buffer directory and
16303: returns con_delayed, if incapable of saving message, returns
16304: con_failed
16305:
16306: =item *
16307:
16308: reconlonc() : tries to reconnect lonc client processes.
16309:
16310: =back
16311:
16312: =head2 Resource Access Logging
16313:
16314: =over 4
16315:
16316: =item *
16317:
16318: flushcourselogs() : flush (save) buffer logs and access logs
16319:
16320: =item *
16321:
16322: courselog($what) : save message for course in hash
16323:
16324: =item *
16325:
16326: courseacclog($what) : save message for course using &courselog(). Perform
16327: special processing for specific resource types (problems, exams, quizzes, etc).
16328:
1.191 harris41 16329: =item *
16330:
16331: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16332: as a PerlChildExitHandler
1.243 albertel 16333:
16334: =back
16335:
16336: =head2 Other
16337:
16338: =over 4
16339:
16340: =item *
16341:
16342: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16343:
16344: =back
16345:
16346: =cut
1.877 foxr 16347:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>