Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.151
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.151! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.150 2024/07/03 19:07:47 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 = {
1.1172.2.151! raeburn 2568: totcodes => $totcodes,
1.1172.2.106 raeburn 2569: codes => \%codes,
2570: codetitles => \@codetitles,
2571: cat_titles => \%cat_titles,
2572: cat_order => \%cat_order,
2573: };
2574: &do_cache_new('instcats',$dom,$instcats,3600);
2575: }
2576: }
2577: }
2578: return $instcats;
2579: }
2580:
2581: sub retrieve_instcodes {
2582: my ($coursecodes,$dom) = @_;
2583: my $totcodes;
2584: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2585: foreach my $course (keys(%courses)) {
2586: if (ref($courses{$course}) eq 'HASH') {
2587: if ($courses{$course}{'inst_code'} ne '') {
2588: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2589: $totcodes ++;
2590: }
2591: }
2592: }
2593: return $totcodes;
2594: }
2595:
1.1172.2.113 raeburn 2596: # --------------------------------------------- Get domain config for passwords
2597:
2598: sub get_passwdconf {
2599: my ($dom) = @_;
2600: my (%passwdconf,$gotconf,$lookup);
2601: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2602: if (defined($cached)) {
2603: if (ref($result) eq 'HASH') {
2604: %passwdconf = %{$result};
2605: $gotconf = 1;
2606: }
2607: }
2608: unless ($gotconf) {
2609: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2610: if (ref($domconfig{'passwords'}) eq 'HASH') {
2611: %passwdconf = %{$domconfig{'passwords'}};
2612: }
2613: my $cachetime = 24*60*60;
2614: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2615: }
2616: return %passwdconf;
2617: }
2618:
1.344 www 2619: # --------------------------------------------------- Assign a key to a student
2620:
2621: sub assign_access_key {
1.364 www 2622: #
2623: # a valid key looks like uname:udom#comments
2624: # comments are being appended
2625: #
1.498 www 2626: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2627: $kdom=
1.620 albertel 2628: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2629: $knum=
1.620 albertel 2630: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2631: $cdom=
1.620 albertel 2632: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2633: $cnum=
1.620 albertel 2634: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2635: $udom=$env{'user.name'} unless (defined($udom));
2636: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2637: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2638: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2639: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2640: # assigned to this person
2641: # - this should not happen,
1.345 www 2642: # unless something went wrong
2643: # the first time around
2644: # ready to assign
1.364 www 2645: $logentry=$1.'; '.$logentry;
1.496 www 2646: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2647: $kdom,$knum) eq 'ok') {
1.345 www 2648: # key now belongs to user
1.346 www 2649: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2650: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2651: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2652: return 'ok';
2653: } else {
2654: return
2655: 'error: Count not permanently assign key, will need to be re-entered later.';
2656: }
2657: } else {
2658: return 'error: Could not assign key, try again later.';
2659: }
1.364 www 2660: } elsif (!$existing{$ckey}) {
1.345 www 2661: # the key does not exist
2662: return 'error: The key does not exist';
2663: } else {
2664: # the key is somebody else's
2665: return 'error: The key is already in use';
2666: }
1.344 www 2667: }
2668:
1.364 www 2669: # ------------------------------------------ put an additional comment on a key
2670:
2671: sub comment_access_key {
2672: #
2673: # a valid key looks like uname:udom#comments
2674: # comments are being appended
2675: #
2676: my ($ckey,$cdom,$cnum,$logentry)=@_;
2677: $cdom=
1.620 albertel 2678: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2679: $cnum=
1.620 albertel 2680: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2681: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2682: if ($existing{$ckey}) {
2683: $existing{$ckey}.='; '.$logentry;
2684: # ready to assign
1.367 www 2685: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2686: $cdom,$cnum) eq 'ok') {
2687: return 'ok';
2688: } else {
2689: return 'error: Count not store comment.';
2690: }
2691: } else {
2692: # the key does not exist
2693: return 'error: The key does not exist';
2694: }
2695: }
2696:
1.344 www 2697: # ------------------------------------------------------ Generate a set of keys
2698:
2699: sub generate_access_keys {
1.364 www 2700: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2701: $cdom=
1.620 albertel 2702: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2703: $cnum=
1.620 albertel 2704: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2705: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2706: unless (($cdom) && ($cnum)) { return 0; }
2707: if ($number>10000) { return 0; }
2708: sleep(2); # make sure don't get same seed twice
2709: srand(time()^($$+($$<<15))); # from "Programming Perl"
2710: my $total=0;
2711: for (my $i=1;$i<=$number;$i++) {
2712: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2713: sprintf("%lx",int(100000*rand)).'-'.
2714: sprintf("%lx",int(100000*rand));
2715: $newkey=~s/1/g/g; # folks mix up 1 and l
2716: $newkey=~s/0/h/g; # and also 0 and O
2717: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2718: if ($existing{$newkey}) {
2719: $i--;
2720: } else {
1.364 www 2721: if (&put('accesskeys',
2722: { $newkey => '# generated '.localtime().
1.620 albertel 2723: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2724: '; '.$logentry },
2725: $cdom,$cnum) eq 'ok') {
1.344 www 2726: $total++;
2727: }
2728: }
2729: }
1.620 albertel 2730: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2731: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2732: return $total;
2733: }
2734:
2735: # ------------------------------------------------------- Validate an accesskey
2736:
2737: sub validate_access_key {
2738: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2739: $cdom=
1.620 albertel 2740: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2741: $cnum=
1.620 albertel 2742: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2743: $udom=$env{'user.domain'} unless (defined($udom));
2744: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2745: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2746: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2747: }
2748:
2749: # ------------------------------------- Find the section of student in a course
1.652 albertel 2750: sub devalidate_getsection_cache {
2751: my ($udom,$unam,$courseid)=@_;
2752: my $hashid="$udom:$unam:$courseid";
2753: &devalidate_cache_new('getsection',$hashid);
2754: }
1.298 matthew 2755:
1.815 albertel 2756: sub courseid_to_courseurl {
2757: my ($courseid) = @_;
2758: #already url style courseid
2759: return $courseid if ($courseid =~ m{^/});
2760:
2761: if (exists($env{'course.'.$courseid.'.num'})) {
2762: my $cnum = $env{'course.'.$courseid.'.num'};
2763: my $cdom = $env{'course.'.$courseid.'.domain'};
2764: return "/$cdom/$cnum";
2765: }
2766:
2767: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2768: if (exists($courseinfo{'num'})) {
2769: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2770: }
2771:
2772: return undef;
2773: }
2774:
1.298 matthew 2775: sub getsection {
2776: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2777: my $cachetime=1800;
1.551 albertel 2778:
2779: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2780: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2781: if (defined($cached)) { return $result; }
2782:
1.298 matthew 2783: my %Pending;
2784: my %Expired;
2785: #
2786: # Each role can either have not started yet (pending), be active,
2787: # or have expired.
2788: #
2789: # If there is an active role, we are done.
2790: #
2791: # If there is more than one role which has not started yet,
2792: # choose the one which will start sooner
2793: # If there is one role which has not started yet, return it.
2794: #
2795: # If there is more than one expired role, choose the one which ended last.
2796: # If there is a role which has expired, return it.
2797: #
1.815 albertel 2798: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2799: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2800: foreach my $key (keys(%roleshash)) {
1.479 albertel 2801: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2802: my $section=$1;
2803: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2804: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2805: my $now=time;
1.548 albertel 2806: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2807: $Expired{$end}=$section;
2808: next;
2809: }
1.548 albertel 2810: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2811: $Pending{$start}=$section;
2812: next;
2813: }
1.599 albertel 2814: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2815: }
2816: #
2817: # Presumedly there will be few matching roles from the above
2818: # loop and the sorting time will be negligible.
2819: if (scalar(keys(%Pending))) {
2820: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2821: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2822: }
2823: if (scalar(keys(%Expired))) {
2824: my @sorted = sort {$a <=> $b} keys(%Expired);
2825: my $time = pop(@sorted);
1.599 albertel 2826: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2827: }
1.599 albertel 2828: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2829: }
1.70 www 2830:
1.599 albertel 2831: sub save_cache {
2832: &purge_remembered();
1.722 albertel 2833: #&Apache::loncommon::validate_page();
1.620 albertel 2834: undef(%env);
1.780 albertel 2835: undef($env_loaded);
1.599 albertel 2836: }
1.452 albertel 2837:
1.599 albertel 2838: my $to_remember=-1;
2839: my %remembered;
2840: my %accessed;
2841: my $kicks=0;
2842: my $hits=0;
1.849 albertel 2843: sub make_key {
2844: my ($name,$id) = @_;
1.872 albertel 2845: if (length($id) > 65
2846: && length(&escape($id)) > 200) {
2847: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2848: }
1.849 albertel 2849: return &escape($name.':'.$id);
2850: }
2851:
1.599 albertel 2852: sub devalidate_cache_new {
2853: my ($name,$id,$debug) = @_;
2854: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2855: my $remembered_id=$name.':'.$id;
1.849 albertel 2856: $id=&make_key($name,$id);
1.599 albertel 2857: $memcache->delete($id);
1.1172.2.81 raeburn 2858: delete($remembered{$remembered_id});
2859: delete($accessed{$remembered_id});
1.599 albertel 2860: }
2861:
2862: sub is_cached_new {
2863: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2864: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2865: # keys in %remembered hash, which persists for
2866: # duration of request (no restriction on key length).
2867: if (exists($remembered{$remembered_id})) {
2868: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2869: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2870: $hits++;
1.1172.2.81 raeburn 2871: return ($remembered{$remembered_id},1);
1.599 albertel 2872: }
1.1172.2.81 raeburn 2873: $id=&make_key($name,$id);
1.599 albertel 2874: my $value = $memcache->get($id);
2875: if (!(defined($value))) {
2876: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2877: return (undef,undef);
1.416 albertel 2878: }
1.599 albertel 2879: if ($value eq '__undef__') {
2880: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2881: $value=undef;
2882: }
1.1172.2.81 raeburn 2883: &make_room($remembered_id,$value,$debug);
1.599 albertel 2884: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2885: return ($value,1);
2886: }
2887:
2888: sub do_cache_new {
2889: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2890: my $remembered_id=$name.':'.$id;
1.849 albertel 2891: $id=&make_key($name,$id);
1.599 albertel 2892: my $setvalue=$value;
2893: if (!defined($setvalue)) {
2894: $setvalue='__undef__';
2895: }
1.623 albertel 2896: if (!defined($time) ) {
2897: $time=600;
2898: }
1.599 albertel 2899: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2900: my $result = $memcache->set($id,$setvalue,$time);
2901: if (! $result) {
1.872 albertel 2902: &logthis("caching of id -> $id failed");
1.910 albertel 2903: $memcache->disconnect_all();
1.872 albertel 2904: }
1.600 albertel 2905: # need to make a copy of $value
1.1172.2.81 raeburn 2906: &make_room($remembered_id,$value,$debug);
1.599 albertel 2907: return $value;
2908: }
2909:
2910: sub make_room {
1.1172.2.81 raeburn 2911: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2912:
1.1172.2.81 raeburn 2913: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2914: : $value;
1.599 albertel 2915: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2916: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2917: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2918: my $to_kick;
2919: my $max_time=0;
2920: foreach my $other (keys(%accessed)) {
2921: if (&tv_interval($accessed{$other}) > $max_time) {
2922: $to_kick=$other;
2923: $max_time=&tv_interval($accessed{$other});
2924: }
2925: }
2926: delete($remembered{$to_kick});
2927: delete($accessed{$to_kick});
2928: $kicks++;
2929: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2930: return;
2931: }
2932:
1.599 albertel 2933: sub purge_remembered {
1.604 albertel 2934: #&logthis("Tossing ".scalar(keys(%remembered)));
2935: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2936: undef(%remembered);
2937: undef(%accessed);
1.428 albertel 2938: }
1.70 www 2939: # ------------------------------------- Read an entry from a user's environment
2940:
2941: sub userenvironment {
2942: my ($udom,$unam,@what)=@_;
1.976 raeburn 2943: my $items;
2944: foreach my $item (@what) {
2945: $items.=&escape($item).'&';
2946: }
2947: $items=~s/\&$//;
1.70 www 2948: my %returnhash=();
1.1009 raeburn 2949: my $uhome = &homeserver($unam,$udom);
2950: unless ($uhome eq 'no_host') {
2951: my @answer=split(/\&/,
2952: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2953: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2954: return %returnhash;
2955: }
1.1009 raeburn 2956: my $i;
2957: for ($i=0;$i<=$#what;$i++) {
2958: $returnhash{$what[$i]}=&unescape($answer[$i]);
2959: }
1.70 www 2960: }
2961: return %returnhash;
1.1 albertel 2962: }
2963:
1.617 albertel 2964: # ---------------------------------------------------------- Get a studentphoto
2965: sub studentphoto {
2966: my ($udom,$unam,$ext) = @_;
2967: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2968: if (defined($env{'request.course.id'})) {
1.708 raeburn 2969: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2970: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2971: return(&retrievestudentphoto($udom,$unam,$ext));
2972: } else {
2973: my ($result,$perm_reqd)=
1.707 albertel 2974: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2975: if ($result eq 'ok') {
2976: if (!($perm_reqd eq 'yes')) {
2977: return(&retrievestudentphoto($udom,$unam,$ext));
2978: }
2979: }
2980: }
2981: }
2982: } else {
2983: my ($result,$perm_reqd) =
1.707 albertel 2984: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2985: if ($result eq 'ok') {
2986: if (!($perm_reqd eq 'yes')) {
2987: return(&retrievestudentphoto($udom,$unam,$ext));
2988: }
2989: }
2990: }
2991: return '/adm/lonKaputt/lonlogo_broken.gif';
2992: }
2993:
2994: sub retrievestudentphoto {
2995: my ($udom,$unam,$ext,$type) = @_;
2996: my $home=&Apache::lonnet::homeserver($unam,$udom);
2997: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2998: if ($ret eq 'ok') {
2999: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3000: if ($type eq 'thumbnail') {
3001: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3002: }
3003: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3004: return $tokenurl;
3005: } else {
3006: if ($type eq 'thumbnail') {
3007: return '/adm/lonKaputt/genericstudent_tn.gif';
3008: } else {
3009: return '/adm/lonKaputt/lonlogo_broken.gif';
3010: }
1.617 albertel 3011: }
3012: }
3013:
1.263 www 3014: # -------------------------------------------------------------------- New chat
3015:
3016: sub chatsend {
1.724 raeburn 3017: my ($newentry,$anon,$group)=@_;
1.620 albertel 3018: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3019: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3020: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3021: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3022: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3023: &escape($newentry)).':'.$group,$chome);
1.292 www 3024: }
3025:
3026: # ------------------------------------------ Find current version of a resource
3027:
3028: sub getversion {
3029: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3030: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3031: return ¤tversion(&filelocation('',$fname));
3032: }
3033:
3034: sub currentversion {
3035: my $fname=shift;
3036: my $author=$fname;
3037: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3038: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3039: my $home=&homeserver($uname,$udom);
1.292 www 3040: if ($home eq 'no_host') {
3041: return -1;
3042: }
1.1112 www 3043: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3044: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3045: return -1;
3046: }
1.1112 www 3047: return $answer;
1.263 www 3048: }
3049:
1.1111 www 3050: #
3051: # Return special version number of resource if set by override, empty otherwise
3052: #
3053: sub usedversion {
3054: my $fname=shift;
3055: unless ($fname) { $fname=$env{'request.uri'}; }
3056: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3057: if ($urlversion) { return $urlversion; }
3058: return '';
3059: }
3060:
1.1 albertel 3061: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3062:
1.1 albertel 3063: sub subscribe {
3064: my $fname=shift;
1.761 raeburn 3065: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3066: $fname=~s/[\n\r]//g;
1.1 albertel 3067: my $author=$fname;
3068: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3069: my ($udom,$uname)=split(/\//,$author);
3070: my $home=homeserver($uname,$udom);
1.335 albertel 3071: if ($home eq 'no_host') {
3072: return 'not_found';
1.1 albertel 3073: }
3074: my $answer=reply("sub:$fname",$home);
1.64 www 3075: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3076: $answer.=' by '.$home;
3077: }
1.1 albertel 3078: return $answer;
3079: }
3080:
1.8 www 3081: # -------------------------------------------------------------- Replicate file
3082:
3083: sub repcopy {
3084: my $filename=shift;
1.23 www 3085: $filename=~s/\/+/\//g;
1.1142 raeburn 3086: my $londocroot = $perlvar{'lonDocRoot'};
3087: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3088: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3089: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3090: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3091: return &repcopy_userfile($filename);
3092: }
1.532 albertel 3093: $filename=~s/[\n\r]//g;
1.8 www 3094: my $transname="$filename.in.transfer";
1.828 www 3095: # FIXME: this should flock
1.607 raeburn 3096: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3097: my $remoteurl=subscribe($filename);
1.64 www 3098: if ($remoteurl =~ /^con_lost by/) {
3099: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3100: return 'unavailable';
1.8 www 3101: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3102: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3103: return 'not_found';
1.64 www 3104: } elsif ($remoteurl =~ /^rejected by/) {
3105: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3106: return 'forbidden';
1.20 www 3107: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3108: return 'ok';
1.8 www 3109: } else {
1.290 www 3110: my $author=$filename;
3111: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3112: my ($udom,$uname)=split(/\//,$author);
3113: my $home=homeserver($uname,$udom);
3114: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3115: my @parts=split(/\//,$filename);
3116: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3117: if ($path ne "$londocroot/res") {
1.8 www 3118: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3119: return 'bad_request';
1.8 www 3120: }
3121: my $count;
3122: for ($count=5;$count<$#parts;$count++) {
3123: $path.="/$parts[$count]";
3124: if ((-e $path)!=1) {
3125: mkdir($path,0777);
3126: }
3127: }
3128: my $ua=new LWP::UserAgent;
3129: my $request=new HTTP::Request('GET',"$remoteurl");
3130: my $response=$ua->request($request,$transname);
3131: if ($response->is_error()) {
3132: unlink($transname);
3133: my $message=$response->status_line;
1.672 albertel 3134: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3135: ." LWP get: $message: $filename</font>");
1.607 raeburn 3136: return 'unavailable';
1.8 www 3137: } else {
1.16 www 3138: if ($remoteurl!~/\.meta$/) {
3139: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3140: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3141: if ($mresponse->is_error()) {
3142: unlink($filename.'.meta');
3143: &logthis(
1.672 albertel 3144: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3145: }
3146: }
1.8 www 3147: rename($transname,$filename);
1.607 raeburn 3148: return 'ok';
1.8 www 3149: }
1.290 www 3150: }
1.8 www 3151: }
1.330 www 3152: }
3153:
1.1172.2.124 raeburn 3154: # ------------------------------------------------- Unsubscribe from a resource
3155:
3156: sub unsubscribe {
3157: my ($fname) = @_;
3158: my $answer;
3159: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3160: $fname=~s/[\n\r]//g;
3161: my $author=$fname;
3162: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3163: my ($udom,$uname)=split(/\//,$author);
3164: my $home=homeserver($uname,$udom);
3165: if ($home eq 'no_host') {
3166: $answer = 'no_host';
3167: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3168: $answer = 'home';
3169: } else {
1.1172.2.125 raeburn 3170: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3171: }
3172: return $answer;
3173: }
3174:
1.330 www 3175: # ------------------------------------------------ Get server side include body
3176: sub ssi_body {
1.381 albertel 3177: my ($filelink,%form)=@_;
1.606 matthew 3178: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3179: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3180: }
1.953 www 3181: my $output='';
3182: my $response;
1.980 raeburn 3183: if ($filelink=~/^https?\:/) {
1.954 raeburn 3184: ($output,$response)=&externalssi($filelink);
1.953 www 3185: } else {
1.1004 droeschl 3186: $filelink .= $filelink=~/\?/ ? '&' : '?';
3187: $filelink .= 'inhibitmenu=yes';
1.953 www 3188: ($output,$response)=&ssi($filelink,%form);
3189: }
1.778 albertel 3190: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3191: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3192: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3193: if (wantarray) {
3194: return ($output, $response);
3195: } else {
3196: return $output;
3197: }
1.8 www 3198: }
3199:
1.15 www 3200: # --------------------------------------------------------- Server Side Include
3201:
1.782 albertel 3202: sub absolute_url {
1.1172.2.145 raeburn 3203: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3204: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3205: if ($host_name eq '') {
3206: $host_name = $ENV{'SERVER_NAME'};
3207: }
1.1172.2.145 raeburn 3208: if ($unalias) {
3209: my $alias = &get_proxy_alias();
3210: if ($alias eq $host_name) {
3211: my $lonhost = $perlvar{'lonHostID'};
3212: my $hostname = &hostname($lonhost);
3213: my $lcproto;
3214: if (($keep_proto) || ($hostname eq '')) {
3215: $lcproto = $protocol;
3216: } else {
3217: $lcproto = $protocol{$lonhost};
3218: $lcproto = 'http' if ($lcproto ne 'https');
3219: $lcproto .= '://';
3220: }
3221: unless ($hostname eq '') {
3222: return $lcproto.$hostname;
3223: }
3224: }
3225: }
1.782 albertel 3226: return $protocol.$host_name;
3227: }
3228:
1.942 foxr 3229: #
3230: # Server side include.
3231: # Parameters:
3232: # fn Possibly encrypted resource name/id.
3233: # form Hash that describes how the rendering should be done
3234: # and other things.
1.944 foxr 3235: # Returns:
1.950 raeburn 3236: # Scalar context: The content of the response.
3237: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3238: #
1.15 www 3239: sub ssi {
3240:
1.944 foxr 3241: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3242: my ($host,$request,$response);
3243: $host = &absolute_url('',1);
1.711 albertel 3244:
3245: $form{'no_update_last_known'}=1;
1.895 albertel 3246: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3247: if (%form) {
1.1172.2.145 raeburn 3248: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3249: $request->content(join('&',map {
3250: my $name = escape($_);
3251: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3252: ? join("&$name=", map {escape($_) } @{$form{$_}})
3253: : &escape($form{$_}) );
3254: } keys(%form)));
1.23 www 3255: } else {
1.1172.2.145 raeburn 3256: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3257: }
3258:
1.15 www 3259: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3260:
1.1172.2.101 raeburn 3261: if (($env{'request.course.id'}) &&
3262: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3263: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3264: ($form{'grade_symb'} ne '') &&
3265: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3266: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3267: if (LWP::UserAgent->VERSION >= 5.834) {
3268: my $ua=new LWP::UserAgent;
3269: $ua->local_address('127.0.0.1');
3270: $response = $ua->request($request);
3271: } else {
3272: {
3273: require LWP::Protocol::http;
3274: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3275: my $ua=new LWP::UserAgent;
3276: $response = $ua->request($request);
3277: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3278: }
3279: }
3280: } else {
3281: my $ua=new LWP::UserAgent;
3282: $response = $ua->request($request);
3283: }
1.944 foxr 3284: if (wantarray) {
1.1172.2.3 raeburn 3285: return ($response->content, $response);
1.944 foxr 3286: } else {
1.1172.2.3 raeburn 3287: return $response->content;
1.942 foxr 3288: }
1.324 www 3289: }
3290:
3291: sub externalssi {
3292: my ($url)=@_;
3293: my $ua=new LWP::UserAgent;
3294: my $request=new HTTP::Request('GET',$url);
3295: my $response=$ua->request($request);
1.954 raeburn 3296: if (wantarray) {
3297: return ($response->content, $response);
3298: } else {
3299: return $response->content;
3300: }
1.15 www 3301: }
1.254 www 3302:
1.1172.2.98 raeburn 3303: # If the local copy of a replicated resource is outdated, trigger a
3304: # connection from the homeserver to flush the delayed queue. If no update
3305: # happens, remove local copies of outdated resource (and corresponding
3306: # metadata file).
3307:
3308: sub remove_stale_resfile {
3309: my ($url) = @_;
3310: my $removed;
3311: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3312: my $audom = $1;
3313: my $auname = $2;
3314: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3315: my $homeserver = &homeserver($auname,$audom);
3316: unless (($homeserver eq 'no_host') ||
3317: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3318: my $fname = &filelocation('',$url);
3319: if (-e $fname) {
3320: my $hostname = &hostname($homeserver);
3321: if ($hostname) {
1.1172.2.120 raeburn 3322: my $protocol = $protocol{$homeserver};
3323: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3324: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3325: my $ua=new LWP::UserAgent;
3326: $ua->timeout(5);
1.1172.2.98 raeburn 3327: my $request=new HTTP::Request('HEAD',$uri);
3328: my $response=$ua->request($request);
3329: if ($response->is_success()) {
3330: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3331: my $locmodtime = (stat($fname))[9];
3332: if ($locmodtime < $remmodtime) {
3333: my $stale;
3334: my $answer = &reply('pong',$homeserver);
3335: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3336: sleep(0.2);
3337: $locmodtime = (stat($fname))[9];
3338: if ($locmodtime < $remmodtime) {
3339: my $posstransfer = $fname.'.in.transfer';
3340: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3341: $removed = 1;
3342: } else {
3343: $stale = 1;
3344: }
3345: } else {
3346: $removed = 1;
3347: }
3348: } else {
3349: $stale = 1;
3350: }
3351: if ($stale) {
1.1172.2.124 raeburn 3352: if (unlink($fname)) {
3353: if ($uri!~/\.meta$/) {
3354: if (-e $fname.'.meta') {
3355: unlink($fname.'.meta');
3356: }
3357: }
3358: my $unsubresult = &unsubscribe($fname);
3359: unless ($unsubresult eq 'ok') {
3360: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3361: }
3362: $removed = 1;
1.1172.2.98 raeburn 3363: }
3364: }
3365: }
3366: }
3367: }
3368: }
3369: }
3370: }
3371: }
3372: return $removed;
3373: }
3374:
1.492 albertel 3375: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3376:
3377: sub allowuploaded {
3378: my ($srcurl,$url)=@_;
3379: $url=&clutter(&declutter($url));
3380: my $dir=$url;
3381: $dir=~s/\/[^\/]+$//;
3382: my %httpref=();
3383: my $httpurl=&hreflocation('',$url);
3384: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3385: &Apache::lonnet::appenv(\%httpref);
1.254 www 3386: }
1.477 raeburn 3387:
1.1172.2.13 raeburn 3388: #
3389: # Determine if the current user should be able to edit a particular resource,
3390: # when viewing in course context.
3391: # (a) When viewing resource used to determine if "Edit" item is included in
3392: # Functions.
3393: # (b) When displaying folder contents in course editor, used to determine if
3394: # "Edit" link will be displayed alongside resource.
3395: #
3396: # input: six args -- filename (decluttered), course number, course domain,
3397: # url, symb (if registered) and group (if this is a group
3398: # item -- e.g., bulletin board, group page etc.).
3399: # output: array of five scalars --
3400: # $cfile -- url for file editing if editable on current server
3401: # $home -- homeserver of resource (i.e., for author if published,
3402: # or course if uploaded.).
3403: # $switchserver -- 1 if server switch will be needed.
3404: # $forceedit -- 1 if icon/link should be to go to edit mode
3405: # $forceview -- 1 if icon/link should be to go to view mode
3406: #
3407:
3408: sub can_edit_resource {
3409: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3410: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3411: #
3412: # For aboutme pages user can only edit his/her own.
3413: #
3414: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3415: my ($sdom,$sname) = ($1,$2);
3416: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3417: $home = $env{'user.home'};
3418: $cfile = $resurl;
3419: if ($env{'form.forceedit'}) {
3420: $forceview = 1;
3421: } else {
3422: $forceedit = 1;
3423: }
3424: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3425: } else {
3426: return;
3427: }
3428: }
3429:
3430: if ($env{'request.course.id'}) {
3431: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3432: if ($group ne '') {
3433: # if this is a group homepage or group bulletin board, check group privs
3434: my $allowed = 0;
3435: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3436: if ((&allowed('mdg',$env{'request.course.id'}.
3437: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3438: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3439: $allowed = 1;
3440: }
3441: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3442: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3443: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3444: $allowed = 1;
3445: }
3446: }
3447: if ($allowed) {
3448: $home=&homeserver($cnum,$cdom);
3449: if ($env{'form.forceedit'}) {
3450: $forceview = 1;
3451: } else {
3452: $forceedit = 1;
3453: }
3454: $cfile = $resurl;
3455: } else {
3456: return;
3457: }
3458: } else {
1.1172.2.15 raeburn 3459: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3460: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3461: return;
3462: }
3463: } elsif (!$crsedit) {
1.1172.2.148 raeburn 3464: if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1172.2.13 raeburn 3465: #
3466: # No edit allowed where CC has switched to student role.
3467: #
1.1172.2.148 raeburn 3468: return;
3469: } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
3470: ($resurl =~ m{^/res/lib/templates/})) {
3471: return;
3472: }
1.1172.2.13 raeburn 3473: }
3474: }
3475: }
3476:
3477: if ($file ne '') {
3478: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3479: if (&is_course_upload($file,$cnum,$cdom)) {
3480: $uploaded = 1;
3481: $incourse = 1;
3482: if ($file =~/\.(htm|html|css|js|txt)$/) {
3483: $cfile = &hreflocation('',$file);
3484: if ($env{'form.forceedit'}) {
3485: $forceview = 1;
3486: } else {
3487: $forceedit = 1;
3488: }
3489: }
3490: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3491: $incourse = 1;
3492: if ($env{'form.forceedit'}) {
3493: $forceview = 1;
3494: } else {
3495: $forceedit = 1;
3496: }
3497: $cfile = $resurl;
3498: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3499: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3500: $incourse = 1;
3501: if ($env{'form.forceedit'}) {
3502: $forceview = 1;
3503: } else {
3504: $forceedit = 1;
3505: }
3506: $cfile = $resurl;
3507: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3508: $incourse = 1;
3509: $cfile = $resurl.'/smpedit';
3510: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3511: $incourse = 1;
3512: if ($env{'form.forceedit'}) {
3513: $forceview = 1;
3514: } else {
3515: $forceedit = 1;
3516: }
3517: $cfile = $resurl;
1.1172.2.122 raeburn 3518: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3519: my ($map,$id,$res) = &decode_symb($symb);
3520: if ($map =~ /\.page$/) {
3521: $incourse = 1;
3522: if ($env{'form.forceedit'}) {
3523: $forceview = 1;
3524: $cfile = $map;
3525: } else {
3526: $forceedit = 1;
3527: $cfile = '/adm/wrapper'.$resurl;
3528: }
3529: }
1.1172.2.15 raeburn 3530: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3531: $incourse = 1;
3532: if ($env{'form.forceedit'}) {
3533: $forceview = 1;
3534: } else {
3535: $forceedit = 1;
3536: }
3537: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3538: }
3539: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3540: my $template = '/res/lib/templates/simpleproblem.problem';
3541: if (&is_on_map($template)) {
3542: $incourse = 1;
3543: $forceview = 1;
3544: $cfile = $template;
3545: }
3546: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3547: $incourse = 1;
3548: if ($env{'form.forceedit'}) {
3549: $forceview = 1;
3550: } else {
3551: $forceedit = 1;
3552: }
3553: $cfile = $resurl;
1.1172.2.13 raeburn 3554: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3555: $incourse = 1;
3556: $forceview = 1;
3557: if ($symb) {
3558: my ($map,$id,$res)=&decode_symb($symb);
3559: $env{'request.symb'} = $symb;
3560: $cfile = &clutter($res);
3561: } else {
3562: $cfile = $env{'form.suppurl'};
3563: $cfile =~ s{^http://}{};
3564: $cfile = '/adm/wrapper/ext/'.$cfile;
3565: }
1.1172.2.31 raeburn 3566: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3567: if ($env{'form.forceedit'}) {
3568: $forceview = 1;
3569: } else {
3570: $forceedit = 1;
3571: }
3572: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3573: }
3574: }
3575: if ($uploaded || $incourse) {
3576: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3577: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3578: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3579: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3580: # Check that the user has permission to edit this resource
3581: my $setpriv = 1;
3582: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3583: if (defined($cfudom)) {
3584: $home=&homeserver($cfuname,$cfudom);
3585: $cfile=$file;
3586: }
3587: }
3588: if (($cfile ne '') && (!$incourse || $uploaded) &&
3589: (($home ne '') && ($home ne 'no_host'))) {
3590: my @ids=¤t_machine_ids();
3591: unless (grep(/^\Q$home\E$/,@ids)) {
3592: $switchserver=1;
3593: }
3594: }
3595: }
3596: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3597: }
3598:
3599: sub is_course_upload {
3600: my ($file,$cnum,$cdom) = @_;
3601: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3602: $uploadpath =~ s{^\/}{};
3603: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3604: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3605: return 1;
3606: }
3607: return;
3608: }
3609:
3610: sub in_course {
3611: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3612: if ($hideprivileged) {
3613: my $skipuser;
1.1172.2.23 raeburn 3614: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3615: my @possdoms = ($cdom);
3616: if ($coursehash{'checkforpriv'}) {
3617: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3618: }
3619: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3620: $skipuser = 1;
3621: if ($coursehash{'nothideprivileged'}) {
3622: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3623: my $user;
3624: if ($item =~ /:/) {
3625: $user = $item;
3626: } else {
3627: $user = join(':',split(/[\@]/,$item));
3628: }
3629: if ($user eq $uname.':'.$udom) {
3630: undef($skipuser);
3631: last;
3632: }
3633: }
3634: }
3635: if ($skipuser) {
3636: return 0;
3637: }
3638: }
3639: }
3640: $type ||= 'any';
3641: if (!defined($cdom) || !defined($cnum)) {
3642: my $cid = $env{'request.course.id'};
3643: $cdom = $env{'course.'.$cid.'.domain'};
3644: $cnum = $env{'course.'.$cid.'.num'};
3645: }
3646: my $typesref;
3647: if (($type eq 'any') || ($type eq 'all')) {
3648: $typesref = ['active','previous','future'];
3649: } elsif ($type eq 'previous' || $type eq 'future') {
3650: $typesref = [$type];
3651: }
3652: my %roles = &get_my_roles($uname,$udom,'userroles',
3653: $typesref,undef,[$cdom]);
3654: my ($tmp) = keys(%roles);
3655: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3656: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3657: if (@course_roles > 0) {
3658: return 1;
3659: }
3660: return 0;
3661: }
3662:
1.478 albertel 3663: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3664: # input: action, courseID, current domain, intended
1.637 raeburn 3665: # path to file, source of file, instruction to parse file for objects,
3666: # ref to hash for embedded objects,
3667: # ref to hash for codebase of java objects.
1.1095 raeburn 3668: # reference to scalar to accommodate mime type determined
3669: # from File::MMagic if $parser = parse.
1.637 raeburn 3670: #
1.485 raeburn 3671: # output: url to file (if action was uploaddoc),
3672: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3673: #
1.478 albertel 3674: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3675: # course.
1.477 raeburn 3676: #
1.478 albertel 3677: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3678: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3679: # course's home server.
1.477 raeburn 3680: #
1.478 albertel 3681: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3682: # be copied from $source (current location) to
3683: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3684: # and will then be copied to
3685: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3686: # course's home server.
1.485 raeburn 3687: #
1.481 raeburn 3688: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3689: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3690: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3691: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3692: # in course's home server.
1.637 raeburn 3693: #
1.477 raeburn 3694:
3695: sub process_coursefile {
1.1095 raeburn 3696: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3697: $mimetype)=@_;
1.477 raeburn 3698: my $fetchresult;
1.638 albertel 3699: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3700: if ($action eq 'propagate') {
1.638 albertel 3701: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3702: $home);
1.481 raeburn 3703: } else {
1.477 raeburn 3704: my $fpath = '';
3705: my $fname = $file;
1.478 albertel 3706: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3707: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3708: my $filepath = &build_filepath($fpath);
1.481 raeburn 3709: if ($action eq 'copy') {
3710: if ($source eq '') {
3711: $fetchresult = 'no source file';
3712: return $fetchresult;
3713: } else {
3714: my $destination = $filepath.'/'.$fname;
3715: rename($source,$destination);
3716: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3717: $home);
1.481 raeburn 3718: }
3719: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3720: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3721: print $fh $env{'form.'.$source};
1.481 raeburn 3722: close($fh);
1.637 raeburn 3723: if ($parser eq 'parse') {
1.1024 raeburn 3724: my $mm = new File::MMagic;
1.1095 raeburn 3725: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3726: if ($type eq 'text/html') {
1.1024 raeburn 3727: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3728: unless ($parse_result eq 'ok') {
3729: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3730: }
1.637 raeburn 3731: }
1.1095 raeburn 3732: if (ref($mimetype)) {
3733: $$mimetype = $type;
3734: }
1.637 raeburn 3735: }
1.477 raeburn 3736: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3737: $home);
1.481 raeburn 3738: if ($fetchresult eq 'ok') {
3739: return '/uploaded/'.$fpath.'/'.$fname;
3740: } else {
3741: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3742: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3743: return '/adm/notfound.html';
3744: }
1.477 raeburn 3745: }
3746: }
1.485 raeburn 3747: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3748: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3749: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3750: }
3751: return $fetchresult;
3752: }
3753:
1.637 raeburn 3754: sub build_filepath {
3755: my ($fpath) = @_;
3756: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3757: unless ($fpath eq '') {
3758: my @parts=split('/',$fpath);
3759: foreach my $part (@parts) {
3760: $filepath.= '/'.$part;
3761: if ((-e $filepath)!=1) {
3762: mkdir($filepath,0777);
3763: }
3764: }
3765: }
3766: return $filepath;
3767: }
3768:
3769: sub store_edited_file {
1.638 albertel 3770: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3771: my $file = $primary_url;
3772: $file =~ s#^/uploaded/$docudom/$docuname/##;
3773: my $fpath = '';
3774: my $fname = $file;
3775: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3776: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3777: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3778: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3779: print $fh $content;
3780: close($fh);
1.638 albertel 3781: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3782: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3783: $home);
1.637 raeburn 3784: if ($$fetchresult eq 'ok') {
3785: return '/uploaded/'.$fpath.'/'.$fname;
3786: } else {
1.638 albertel 3787: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3788: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3789: return '/adm/notfound.html';
3790: }
3791: }
3792:
1.531 albertel 3793: sub clean_filename {
1.831 albertel 3794: my ($fname,$args)=@_;
1.315 www 3795: # Replace Windows backslashes by forward slashes
1.257 www 3796: $fname=~s/\\/\//g;
1.831 albertel 3797: if (!$args->{'keep_path'}) {
3798: # Get rid of everything but the actual filename
3799: $fname=~s/^.*\/([^\/]+)$/$1/;
3800: }
1.315 www 3801: # Replace spaces by underscores
3802: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3803: # Transliterate non-ascii text to ascii
3804: my $lang = &Apache::lonlocal::current_language();
3805: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3806: # Replace all other weird characters by nothing
1.831 albertel 3807: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3808: # Replace all .\d. sequences with _\d. so they no longer look like version
3809: # numbers
3810: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3811: # Replace three or more adjacent underscores with one for consistency
3812: # with loncfile::filename_check() so complete url can be extracted by
3813: # lonnet::decode_symb()
3814: $fname=~s/_{3,}/_/g;
1.531 albertel 3815: return $fname;
3816: }
1.1172.2.110 raeburn 3817:
1.1051 raeburn 3818: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3819: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3820: # image with the same aspect ratio as the original, but with dimensions which do
3821: # not exceed $resizewidth and $resizeheight.
3822:
1.984 neumanie 3823: sub resizeImage {
1.1051 raeburn 3824: my ($img_path,$resizewidth,$resizeheight) = @_;
3825: my $ima = Image::Magick->new;
3826: my $resized;
3827: if (-e $img_path) {
3828: $ima->Read($img_path);
3829: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3830: my $width = $ima->Get('width');
3831: my $height = $ima->Get('height');
3832: if ($width > $resizewidth) {
3833: my $factor = $width/$resizewidth;
3834: my $newheight = $height/$factor;
3835: $ima->Scale(width=>$resizewidth,height=>$newheight);
3836: $resized = 1;
3837: }
3838: }
3839: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3840: my $width = $ima->Get('width');
3841: my $height = $ima->Get('height');
3842: if ($height > $resizeheight) {
3843: my $factor = $height/$resizeheight;
3844: my $newwidth = $width/$factor;
3845: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3846: $resized = 1;
3847: }
3848: }
3849: if ($resized) {
3850: $ima->Write($img_path);
3851: }
3852: }
3853: return;
1.977 amueller 3854: }
3855:
1.608 albertel 3856: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3857: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3858: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3859: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3860: # canceloverwrite, scantron or ''.
1.1090 raeburn 3861: # if 'coursedoc': upload to the current course
3862: # if 'existingfile': write file to tmp/overwrites directory
3863: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3864: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3865: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3866: # $parser - instruction to parse file for objects ($parser = parse) or
3867: # if context is 'scantron', $parser is hashref of csv column mapping
3868: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3869: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3870: # $allfiles - reference to hash for embedded objects
3871: # $codebase - reference to hash for codebase of java objects
3872: # $desuname - username for permanent storage of uploaded file
3873: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3874: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3875: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3876: # $resizewidth - width (pixels) to which to resize uploaded image
3877: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3878: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3879: # from File::MMagic.
1.858 raeburn 3880: #
1.686 albertel 3881: # output: url of file in userspace, or error: <message>
3882: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3883:
1.531 albertel 3884: sub userfileupload {
1.1090 raeburn 3885: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3886: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3887: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3888: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3889: $fname=&clean_filename($fname);
1.1090 raeburn 3890: # See if there is anything left
1.257 www 3891: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3892: # If filename now begins with a . prepend unix timestamp _ milliseconds
3893: if ($fname =~ /^\./) {
3894: my ($s,$usec) = &gettimeofday();
3895: while (length($usec) < 6) {
3896: $usec = '0'.$usec;
3897: }
3898: $fname = $s.'_'.substr($usec,0,3).$fname;
3899: }
1.1090 raeburn 3900: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3901: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3902: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3903: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3904: my $now = time;
1.1090 raeburn 3905: my $filepath;
1.1095 raeburn 3906: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3907: $filepath = 'tmp/helprequests/'.$now;
3908: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3909: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3910: '_'.$env{'user.domain'}.'/pending';
3911: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3912: my ($docuname,$docudom);
1.1172.2.96 raeburn 3913: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3914: $docudom = $destudom;
3915: } else {
3916: $docudom = $env{'user.domain'};
3917: }
1.1172.2.96 raeburn 3918: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3919: $docuname = $destuname;
3920: } else {
3921: $docuname = $env{'user.name'};
3922: }
3923: if (exists($env{'form.group'})) {
3924: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3925: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3926: }
3927: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3928: if ($context eq 'canceloverwrite') {
3929: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3930: if (-e $tempfile) {
3931: my @info = stat($tempfile);
3932: if ($info[9] eq $env{'form.timestamp'}) {
3933: unlink($tempfile);
3934: }
3935: }
3936: return;
1.523 raeburn 3937: }
3938: }
1.1090 raeburn 3939: # Create the directory if not present
1.741 raeburn 3940: my @parts=split(/\//,$filepath);
3941: my $fullpath = $perlvar{'lonDaemons'};
3942: for (my $i=0;$i<@parts;$i++) {
3943: $fullpath .= '/'.$parts[$i];
3944: if ((-e $fullpath)!=1) {
3945: mkdir($fullpath,0777);
3946: }
3947: }
1.1172.2.96 raeburn 3948: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3949: print $fh $env{'form.'.$formname};
3950: close($fh);
1.1090 raeburn 3951: if ($context eq 'existingfile') {
3952: my @info = stat($fullpath.'/'.$fname);
3953: return ($fullpath.'/'.$fname,$info[9]);
3954: } else {
3955: return $fullpath.'/'.$fname;
3956: }
1.523 raeburn 3957: }
1.995 raeburn 3958: if ($subdir eq 'scantron') {
3959: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3960: } else {
1.995 raeburn 3961: $fname="$subdir/$fname";
3962: }
1.1090 raeburn 3963: if ($context eq 'coursedoc') {
1.638 albertel 3964: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3965: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3966: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3967: return &finishuserfileupload($docuname,$docudom,
3968: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3969: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3970: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3971: } else {
1.1172.2.21 raeburn 3972: if ($env{'form.folder'}) {
3973: $fname=$env{'form.folder'}.'/'.$fname;
3974: }
1.638 albertel 3975: return &process_coursefile('uploaddoc',$docuname,$docudom,
3976: $fname,$formname,$parser,
1.1095 raeburn 3977: $allfiles,$codebase,$mimetype);
1.481 raeburn 3978: }
1.719 banghart 3979: } elsif (defined($destuname)) {
3980: my $docuname=$destuname;
3981: my $docudom=$destudom;
1.860 raeburn 3982: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3983: $parser,$allfiles,$codebase,
1.1051 raeburn 3984: $thumbwidth,$thumbheight,
1.1095 raeburn 3985: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3986: } else {
1.638 albertel 3987: my $docuname=$env{'user.name'};
3988: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3989: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3990: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3991: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3992: }
1.860 raeburn 3993: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3994: $parser,$allfiles,$codebase,
1.1051 raeburn 3995: $thumbwidth,$thumbheight,
1.1095 raeburn 3996: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3997: }
1.271 www 3998: }
3999:
4000: sub finishuserfileupload {
1.860 raeburn 4001: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4002: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4003: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4004: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4005:
1.860 raeburn 4006: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4007: $file=$fname;
4008: if ($fname=~m|/|) {
4009: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4010: $path.=$fnamepath.'/';
4011: }
1.259 www 4012: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4013: my $count;
4014: for ($count=4;$count<=$#parts;$count++) {
4015: $filepath.="/$parts[$count]";
4016: if ((-e $filepath)!=1) {
4017: mkdir($filepath,0777);
4018: }
4019: }
1.984 neumanie 4020:
1.258 www 4021: # Save the file
4022: {
1.1172.2.96 raeburn 4023: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4024: &logthis('Failed to create '.$filepath.'/'.$file);
4025: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4026: return '/adm/notfound.html';
4027: }
1.1090 raeburn 4028: if ($context eq 'overwrite') {
1.1117 foxr 4029: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4030: my $target = $filepath.'/'.$file;
4031: if (-e $source) {
4032: my @info = stat($source);
4033: if ($info[9] eq $env{'form.timestamp'}) {
4034: unless (&File::Copy::move($source,$target)) {
4035: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4036: return "Moving from $source failed";
4037: }
4038: } else {
4039: return "Temporary file: $source had unexpected date/time for last modification";
4040: }
4041: } else {
4042: return "Temporary file: $source missing";
4043: }
4044: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4045: &logthis('Failed to write to '.$filepath.'/'.$file);
4046: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4047: return '/adm/notfound.html';
4048: }
1.570 albertel 4049: close(FH);
1.1051 raeburn 4050: if ($resizewidth && $resizeheight) {
4051: my $mm = new File::MMagic;
4052: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4053: if ($mime_type =~ m{^image/}) {
4054: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4055: }
1.977 amueller 4056: }
1.258 www 4057: }
1.1152 raeburn 4058: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4059: if (ref($mimetype)) {
4060: if ($$mimetype eq '') {
4061: my $mm = new File::MMagic;
4062: my $type = $mm->checktype_filename($filepath.'/'.$file);
4063: $$mimetype = $type;
4064: }
4065: }
4066: }
1.1172.2.109 raeburn 4067: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4068: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4069: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4070: $allfiles,$codebase);
4071: unless ($parse_result eq 'ok') {
4072: &logthis('Failed to parse '.$filepath.$file.
4073: ' for embedded media: '.$parse_result);
4074: }
1.637 raeburn 4075: }
1.1172.2.109 raeburn 4076: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4077: my $format = $env{'form.scantron_format'};
4078: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4079: }
1.860 raeburn 4080: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4081: my $input = $filepath.'/'.$file;
4082: my $output = $filepath.'/'.'tn-'.$file;
4083: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4084: my @args = ('convert','-sample',$thumbsize,$input,$output);
4085: system({$args[0]} @args);
1.860 raeburn 4086: if (-e $filepath.'/'.'tn-'.$file) {
4087: $fetchthumb = 1;
4088: }
4089: }
1.858 raeburn 4090:
1.259 www 4091: # Notify homeserver to grep it
4092: #
1.984 neumanie 4093: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4094: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4095: if ($fetchresult eq 'ok') {
1.860 raeburn 4096: if ($fetchthumb) {
4097: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4098: if ($thumbresult ne 'ok') {
4099: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4100: $docuhome.': '.$thumbresult);
4101: }
4102: }
1.259 www 4103: #
1.258 www 4104: # Return the URL to it
1.494 albertel 4105: return '/uploaded/'.$path.$file;
1.263 www 4106: } else {
1.494 albertel 4107: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4108: ': '.$fetchresult);
1.263 www 4109: return '/adm/notfound.html';
1.858 raeburn 4110: }
1.493 albertel 4111: }
4112:
1.637 raeburn 4113: sub extract_embedded_items {
1.961 raeburn 4114: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4115: my @state = ();
1.1164 raeburn 4116: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4117: my %javafiles = (
4118: codebase => '',
4119: code => '',
4120: archive => ''
4121: );
4122: my %mediafiles = (
4123: src => '',
4124: movie => '',
4125: );
1.648 raeburn 4126: my $p;
4127: if ($content) {
4128: $p = HTML::LCParser->new($content);
4129: } else {
1.961 raeburn 4130: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4131: }
1.641 albertel 4132: while (my $t=$p->get_token()) {
1.640 albertel 4133: if ($t->[0] eq 'S') {
4134: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4135: push(@state, $tagname);
1.648 raeburn 4136: if (lc($tagname) eq 'allow') {
4137: &add_filetype($allfiles,$attr->{'src'},'src');
4138: }
1.640 albertel 4139: if (lc($tagname) eq 'img') {
4140: &add_filetype($allfiles,$attr->{'src'},'src');
4141: }
1.886 albertel 4142: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4143: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4144: &add_filetype($allfiles,$attr->{'href'},'href');
4145: }
1.886 albertel 4146: }
1.645 raeburn 4147: if (lc($tagname) eq 'script') {
1.1164 raeburn 4148: my $src;
1.645 raeburn 4149: if ($attr->{'archive'} =~ /\.jar$/i) {
4150: &add_filetype($allfiles,$attr->{'archive'},'archive');
4151: } else {
1.1164 raeburn 4152: if ($attr->{'src'} ne '') {
4153: $src = $attr->{'src'};
4154: &add_filetype($allfiles,$src,'src');
4155: }
4156: }
4157: my $text = $p->get_trimmed_text();
4158: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4159: my @swfargs = split(/,/,$1);
4160: foreach my $item (@swfargs) {
4161: $item =~ s/["']//g;
4162: $item =~ s/^\s+//;
4163: $item =~ s/\s+$//;
4164: }
4165: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4166: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4167: push(@{$related{$swfargs[0]}},$swfargs[2]);
4168: } else {
4169: $related{$swfargs[0]} = [$swfargs[2]];
4170: }
4171: }
1.645 raeburn 4172: }
4173: }
4174: if (lc($tagname) eq 'link') {
4175: if (lc($attr->{'rel'}) eq 'stylesheet') {
4176: &add_filetype($allfiles,$attr->{'href'},'href');
4177: }
4178: }
1.640 albertel 4179: if (lc($tagname) eq 'object' ||
4180: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4181: foreach my $item (keys(%javafiles)) {
4182: $javafiles{$item} = '';
4183: }
1.1164 raeburn 4184: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4185: $lastids{lc($tagname)} = $attr->{'id'};
4186: }
1.640 albertel 4187: }
4188: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4189: my $name = lc($attr->{'name'});
4190: foreach my $item (keys(%javafiles)) {
4191: if ($name eq $item) {
4192: $javafiles{$item} = $attr->{'value'};
4193: last;
4194: }
4195: }
1.1164 raeburn 4196: my $pathfrom;
1.640 albertel 4197: foreach my $item (keys(%mediafiles)) {
4198: if ($name eq $item) {
1.1164 raeburn 4199: $pathfrom = $attr->{'value'};
4200: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4201: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4202: last;
4203: }
4204: }
1.1164 raeburn 4205: if ($name eq 'flashvars') {
4206: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4207: }
4208: if ($pathfrom ne '') {
4209: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4210: $pathfrom);
4211: }
1.640 albertel 4212: }
4213: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4214: foreach my $item (keys(%javafiles)) {
4215: if ($attr->{$item}) {
4216: $javafiles{$item} = $attr->{$item};
4217: last;
4218: }
4219: }
4220: foreach my $item (keys(%mediafiles)) {
4221: if ($attr->{$item}) {
4222: &add_filetype($allfiles,$attr->{$item},$item);
4223: last;
4224: }
4225: }
1.1164 raeburn 4226: if (lc($tagname) eq 'embed') {
4227: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4228: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4229: $attr->{'src'});
4230: }
4231: }
1.640 albertel 4232: }
1.1172.2.35 raeburn 4233: if (lc($tagname) eq 'iframe') {
4234: my $src = $attr->{'src'} ;
4235: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4236: &add_filetype($allfiles,$src,'src');
4237: } elsif ($src =~ m{^/}) {
4238: if ($env{'request.course.id'}) {
4239: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4240: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4241: my $url = &hreflocation('',$fullpath);
4242: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4243: my $relpath = $1;
4244: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4245: &add_filetype($allfiles,$1,'src');
4246: }
4247: }
4248: }
4249: }
4250: }
1.1164 raeburn 4251: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4252: pop(@state);
1.1164 raeburn 4253: }
1.640 albertel 4254: } elsif ($t->[0] eq 'E') {
4255: my ($tagname) = ($t->[1]);
4256: if ($javafiles{'codebase'} ne '') {
4257: $javafiles{'codebase'} .= '/';
4258: }
4259: if (lc($tagname) eq 'applet' ||
4260: lc($tagname) eq 'object' ||
4261: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4262: ) {
4263: foreach my $item (keys(%javafiles)) {
4264: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4265: my $file=$javafiles{'codebase'}.$javafiles{$item};
4266: &add_filetype($allfiles,$file,$item);
4267: }
4268: }
4269: }
4270: pop @state;
4271: }
4272: }
1.1164 raeburn 4273: foreach my $id (sort(keys(%flashvars))) {
4274: if ($shockwave{$id} ne '') {
4275: my @pairs = split(/\&/,$flashvars{$id});
4276: foreach my $pair (@pairs) {
4277: my ($key,$value) = split(/\=/,$pair);
4278: if ($key eq 'thumb') {
4279: &add_filetype($allfiles,$value,$key);
4280: } elsif ($key eq 'content') {
4281: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4282: my ($ext) = ($value =~ /\.([^.]+)$/);
4283: if ($ext ne '') {
4284: &add_filetype($allfiles,$path.$value,$ext);
4285: }
4286: }
4287: }
4288: }
4289: }
1.637 raeburn 4290: return 'ok';
4291: }
4292:
1.639 albertel 4293: sub add_filetype {
4294: my ($allfiles,$file,$type)=@_;
4295: if (exists($allfiles->{$file})) {
4296: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4297: push(@{$allfiles->{$file}}, &escape($type));
4298: }
4299: } else {
4300: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4301: }
4302: }
4303:
1.1164 raeburn 4304: sub embedded_dependency {
4305: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4306: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4307: if (($identifier ne '') &&
4308: (ref($related->{$identifier}) eq 'ARRAY') &&
4309: ($pathfrom ne '')) {
4310: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4311: foreach my $dep (@{$related->{$identifier}}) {
4312: &add_filetype($allfiles,$path.$dep,'object');
4313: }
4314: }
4315: }
4316: return;
4317: }
4318:
1.1172.2.109 raeburn 4319: sub bubblesheet_converter {
4320: my ($cdom,$fullpath,$config,$format) = @_;
4321: if ((&domain($cdom) ne '') &&
4322: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4323: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4324: my (%csvcols,%csvoptions);
4325: if (ref($config->{'fields'}) eq 'HASH') {
4326: %csvcols = %{$config->{'fields'}};
4327: }
4328: if (ref($config->{'options'}) eq 'HASH') {
4329: %csvoptions = %{$config->{'options'}};
4330: }
4331: my %csvbynum = reverse(%csvcols);
4332: my %scantronconf = &get_scantron_config($format,$cdom);
4333: if (keys(%scantronconf)) {
4334: my %bynum = (
4335: $scantronconf{CODEstart} => 'CODEstart',
4336: $scantronconf{IDstart} => 'IDstart',
4337: $scantronconf{PaperID} => 'PaperID',
4338: $scantronconf{FirstName} => 'FirstName',
4339: $scantronconf{LastName} => 'LastName',
4340: $scantronconf{Qstart} => 'Qstart',
4341: );
4342: my @ordered;
4343: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4344: push(@ordered,$bynum{$item});
4345: }
4346: my %mapstart = (
4347: CODEstart => 'CODE',
4348: IDstart => 'ID',
4349: PaperID => 'PaperID',
4350: FirstName => 'FirstName',
4351: LastName => 'LastName',
4352: Qstart => 'FirstQuestion',
4353: );
4354: my %maplength = (
4355: CODEstart => 'CODElength',
4356: IDstart => 'IDlength',
4357: PaperID => 'PaperIDlength',
4358: FirstName => 'FirstNamelength',
4359: LastName => 'LastNamelength',
4360: );
4361: if (open(my $fh,'<',$fullpath)) {
4362: my $output;
4363: my %lettdig = &letter_to_digits();
4364: my %diglett = reverse(%lettdig);
4365: my $numletts = scalar(keys(%lettdig));
4366: my $num = 0;
4367: while (my $line=<$fh>) {
4368: $num ++;
4369: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4370: $line =~ s{[\r\n]+$}{};
4371: my %found;
1.1172.2.143 raeburn 4372: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4373: my ($qstart,$record);
4374: for (my $i=0; $i<@values; $i++) {
4375: if ((($qstart ne '') && ($i > $qstart)) ||
4376: ($csvbynum{$i} eq 'FirstQuestion')) {
4377: if ($values[$i] eq '') {
4378: $values[$i] = $scantronconf{'Qoff'};
4379: } elsif ($scantronconf{'Qon'} eq 'number') {
4380: if ($values[$i] =~ /^[A-Ja-j]$/) {
4381: $values[$i] = $lettdig{uc($values[$i])};
4382: }
4383: } elsif ($scantronconf{'Qon'} eq 'letter') {
4384: if ($values[$i] =~ /^[0-9]$/) {
4385: $values[$i] = $diglett{$values[$i]};
4386: }
4387: } else {
4388: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4389: my $digit;
4390: if ($values[$i] =~ /^[A-Ja-j]$/) {
4391: $digit = $lettdig{uc($values[$i])}-1;
4392: if ($values[$i] eq 'J') {
4393: $digit += $numletts;
4394: }
4395: } elsif ($values[$i] =~ /^[0-9]$/) {
4396: $digit = $values[$i]-1;
4397: if ($values[$i] eq '0') {
4398: $digit += $numletts;
4399: }
4400: }
4401: my $qval='';
4402: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4403: if ($j == $digit) {
4404: $qval .= $scantronconf{'Qon'};
4405: } else {
4406: $qval .= $scantronconf{'Qoff'};
4407: }
4408: }
4409: $values[$i] = $qval;
4410: }
4411: }
4412: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4413: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4414: }
4415: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4416: if ($numblank > 0) {
4417: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4418: }
4419: if ($csvbynum{$i} eq 'FirstQuestion') {
4420: $qstart = $i;
4421: $found{$csvbynum{$i}} = $values[$i];
4422: } else {
4423: $found{'FirstQuestion'} .= $values[$i];
4424: }
4425: } elsif (exists($csvbynum{$i})) {
4426: if ($csvoptions{'rem'}) {
4427: $values[$i] =~ s/^\s+//;
4428: }
4429: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4430: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4431: $values[$i] = '0'.$values[$i];
4432: }
4433: }
4434: $found{$csvbynum{$i}} = $values[$i];
4435: }
4436: }
4437: foreach my $item (@ordered) {
4438: my $currlength = 1+length($record);
4439: my $numspaces = $scantronconf{$item} - $currlength;
4440: if ($numspaces > 0) {
4441: $record .= (' ' x $numspaces);
4442: }
4443: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4444: unless ($item eq 'Qstart') {
4445: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4446: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4447: }
4448: }
4449: $record .= $found{$mapstart{$item}};
4450: }
4451: }
4452: $output .= "$record\n";
4453: }
4454: close($fh);
4455: if ($output) {
4456: if (open(my $fh,'>',$fullpath)) {
4457: print $fh $output;
4458: close($fh);
4459: }
4460: }
4461: }
4462: }
4463: return;
4464: }
4465: }
4466:
4467: sub letter_to_digits {
4468: my %lettdig = (
4469: A => 1,
4470: B => 2,
4471: C => 3,
4472: D => 4,
4473: E => 5,
4474: F => 6,
4475: G => 7,
4476: H => 8,
4477: I => 9,
4478: J => 0,
4479: );
4480: return %lettdig;
4481: }
4482:
4483: sub get_scantron_config {
4484: my ($which,$cdom) = @_;
4485: my @lines = &get_scantronformat_file($cdom);
4486: my %config;
4487: #FIXME probably should move to XML it has already gotten a bit much now
4488: foreach my $line (@lines) {
4489: my ($name,$descrip)=split(/:/,$line);
4490: if ($name ne $which ) { next; }
4491: chomp($line);
4492: my @config=split(/:/,$line);
4493: $config{'name'}=$config[0];
4494: $config{'description'}=$config[1];
4495: $config{'CODElocation'}=$config[2];
4496: $config{'CODEstart'}=$config[3];
4497: $config{'CODElength'}=$config[4];
4498: $config{'IDstart'}=$config[5];
4499: $config{'IDlength'}=$config[6];
4500: $config{'Qstart'}=$config[7];
4501: $config{'Qlength'}=$config[8];
4502: $config{'Qoff'}=$config[9];
4503: $config{'Qon'}=$config[10];
4504: $config{'PaperID'}=$config[11];
4505: $config{'PaperIDlength'}=$config[12];
4506: $config{'FirstName'}=$config[13];
4507: $config{'FirstNamelength'}=$config[14];
4508: $config{'LastName'}=$config[15];
4509: $config{'LastNamelength'}=$config[16];
4510: $config{'BubblesPerRow'}=$config[17];
4511: last;
4512: }
4513: return %config;
4514: }
4515:
4516: sub get_scantronformat_file {
4517: my ($cdom) = @_;
4518: if ($cdom eq '') {
4519: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4520: }
4521: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4522: my $gottab = 0;
4523: my @lines;
4524: if (ref($domconfig{'scantron'}) eq 'HASH') {
4525: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4526: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4527: if ($formatfile ne '-1') {
4528: @lines = split("\n",$formatfile,-1);
4529: $gottab = 1;
4530: }
4531: }
4532: }
4533: if (!$gottab) {
4534: my $confname = $cdom.'-domainconfig';
4535: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4536: my $formatfile = &getfile($default);
4537: if ($formatfile ne '-1') {
4538: @lines = split("\n",$formatfile,-1);
4539: $gottab = 1;
4540: }
4541: }
4542: if (!$gottab) {
4543: my @domains = ¤t_machine_domains();
4544: if (grep(/^\Q$cdom\E$/,@domains)) {
4545: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4546: @lines = <$fh>;
4547: close($fh);
4548: }
4549: } else {
4550: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4551: @lines = <$fh>;
4552: close($fh);
4553: }
4554: }
1.1172.2.150 raeburn 4555: chomp(@lines);
1.1172.2.109 raeburn 4556: }
4557: return @lines;
4558: }
4559:
1.493 albertel 4560: sub removeuploadedurl {
1.984 neumanie 4561: my ($url)=@_;
4562: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4563: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4564: }
4565:
4566: sub removeuserfile {
4567: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4568: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4569: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4570: if ($result eq 'ok') {
1.798 raeburn 4571: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4572: my $metafile = $fname.'.meta';
4573: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4574: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4575: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4576: my $sqlresult =
1.823 albertel 4577: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4578: 'portfolio_metadata',$group,
4579: 'delete');
1.798 raeburn 4580: }
4581: }
4582: return $result;
1.257 www 4583: }
1.15 www 4584:
1.530 albertel 4585: sub mkdiruserfile {
4586: my ($docuname,$docudom,$dir)=@_;
4587: my $home=&homeserver($docuname,$docudom);
4588: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4589: }
4590:
1.531 albertel 4591: sub renameuserfile {
4592: my ($docuname,$docudom,$old,$new)=@_;
4593: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4594: my $result = &reply("renameuserfile:$docudom:$docuname:".
4595: &escape("$old").':'.&escape("$new"),$home);
4596: if ($result eq 'ok') {
4597: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4598: my $oldmeta = $old.'.meta';
4599: my $newmeta = $new.'.meta';
4600: my $metaresult =
4601: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4602: my $url = "/uploaded/$docudom/$docuname/$old";
4603: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4604: my $sqlresult =
1.823 albertel 4605: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4606: 'portfolio_metadata',$group,
4607: 'delete');
1.798 raeburn 4608: }
4609: }
4610: return $result;
1.531 albertel 4611: }
4612:
1.14 www 4613: # ------------------------------------------------------------------------- Log
4614:
4615: sub log {
4616: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4617: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4618: }
4619:
4620: # ------------------------------------------------------------------ Course Log
1.352 www 4621: #
4622: # This routine flushes several buffers of non-mission-critical nature
4623: #
1.157 www 4624:
4625: sub flushcourselogs {
1.352 www 4626: &logthis('Flushing log buffers');
4627: #
4628: # course logs
4629: # This is a log of all transactions in a course, which can be used
4630: # for data mining purposes
4631: #
4632: # It also collects the courseid database, which lists last transaction
4633: # times and course titles for all courseids
4634: #
4635: my %courseidbuffer=();
1.921 raeburn 4636: foreach my $crsid (keys(%courselogs)) {
1.352 www 4637: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4638: &escape($courselogs{$crsid}),
4639: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4640: delete $courselogs{$crsid};
4641: } else {
4642: &logthis('Failed to flush log buffer for '.$crsid);
4643: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4644: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4645: " exceeded maximum size, deleting.</font>");
4646: delete $courselogs{$crsid};
4647: }
1.352 www 4648: }
1.920 raeburn 4649: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4650: 'description' => $coursedescrbuf{$crsid},
4651: 'inst_code' => $courseinstcodebuf{$crsid},
4652: 'type' => $coursetypebuf{$crsid},
4653: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4654: };
1.191 harris41 4655: }
1.352 www 4656: #
4657: # Write course id database (reverse lookup) to homeserver of courses
4658: # Is used in pickcourse
4659: #
1.840 albertel 4660: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4661: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4662: $courseidbuffer{$crs_home},
4663: $crs_home,'timeonly');
1.352 www 4664: }
4665: #
4666: # File accesses
4667: # Writes to the dynamic metadata of resources to get hit counts, etc.
4668: #
1.449 matthew 4669: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4670: if ($entry =~ /___count$/) {
4671: my ($dom,$name);
1.807 albertel 4672: ($dom,$name,undef)=
1.811 albertel 4673: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4674: if (! defined($dom) || $dom eq '' ||
4675: ! defined($name) || $name eq '') {
1.620 albertel 4676: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4677: #
4678: # FIXME 11/29/2021
4679: # Typo in rev. 1.458 (2003/12/09)??
4680: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4681: #
4682: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4683: # $dom and $name will always be null, so the &inc() call will default to storing this data
4684: # in a nohist_accesscount.db file for the user rather than the course.
4685: #
4686: # That said there is a lot of noise in the data being stored.
4687: # So counts for prtspool/ and adm/ etc. are recorded.
4688: #
4689: # A review of which items ending '___count' are written to %accesshash should likely be
4690: # made before deciding whether to set these to 'course.' instead of 'request.'
4691: #
4692: # Under the current scheme each user receives a nohist_accesscount.db file listing
4693: # accesses for things which are not published resources, regardless of course, and
4694: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4695: # anyone in the course for things which are not published resources.
4696: #
4697: # For an author, nohist_accesscount.db ends up having records for other items
4698: # mixed up with the legitimate access counts for the author's published resources.
4699: #
1.620 albertel 4700: $dom = $env{'request.'.$cid.'.domain'};
4701: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4702: }
1.450 matthew 4703: my $value = $accesshash{$entry};
4704: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4705: my %temphash=($url => $value);
1.449 matthew 4706: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4707: if ($result eq 'ok') {
4708: delete $accesshash{$entry};
4709: }
4710: } else {
1.811 albertel 4711: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4712: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4713: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4714: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4715: delete $accesshash{$entry};
4716: }
1.185 www 4717: }
1.191 harris41 4718: }
1.352 www 4719: #
4720: # Roles
4721: # Reverse lookup of user roles for course faculty/staff and co-authorship
4722: #
1.800 albertel 4723: foreach my $entry (keys(%userrolehash)) {
1.351 www 4724: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4725: split(/\:/,$entry);
4726: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4727: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4728: $rudom,$runame) eq 'ok') {
4729: delete $userrolehash{$entry};
4730: }
4731: }
1.662 raeburn 4732: #
1.1172.2.90 raeburn 4733: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4734: #
4735: my %domrolebuffer = ();
1.1000 raeburn 4736: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4737: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4738: if ($domrolebuffer{$rudom}) {
4739: $domrolebuffer{$rudom}.='&'.&escape($entry).
4740: '='.&escape($domainrolehash{$entry});
4741: } else {
4742: $domrolebuffer{$rudom}.=&escape($entry).
4743: '='.&escape($domainrolehash{$entry});
4744: }
4745: delete $domainrolehash{$entry};
4746: }
4747: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4748: my %servers;
4749: if (defined(&domain($dom,'primary'))) {
4750: my $primary=&domain($dom,'primary');
4751: my $hostname=&hostname($primary);
4752: $servers{$primary} = $hostname;
4753: } else {
4754: %servers = &get_servers($dom,'library');
4755: }
1.841 albertel 4756: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4757: if (&reply('domroleput:'.$dom.':'.
4758: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4759: last;
4760: } else {
1.841 albertel 4761: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4762: }
1.662 raeburn 4763: }
4764: }
1.186 www 4765: $dumpcount++;
1.157 www 4766: }
4767:
4768: sub courselog {
4769: my $what=shift;
1.158 www 4770: $what=time.':'.$what;
1.620 albertel 4771: unless ($env{'request.course.id'}) { return ''; }
4772: $coursedombuf{$env{'request.course.id'}}=
4773: $env{'course.'.$env{'request.course.id'}.'.domain'};
4774: $coursenumbuf{$env{'request.course.id'}}=
4775: $env{'course.'.$env{'request.course.id'}.'.num'};
4776: $coursehombuf{$env{'request.course.id'}}=
4777: $env{'course.'.$env{'request.course.id'}.'.home'};
4778: $coursedescrbuf{$env{'request.course.id'}}=
4779: $env{'course.'.$env{'request.course.id'}.'.description'};
4780: $courseinstcodebuf{$env{'request.course.id'}}=
4781: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4782: $courseownerbuf{$env{'request.course.id'}}=
4783: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4784: $coursetypebuf{$env{'request.course.id'}}=
4785: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4786: if (defined $courselogs{$env{'request.course.id'}}) {
4787: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4788: } else {
1.620 albertel 4789: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4790: }
1.620 albertel 4791: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4792: &flushcourselogs();
4793: }
1.158 www 4794: }
4795:
4796: sub courseacclog {
4797: my $fnsymb=shift;
1.620 albertel 4798: unless ($env{'request.course.id'}) { return ''; }
4799: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4800: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4801: $what.=':POST';
1.583 matthew 4802: # FIXME: Probably ought to escape things....
1.800 albertel 4803: foreach my $key (keys(%env)) {
4804: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4805: my $formitem = $1;
4806: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4807: $what.=':'.$formitem.'='.$env{$key};
4808: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4809: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4810: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4811: } else {
4812: $what.=':'.$formitem.'='.$env{$key};
4813: }
1.975 raeburn 4814: }
1.158 www 4815: }
1.191 harris41 4816: }
1.583 matthew 4817: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4818: # FIXME: We should not be depending on a form parameter that someone
4819: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4820: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4821: $what.= ':POST';
4822: # FIXME: Probably ought to escape things....
4823: foreach my $element ('courseexp','crsfulltext','crsrelated',
4824: 'crsdiscuss') {
1.620 albertel 4825: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4826: }
4827: }
1.158 www 4828: }
4829: &courselog($what);
1.149 www 4830: }
4831:
1.185 www 4832: sub countacc {
4833: my $url=&declutter(shift);
1.458 matthew 4834: return if (! defined($url) || $url eq '');
1.620 albertel 4835: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4836: #
4837: # Mark that this url was used in this course
4838: #
1.620 albertel 4839: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4840: #
4841: # Increase the access count for this resource in this child process
4842: #
1.281 www 4843: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4844: $accesshash{$key}++;
1.185 www 4845: }
1.349 www 4846:
1.361 www 4847: sub linklog {
4848: my ($from,$to)=@_;
4849: $from=&declutter($from);
4850: $to=&declutter($to);
4851: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4852: $accesshash{$to.'___'.$from.'___goto'}=1;
4853: }
1.1160 www 4854:
4855: sub statslog {
4856: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4857: if ($users<2) { return; }
4858: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4859: 'course' => $env{'request.course.id'},
4860: 'sections' => '"all"',
4861: 'num_students' => $users,
4862: 'part' => $part,
4863: 'symb' => $symb,
4864: 'mean_tries' => $av_attempts,
4865: 'deg_of_diff' => $degdiff});
4866: foreach my $key (keys(%dynstore)) {
4867: $accesshash{$key}=$dynstore{$key};
4868: }
4869: }
1.361 www 4870:
1.349 www 4871: sub userrolelog {
4872: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4873: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4874: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4875: $userrolehash
4876: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4877: =$tend.':'.$tstart;
1.662 raeburn 4878: }
1.1169 droeschl 4879: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4880: $userrolehash
4881: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4882: =$tend.':'.$tstart;
4883: }
1.1172.2.90 raeburn 4884: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4885: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4886: $domainrolehash
4887: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4888: = $tend.':'.$tstart;
4889: }
1.351 www 4890: }
4891:
1.957 raeburn 4892: sub courserolelog {
4893: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4894: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4895: my $cdom = $1;
4896: my $cnum = $2;
4897: my $sec = $3;
4898: my $namespace = 'rolelog';
4899: my %storehash = (
4900: role => $trole,
4901: start => $tstart,
4902: end => $tend,
4903: selfenroll => $selfenroll,
4904: context => $context,
4905: );
4906: if ($trole eq 'gr') {
4907: $namespace = 'groupslog';
4908: $storehash{'group'} = $sec;
4909: } else {
4910: $storehash{'section'} = $sec;
4911: }
4912: &write_log('course',$namespace,\%storehash,$delflag,$username,
4913: $domain,$cnum,$cdom);
4914: if (($trole ne 'st') || ($sec ne '')) {
4915: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4916: }
4917: }
4918: return;
4919: }
4920:
1.1172.2.9 raeburn 4921: sub domainrolelog {
4922: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4923: if ($area =~ m{^/($match_domain)/$}) {
4924: my $cdom = $1;
4925: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4926: my $namespace = 'rolelog';
4927: my %storehash = (
4928: role => $trole,
4929: start => $tstart,
4930: end => $tend,
4931: context => $context,
4932: );
4933: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4934: $domain,$domconfiguser,$cdom);
4935: }
4936: return;
4937:
4938: }
4939:
4940: sub coauthorrolelog {
4941: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4942: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4943: my $audom = $1;
4944: my $auname = $2;
4945: my $namespace = 'rolelog';
4946: my %storehash = (
4947: role => $trole,
4948: start => $tstart,
4949: end => $tend,
4950: context => $context,
4951: );
4952: &write_log('author',$namespace,\%storehash,$delflag,$username,
4953: $domain,$auname,$audom);
4954: }
4955: return;
4956: }
4957:
1.351 www 4958: sub get_course_adv_roles {
1.948 raeburn 4959: my ($cid,$codes) = @_;
1.620 albertel 4960: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4961: my %coursehash=&coursedescription($cid);
1.988 raeburn 4962: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4963: my %nothide=();
1.800 albertel 4964: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4965: if ($user !~ /:/) {
4966: $nothide{join(':',split(/[\@]/,$user))}=1;
4967: } else {
4968: $nothide{$user}=1;
4969: }
1.470 www 4970: }
1.1172.2.23 raeburn 4971: my @possdoms = ($coursehash{'domain'});
4972: if ($coursehash{'checkforpriv'}) {
4973: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4974: }
1.351 www 4975: my %returnhash=();
4976: my %dumphash=
4977: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4978: my $now=time;
1.997 raeburn 4979: my %privileged;
1.1000 raeburn 4980: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4981: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4982: if (($tstart) && ($tstart<0)) { next; }
4983: if (($tend) && ($tend<$now)) { next; }
4984: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4985: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4986: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4987: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4988: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4989: if ($role eq 'cr') { next; }
1.948 raeburn 4990: if ($codes) {
4991: if ($section) { $role .= ':'.$section; }
4992: if ($returnhash{$role}) {
4993: $returnhash{$role}.=','.$username.':'.$domain;
4994: } else {
4995: $returnhash{$role}=$username.':'.$domain;
4996: }
1.351 www 4997: } else {
1.988 raeburn 4998: my $key=&plaintext($role,$crstype);
1.973 bisitz 4999: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5000: if ($returnhash{$key}) {
5001: $returnhash{$key}.=','.$username.':'.$domain;
5002: } else {
5003: $returnhash{$key}=$username.':'.$domain;
5004: }
1.351 www 5005: }
1.948 raeburn 5006: }
1.400 www 5007: return %returnhash;
5008: }
5009:
5010: sub get_my_roles {
1.937 raeburn 5011: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5012: unless (defined($uname)) { $uname=$env{'user.name'}; }
5013: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5014: my (%dumphash,%nothide);
1.1086 raeburn 5015: if ($context eq 'userroles') {
1.1166 raeburn 5016: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5017: } else {
1.1172.2.23 raeburn 5018: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5019: if ($hidepriv) {
5020: my %coursehash=&coursedescription($udom.'_'.$uname);
5021: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5022: if ($user !~ /:/) {
5023: $nothide{join(':',split(/[\@]/,$user))} = 1;
5024: } else {
5025: $nothide{$user} = 1;
5026: }
5027: }
5028: }
1.858 raeburn 5029: }
1.400 www 5030: my %returnhash=();
5031: my $now=time;
1.999 raeburn 5032: my %privileged;
1.800 albertel 5033: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5034: my ($role,$tend,$tstart);
5035: if ($context eq 'userroles') {
1.1149 raeburn 5036: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5037: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5038: } else {
5039: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5040: }
1.400 www 5041: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5042: my $status = 'active';
1.939 raeburn 5043: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5044: $status = 'previous';
5045: }
5046: if (($tstart) && ($now<$tstart)) {
5047: $status = 'future';
5048: }
5049: if (ref($types) eq 'ARRAY') {
5050: if (!grep(/^\Q$status\E$/,@{$types})) {
5051: next;
5052: }
5053: } else {
5054: if ($status ne 'active') {
5055: next;
5056: }
5057: }
1.867 raeburn 5058: my ($rolecode,$username,$domain,$section,$area);
5059: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5060: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5061: (undef,$domain,$username,$section) = split(/\//,$area);
5062: } else {
5063: ($role,$username,$domain,$section) = split(/\:/,$entry);
5064: }
1.832 raeburn 5065: if (ref($roledoms) eq 'ARRAY') {
5066: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5067: next;
5068: }
5069: }
5070: if (ref($roles) eq 'ARRAY') {
5071: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5072: if ($role =~ /^cr\//) {
5073: if (!grep(/^cr$/,@{$roles})) {
5074: next;
5075: }
1.1104 raeburn 5076: } elsif ($role =~ /^gr\//) {
5077: if (!grep(/^gr$/,@{$roles})) {
5078: next;
5079: }
1.922 raeburn 5080: } else {
5081: next;
5082: }
1.832 raeburn 5083: }
1.867 raeburn 5084: }
1.937 raeburn 5085: if ($hidepriv) {
1.1172.2.23 raeburn 5086: my @privroles = ('dc','su');
1.999 raeburn 5087: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5088: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5089: } else {
1.1172.2.23 raeburn 5090: my $possdoms = [$domain];
5091: if (ref($roledoms) eq 'ARRAY') {
5092: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5093: }
1.1172.2.23 raeburn 5094: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5095: if (!$nothide{$username.':'.$domain}) {
5096: next;
5097: }
5098: }
1.937 raeburn 5099: }
5100: }
1.933 raeburn 5101: if ($withsec) {
5102: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5103: $tstart.':'.$tend;
5104: } else {
5105: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5106: }
1.832 raeburn 5107: }
1.373 www 5108: return %returnhash;
1.399 www 5109: }
5110:
1.1172.2.89 raeburn 5111: sub get_all_adhocroles {
5112: my ($dom) = @_;
5113: my @roles_by_num = ();
5114: my %domdefaults = &get_domain_defaults($dom);
5115: my (%description,%access_in_dom,%access_info);
5116: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5117: my $count = 0;
5118: my %domcurrent = %{$domdefaults{'adhocroles'}};
5119: my %ordered;
5120: foreach my $role (sort(keys(%domcurrent))) {
5121: my ($order,$desc,$access_in_dom);
5122: if (ref($domcurrent{$role}) eq 'HASH') {
5123: $order = $domcurrent{$role}{'order'};
5124: $desc = $domcurrent{$role}{'desc'};
5125: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5126: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5127: }
5128: if ($order eq '') {
5129: $order = $count;
5130: }
5131: $ordered{$order} = $role;
5132: if ($desc ne '') {
5133: $description{$role} = $desc;
5134: } else {
5135: $description{$role}= $role;
5136: }
5137: $count++;
5138: }
5139: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5140: push(@roles_by_num,$ordered{$item});
5141: }
5142: }
5143: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5144: }
5145:
5146: sub get_my_adhocroles {
5147: my ($cid,$checkreg) = @_;
5148: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5149: if ($env{'request.course.id'} eq $cid) {
5150: $cdom = $env{'course.'.$cid.'.domain'};
5151: $cnum = $env{'course.'.$cid.'.num'};
5152: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5153: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5154: $cdom = $1;
5155: $cnum = $2;
5156: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5157: $cdom,$cnum);
5158: }
5159: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5160: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5161: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5162: if ($rosterhash{$user} ne '') {
5163: my $type = (split(/:/,$rosterhash{$user}))[5];
5164: return ([],{}) if ($type eq 'auto');
5165: }
5166: }
5167: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5168: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5169: my $then=$env{'user.login.time'};
5170: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5171: if (!$update) {
5172: $update = $then;
5173: }
5174: my @liveroles;
5175: foreach my $role ('dh','da') {
5176: if ($env{"user.role.$role./$cdom/"}) {
5177: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5178: my $limit = $update;
5179: if ($env{'request.role'} eq "$role./$cdom/") {
5180: $limit = $then;
5181: }
5182: my $activerole = 1;
5183: if ($tstart && $tstart>$limit) { $activerole = 0; }
5184: if ($tend && $tend <$limit) { $activerole = 0; }
5185: if ($activerole) {
5186: push(@liveroles,$role);
5187: }
5188: }
5189: }
5190: if (@liveroles) {
1.1172.2.89 raeburn 5191: if (&homeserver($cnum,$cdom) ne 'no_host') {
5192: my ($accessref,$accessinfo,%access_in_dom);
5193: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5194: if (ref($roles_by_num) eq 'ARRAY') {
5195: if (@{$roles_by_num}) {
5196: my %settings;
5197: if ($env{'request.course.id'} eq $cid) {
5198: foreach my $envkey (keys(%env)) {
5199: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5200: $settings{$1} = $env{$envkey};
5201: }
5202: }
5203: } else {
5204: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5205: }
5206: my %setincrs;
5207: if ($settings{'internal.adhocaccess'}) {
5208: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5209: }
5210: my @statuses;
5211: if ($env{'environment.inststatus'}) {
5212: @statuses = split(/,/,$env{'environment.inststatus'});
5213: }
5214: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5215: if (ref($accessref) eq 'HASH') {
5216: %access_in_dom = %{$accessref};
5217: }
5218: foreach my $role (@{$roles_by_num}) {
5219: my ($curraccess,@okstatus,@personnel);
5220: if ($setincrs{$role}) {
5221: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5222: if ($curraccess eq 'status') {
5223: @okstatus = split(/\&/,$rest);
5224: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5225: @personnel = split(/\&/,$rest);
5226: }
5227: } else {
5228: $curraccess = $access_in_dom{$role};
5229: if (ref($accessinfo) eq 'HASH') {
5230: if ($curraccess eq 'status') {
5231: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5232: @okstatus = @{$accessinfo->{$role}};
5233: }
5234: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5235: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5236: @personnel = @{$accessinfo->{$role}};
5237: }
5238: }
5239: }
5240: }
5241: if ($curraccess eq 'none') {
5242: next;
5243: } elsif ($curraccess eq 'all') {
5244: push(@possroles,$role);
1.1172.2.90 raeburn 5245: } elsif ($curraccess eq 'dh') {
5246: if (grep(/^dh$/,@liveroles)) {
5247: push(@possroles,$role);
5248: } else {
5249: next;
5250: }
5251: } elsif ($curraccess eq 'da') {
5252: if (grep(/^da$/,@liveroles)) {
5253: push(@possroles,$role);
5254: } else {
5255: next;
5256: }
1.1172.2.89 raeburn 5257: } elsif ($curraccess eq 'status') {
5258: if (@okstatus) {
5259: if (!@statuses) {
5260: if (grep(/^default$/,@okstatus)) {
5261: push(@possroles,$role);
5262: }
5263: } else {
5264: foreach my $status (@okstatus) {
5265: if (grep(/^\Q$status\E$/,@statuses)) {
5266: push(@possroles,$role);
5267: last;
5268: }
5269: }
5270: }
5271: }
5272: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5273: if (grep(/^\Q$user\E$/,@personnel)) {
5274: if ($curraccess eq 'exc') {
5275: push(@possroles,$role);
5276: }
5277: } elsif ($curraccess eq 'inc') {
5278: push(@possroles,$role);
5279: }
5280: }
5281: }
5282: }
5283: }
5284: }
5285: }
5286: }
5287: }
5288: unless (ref($description) eq 'HASH') {
5289: if (ref($roles_by_num) eq 'ARRAY') {
5290: my %desc;
5291: map { $desc{$_} = $_; } (@{$roles_by_num});
5292: $description = \%desc;
5293: } else {
5294: $description = {};
5295: }
5296: }
5297: return (\@possroles,$description);
5298: }
5299:
1.399 www 5300: # ----------------------------------------------------- Frontpage Announcements
5301: #
5302: #
5303:
5304: sub postannounce {
5305: my ($server,$text)=@_;
1.844 albertel 5306: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5307: unless ($text=~/\w/) { $text=''; }
5308: return &reply('setannounce:'.&escape($text),$server);
5309: }
5310:
5311: sub getannounce {
1.448 albertel 5312:
1.1172.2.96 raeburn 5313: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5314: my $announcement='';
1.800 albertel 5315: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5316: close($fh);
1.399 www 5317: if ($announcement=~/\w/) {
5318: return
5319: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5320: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5321: } else {
5322: return '';
5323: }
5324: } else {
5325: return '';
5326: }
1.351 www 5327: }
1.353 www 5328:
5329: # ---------------------------------------------------------- Course ID routines
5330: # Deal with domain's nohist_courseid.db files
5331: #
5332:
5333: sub courseidput {
1.921 raeburn 5334: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5335: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5336: my $outcome;
5337: if ($caller eq 'timeonly') {
5338: my $cids = '';
5339: foreach my $item (keys(%$storehash)) {
5340: $cids.=&escape($item).'&';
5341: }
5342: $cids=~s/\&$//;
5343: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5344: $coursehome);
5345: } else {
5346: my $items = '';
5347: foreach my $item (keys(%$storehash)) {
5348: $items.= &escape($item).'='.
5349: &freeze_escape($$storehash{$item}).'&';
5350: }
5351: $items=~s/\&$//;
5352: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5353: $coursehome);
1.918 raeburn 5354: }
5355: if ($outcome eq 'unknown_cmd') {
5356: my $what;
5357: foreach my $cid (keys(%$storehash)) {
5358: $what .= &escape($cid).'=';
1.921 raeburn 5359: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5360: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5361: }
5362: $what =~ s/\:$/&/;
5363: }
5364: $what =~ s/\&$//;
5365: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5366: } else {
5367: return $outcome;
5368: }
1.353 www 5369: }
5370:
5371: sub courseiddump {
1.921 raeburn 5372: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5373: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5374: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5375: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5376: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5377: my $as_hash = 1;
5378: my %returnhash;
5379: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5380: my %libserv = &all_library();
5381: foreach my $tryserver (keys(%libserv)) {
5382: if ( ( $hostidflag == 1
5383: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5384: || (!defined($hostidflag)) ) {
5385:
1.918 raeburn 5386: if (($domfilter eq '') ||
5387: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5388: my $rep;
5389: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5390: $rep = &LONCAPA::Lond::dump_course_id_handler(
5391: join(":", (&host_domain($tryserver), $sincefilter,
5392: &escape($descfilter), &escape($instcodefilter),
5393: &escape($ownerfilter), &escape($coursefilter),
5394: &escape($typefilter), &escape($regexp_ok),
5395: $as_hash, &escape($selfenrollonly),
5396: &escape($catfilter), $showhidden, $caller,
5397: &escape($cloner), &escape($cc_clone), $cloneonly,
5398: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5399: &escape($creationcontext),$domcloner,$hasuniquecode,
5400: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5401: } else {
5402: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5403: $sincefilter.':'.&escape($descfilter).':'.
5404: &escape($instcodefilter).':'.&escape($ownerfilter).
5405: ':'.&escape($coursefilter).':'.&escape($typefilter).
5406: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5407: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5408: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5409: &escape($cc_clone).':'.$cloneonly.':'.
5410: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5411: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5412: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5413: }
5414:
1.918 raeburn 5415: my @pairs=split(/\&/,$rep);
5416: foreach my $item (@pairs) {
5417: my ($key,$value)=split(/\=/,$item,2);
5418: $key = &unescape($key);
5419: next if ($key =~ /^error: 2 /);
5420: my $result = &thaw_unescape($value);
5421: if (ref($result) eq 'HASH') {
5422: $returnhash{$key}=$result;
5423: } else {
1.921 raeburn 5424: my @responses = split(/:/,$value);
5425: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5426: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5427: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5428: }
1.1008 raeburn 5429: }
1.353 www 5430: }
5431: }
5432: }
5433: }
5434: return %returnhash;
5435: }
5436:
1.1055 raeburn 5437: sub courselastaccess {
5438: my ($cdom,$cnum,$hostidref) = @_;
5439: my %returnhash;
5440: if ($cdom && $cnum) {
5441: my $chome = &homeserver($cnum,$cdom);
5442: if ($chome ne 'no_host') {
5443: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5444: &extract_lastaccess(\%returnhash,$rep);
5445: }
5446: } else {
5447: if (!$cdom) { $cdom=''; }
5448: my %libserv = &all_library();
5449: foreach my $tryserver (keys(%libserv)) {
5450: if (ref($hostidref) eq 'ARRAY') {
5451: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5452: }
5453: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5454: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5455: &extract_lastaccess(\%returnhash,$rep);
5456: }
5457: }
5458: }
5459: return %returnhash;
5460: }
5461:
5462: sub extract_lastaccess {
5463: my ($returnhash,$rep) = @_;
5464: if (ref($returnhash) eq 'HASH') {
5465: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5466: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5467: $rep eq '') {
5468: my @pairs=split(/\&/,$rep);
5469: foreach my $item (@pairs) {
5470: my ($key,$value)=split(/\=/,$item,2);
5471: $key = &unescape($key);
5472: next if ($key =~ /^error: 2 /);
5473: $returnhash->{$key} = &thaw_unescape($value);
5474: }
5475: }
5476: }
5477: return;
5478: }
5479:
1.658 raeburn 5480: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5481:
5482: sub dcmailput {
1.685 raeburn 5483: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5484: my $status = &Apache::lonnet::critical(
1.740 www 5485: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5486: &escape($message),$server);
1.662 raeburn 5487: return $status;
5488: }
5489:
1.658 raeburn 5490: sub dcmaildump {
5491: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5492: my %returnhash=();
1.846 albertel 5493:
5494: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5495: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5496: &escape($enddate).':';
5497: my @esc_senders=map { &escape($_)} @$senders;
5498: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5499: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5500: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5501: if (($key) && ($value)) {
5502: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5503: }
5504: }
5505: }
5506: return %returnhash;
5507: }
1.662 raeburn 5508: # ---------------------------------------------------------- Domain roles
5509:
5510: sub get_domain_roles {
5511: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5512: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5513: $startdate = '.';
5514: }
1.1018 raeburn 5515: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5516: $enddate = '.';
5517: }
1.922 raeburn 5518: my $rolelist;
5519: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5520: $rolelist = join('&',@{$roles});
1.922 raeburn 5521: }
1.662 raeburn 5522: my %personnel = ();
1.841 albertel 5523:
5524: my %servers = &get_servers($dom,'library');
5525: foreach my $tryserver (keys(%servers)) {
5526: %{$personnel{$tryserver}}=();
5527: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5528: &escape($startdate).':'.
5529: &escape($enddate).':'.
5530: &escape($rolelist), $tryserver))) {
5531: my ($key,$value) = split(/\=/,$line,2);
5532: if (($key) && ($value)) {
5533: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5534: }
5535: }
1.662 raeburn 5536: }
5537: return %personnel;
5538: }
1.658 raeburn 5539:
1.1172.2.89 raeburn 5540: sub get_active_domroles {
5541: my ($dom,$roles) = @_;
5542: return () unless (ref($roles) eq 'ARRAY');
5543: my $now = time;
5544: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5545: my %domroles;
5546: foreach my $server (keys(%dompersonnel)) {
5547: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5548: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5549: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5550: }
5551: }
5552: return %domroles;
5553: }
5554:
1.1057 www 5555: # ----------------------------------------------------------- Interval timing
1.149 www 5556:
1.1153 www 5557: {
5558: # Caches needed for speedup of navmaps
5559: # We don't want to cache this for very long at all (5 seconds at most)
5560: #
5561: # The user for whom we cache
5562: my $cachedkey='';
5563: # The cached times for this user
5564: my %cachedtimes=();
5565: # When this was last done
1.1172.2.66 raeburn 5566: my $cachedtime='';
1.1153 www 5567:
5568: sub load_all_first_access {
1.1154 raeburn 5569: my ($uname,$udom)=@_;
1.1156 www 5570: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5571: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5572: return;
5573: }
5574: $cachedtime=time;
5575: $cachedkey=$uname.':'.$udom;
5576: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5577: }
5578:
1.504 albertel 5579: sub get_first_access {
1.1162 raeburn 5580: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5581: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5582: if ($argsymb) { $symb=$argsymb; }
5583: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5584: if ($argmap) { $map = $argmap; }
1.926 albertel 5585: if ($type eq 'course') {
5586: $res='course';
5587: } elsif ($type eq 'map') {
1.588 albertel 5588: $res=&symbread($map);
5589: } else {
5590: $res=$symb;
5591: }
1.1153 www 5592: &load_all_first_access($uname,$udom);
5593: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5594: }
5595:
5596: sub set_first_access {
1.1162 raeburn 5597: my ($type,$interval)=@_;
1.790 albertel 5598: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5599: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5600: if ($type eq 'course') {
5601: $res='course';
5602: } elsif ($type eq 'map') {
1.588 albertel 5603: $res=&symbread($map);
5604: } else {
5605: $res=$symb;
5606: }
1.1153 www 5607: $cachedkey='';
1.1162 raeburn 5608: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5609: if ($firstaccess) {
5610: &logthis("First access time already set ($firstaccess) when attempting ".
5611: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5612: "in $courseid");
5613: return 'already_set';
5614: } else {
1.1162 raeburn 5615: my $start = time;
5616: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5617: $udom,$uname);
5618: if ($putres eq 'ok') {
5619: &put('timerinterval',{"$courseid\0$res"=>$interval},
5620: $udom,$uname);
5621: &appenv(
5622: {
5623: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5624: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5625: }
5626: );
1.1172.2.97 raeburn 5627: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5628: $cachedtimes{"$courseid\0$res"} = $start;
5629: }
1.1172.2.102 raeburn 5630: } elsif ($putres ne 'refused') {
5631: &logthis("Result: $putres when attempting to set first access time ".
5632: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5633: }
5634: return $putres;
1.505 albertel 5635: }
5636: return 'already_set';
1.504 albertel 5637: }
1.1153 www 5638: }
1.1172.2.32 raeburn 5639:
5640: sub checkout {
5641: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5642: my $now=time;
5643: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5644: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5645: my $infostr=&escape(
5646: 'CHECKOUTTOKEN&'.
5647: $tuname.'&'.
5648: $tudom.'&'.
5649: $tcrsid.'&'.
5650: $symb.'&'.
1.1172.2.134 raeburn 5651: $now.'&'.$ip);
1.1172.2.32 raeburn 5652: my $token=&reply('tmpput:'.$infostr,$lonhost);
5653: if ($token=~/^error\:/) {
5654: &logthis("<font color=\"blue\">WARNING: ".
5655: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5656: "</font>");
5657: return '';
5658: }
5659:
5660: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5661: $token=~tr/a-z/A-Z/;
5662:
5663: my %infohash=('resource.0.outtoken' => $token,
5664: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5665: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5666:
5667: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5668: return '';
5669: } else {
5670: &logthis("<font color=\"blue\">WARNING: ".
5671: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5672: "</font>");
5673: }
5674:
5675: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5676: &escape('Checkout '.$infostr.' - '.
5677: $token)) ne 'ok') {
5678: return '';
5679: } else {
5680: &logthis("<font color=\"blue\">WARNING: ".
5681: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5682: "</font>");
5683: }
5684: return $token;
5685: }
5686:
5687: # ------------------------------------------------------------ Check in an item
5688:
5689: sub checkin {
5690: my $token=shift;
5691: my $now=time;
5692: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5693: $lonhost=~tr/A-Z/a-z/;
5694: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5695: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5696: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5697: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5698: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5699:
5700: unless (($tuname) && ($tudom)) {
5701: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5702: return '';
5703: }
5704:
5705: unless (&allowed('mgr',$tcrsid)) {
5706: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5707: $env{'user.name'}.' - '.$env{'user.domain'});
5708: return '';
5709: }
5710:
5711: my %infohash=('resource.0.intoken' => $token,
5712: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5713: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5714:
5715: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5716: return '';
5717: }
5718:
5719: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5720: &escape('Checkin - '.$token)) ne 'ok') {
5721: return '';
5722: }
5723:
5724: return ($symb,$tuname,$tudom,$tcrsid);
5725: }
5726:
1.110 www 5727: # --------------------------------------------- Set Expire Date for Spreadsheet
5728:
5729: sub expirespread {
5730: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5731: my $cid=$env{'request.course.id'};
1.110 www 5732: if ($cid) {
5733: my $now=time;
5734: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5735: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5736: $env{'course.'.$cid.'.num'}.
1.110 www 5737: ':nohist_expirationdates:'.
5738: &escape($key).'='.$now,
1.620 albertel 5739: $env{'course.'.$cid.'.home'})
1.110 www 5740: }
5741: return 'ok';
1.14 www 5742: }
5743:
1.109 www 5744: # ----------------------------------------------------- Devalidate Spreadsheets
5745:
5746: sub devalidate {
1.325 www 5747: my ($symb,$uname,$udom)=@_;
1.620 albertel 5748: my $cid=$env{'request.course.id'};
1.109 www 5749: if ($cid) {
1.391 matthew 5750: # delete the stored spreadsheets for
5751: # - the student level sheet of this user in course's homespace
5752: # - the assessment level sheet for this resource
5753: # for this user in user's homespace
1.553 albertel 5754: # - current conditional state info
1.325 www 5755: my $key=$uname.':'.$udom.':';
1.109 www 5756: my $status=
1.299 matthew 5757: &del('nohist_calculatedsheets',
1.391 matthew 5758: [$key.'studentcalc:'],
1.620 albertel 5759: $env{'course.'.$cid.'.domain'},
5760: $env{'course.'.$cid.'.num'})
1.133 albertel 5761: .' '.
5762: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5763: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5764: unless ($status eq 'ok ok') {
5765: &logthis('Could not devalidate spreadsheet '.
1.325 www 5766: $uname.' at '.$udom.' for '.
1.109 www 5767: $symb.': '.$status);
1.133 albertel 5768: }
1.553 albertel 5769: &delenv('user.state.'.$cid);
1.109 www 5770: }
5771: }
5772:
1.265 albertel 5773: sub get_scalar {
5774: my ($string,$end) = @_;
5775: my $value;
5776: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5777: $value = $1;
5778: } elsif ($$string =~ s/^([^&]*?)&//) {
5779: $value = $1;
5780: }
5781: return &unescape($value);
5782: }
5783:
5784: sub array2str {
5785: my (@array) = @_;
5786: my $result=&arrayref2str(\@array);
5787: $result=~s/^__ARRAY_REF__//;
5788: $result=~s/__END_ARRAY_REF__$//;
5789: return $result;
5790: }
5791:
1.204 albertel 5792: sub arrayref2str {
5793: my ($arrayref) = @_;
1.265 albertel 5794: my $result='__ARRAY_REF__';
1.204 albertel 5795: foreach my $elem (@$arrayref) {
1.265 albertel 5796: if(ref($elem) eq 'ARRAY') {
5797: $result.=&arrayref2str($elem).'&';
5798: } elsif(ref($elem) eq 'HASH') {
5799: $result.=&hashref2str($elem).'&';
5800: } elsif(ref($elem)) {
5801: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5802: } else {
5803: $result.=&escape($elem).'&';
5804: }
5805: }
5806: $result=~s/\&$//;
1.265 albertel 5807: $result .= '__END_ARRAY_REF__';
1.204 albertel 5808: return $result;
5809: }
5810:
1.168 albertel 5811: sub hash2str {
1.204 albertel 5812: my (%hash) = @_;
5813: my $result=&hashref2str(\%hash);
1.265 albertel 5814: $result=~s/^__HASH_REF__//;
5815: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5816: return $result;
5817: }
5818:
5819: sub hashref2str {
5820: my ($hashref)=@_;
1.265 albertel 5821: my $result='__HASH_REF__';
1.800 albertel 5822: foreach my $key (sort(keys(%$hashref))) {
5823: if (ref($key) eq 'ARRAY') {
5824: $result.=&arrayref2str($key).'=';
5825: } elsif (ref($key) eq 'HASH') {
5826: $result.=&hashref2str($key).'=';
5827: } elsif (ref($key)) {
1.265 albertel 5828: $result.='=';
1.800 albertel 5829: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5830: } else {
1.1132 raeburn 5831: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5832: }
5833:
1.800 albertel 5834: if(ref($hashref->{$key}) eq 'ARRAY') {
5835: $result.=&arrayref2str($hashref->{$key}).'&';
5836: } elsif(ref($hashref->{$key}) eq 'HASH') {
5837: $result.=&hashref2str($hashref->{$key}).'&';
5838: } elsif(ref($hashref->{$key})) {
1.265 albertel 5839: $result.='&';
1.800 albertel 5840: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5841: } else {
1.800 albertel 5842: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5843: }
5844: }
1.168 albertel 5845: $result=~s/\&$//;
1.265 albertel 5846: $result .= '__END_HASH_REF__';
1.168 albertel 5847: return $result;
5848: }
5849:
5850: sub str2hash {
1.265 albertel 5851: my ($string)=@_;
5852: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5853: return %$hash;
5854: }
5855:
5856: sub str2hashref {
1.168 albertel 5857: my ($string) = @_;
1.265 albertel 5858:
5859: my %hash;
5860:
5861: if($string !~ /^__HASH_REF__/) {
5862: if (! ($string eq '' || !defined($string))) {
5863: $hash{'error'}='Not hash reference';
5864: }
5865: return (\%hash, $string);
5866: }
5867:
5868: $string =~ s/^__HASH_REF__//;
5869:
5870: while($string !~ /^__END_HASH_REF__/) {
5871: #key
5872: my $key='';
5873: if($string =~ /^__HASH_REF__/) {
5874: ($key, $string)=&str2hashref($string);
5875: if(defined($key->{'error'})) {
5876: $hash{'error'}='Bad data';
5877: return (\%hash, $string);
5878: }
5879: } elsif($string =~ /^__ARRAY_REF__/) {
5880: ($key, $string)=&str2arrayref($string);
5881: if($key->[0] eq 'Array reference error') {
5882: $hash{'error'}='Bad data';
5883: return (\%hash, $string);
5884: }
5885: } else {
5886: $string =~ s/^(.*?)=//;
1.267 albertel 5887: $key=&unescape($1);
1.265 albertel 5888: }
5889: $string =~ s/^=//;
5890:
5891: #value
5892: my $value='';
5893: if($string =~ /^__HASH_REF__/) {
5894: ($value, $string)=&str2hashref($string);
5895: if(defined($value->{'error'})) {
5896: $hash{'error'}='Bad data';
5897: return (\%hash, $string);
5898: }
5899: } elsif($string =~ /^__ARRAY_REF__/) {
5900: ($value, $string)=&str2arrayref($string);
5901: if($value->[0] eq 'Array reference error') {
5902: $hash{'error'}='Bad data';
5903: return (\%hash, $string);
5904: }
5905: } else {
5906: $value=&get_scalar(\$string,'__END_HASH_REF__');
5907: }
5908: $string =~ s/^&//;
5909:
5910: $hash{$key}=$value;
1.204 albertel 5911: }
1.265 albertel 5912:
5913: $string =~ s/^__END_HASH_REF__//;
5914:
5915: return (\%hash, $string);
1.204 albertel 5916: }
5917:
5918: sub str2array {
1.265 albertel 5919: my ($string)=@_;
5920: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5921: return @$array;
5922: }
5923:
5924: sub str2arrayref {
1.204 albertel 5925: my ($string) = @_;
1.265 albertel 5926: my @array;
5927:
5928: if($string !~ /^__ARRAY_REF__/) {
5929: if (! ($string eq '' || !defined($string))) {
5930: $array[0]='Array reference error';
5931: }
5932: return (\@array, $string);
5933: }
5934:
5935: $string =~ s/^__ARRAY_REF__//;
5936:
5937: while($string !~ /^__END_ARRAY_REF__/) {
5938: my $value='';
5939: if($string =~ /^__HASH_REF__/) {
5940: ($value, $string)=&str2hashref($string);
5941: if(defined($value->{'error'})) {
5942: $array[0] ='Array reference error';
5943: return (\@array, $string);
5944: }
5945: } elsif($string =~ /^__ARRAY_REF__/) {
5946: ($value, $string)=&str2arrayref($string);
5947: if($value->[0] eq 'Array reference error') {
5948: $array[0] ='Array reference error';
5949: return (\@array, $string);
5950: }
5951: } else {
5952: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5953: }
5954: $string =~ s/^&//;
5955:
5956: push(@array, $value);
1.191 harris41 5957: }
1.265 albertel 5958:
5959: $string =~ s/^__END_ARRAY_REF__//;
5960:
5961: return (\@array, $string);
1.168 albertel 5962: }
5963:
1.167 albertel 5964: # -------------------------------------------------------------------Temp Store
5965:
1.168 albertel 5966: sub tmpreset {
5967: my ($symb,$namespace,$domain,$stuname) = @_;
5968: if (!$symb) {
5969: $symb=&symbread();
1.620 albertel 5970: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5971: }
5972: $symb=escape($symb);
5973:
1.620 albertel 5974: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5975: $namespace=~s/\//\_/g;
5976: $namespace=~s/\W//g;
5977:
1.620 albertel 5978: if (!$domain) { $domain=$env{'user.domain'}; }
5979: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5980: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5981: $stuname=&get_requestor_ip();
1.591 albertel 5982: }
1.1117 foxr 5983: my $path=LONCAPA::tempdir();
1.168 albertel 5984: my %hash;
5985: if (tie(%hash,'GDBM_File',
5986: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5987: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5988: foreach my $key (keys(%hash)) {
1.180 albertel 5989: if ($key=~ /:$symb/) {
1.168 albertel 5990: delete($hash{$key});
5991: }
5992: }
5993: }
5994: }
5995:
1.167 albertel 5996: sub tmpstore {
1.168 albertel 5997: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5998:
5999: if (!$symb) {
6000: $symb=&symbread();
1.620 albertel 6001: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6002: }
6003: $symb=escape($symb);
6004:
6005: if (!$namespace) {
6006: # I don't think we would ever want to store this for a course.
6007: # it seems this will only be used if we don't have a course.
1.620 albertel 6008: #$namespace=$env{'request.course.id'};
1.168 albertel 6009: #if (!$namespace) {
1.620 albertel 6010: $namespace=$env{'request.state'};
1.168 albertel 6011: #}
6012: }
6013: $namespace=~s/\//\_/g;
6014: $namespace=~s/\W//g;
1.620 albertel 6015: if (!$domain) { $domain=$env{'user.domain'}; }
6016: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6017: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6018: $stuname=&get_requestor_ip();
1.591 albertel 6019: }
1.168 albertel 6020: my $now=time;
6021: my %hash;
1.1117 foxr 6022: my $path=LONCAPA::tempdir();
1.168 albertel 6023: if (tie(%hash,'GDBM_File',
6024: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6025: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6026: $hash{"version:$symb"}++;
6027: my $version=$hash{"version:$symb"};
6028: my $allkeys='';
6029: foreach my $key (keys(%$storehash)) {
6030: $allkeys.=$key.':';
1.591 albertel 6031: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6032: }
6033: $hash{"$version:$symb:timestamp"}=$now;
6034: $allkeys.='timestamp';
6035: $hash{"$version:keys:$symb"}=$allkeys;
6036: if (untie(%hash)) {
6037: return 'ok';
6038: } else {
6039: return "error:$!";
6040: }
6041: } else {
6042: return "error:$!";
6043: }
6044: }
1.167 albertel 6045:
1.168 albertel 6046: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6047:
1.168 albertel 6048: sub tmprestore {
6049: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6050:
1.168 albertel 6051: if (!$symb) {
6052: $symb=&symbread();
1.620 albertel 6053: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6054: }
6055: $symb=escape($symb);
6056:
1.620 albertel 6057: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6058:
1.620 albertel 6059: if (!$domain) { $domain=$env{'user.domain'}; }
6060: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6061: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6062: $stuname=&get_requestor_ip();
1.591 albertel 6063: }
1.168 albertel 6064: my %returnhash;
6065: $namespace=~s/\//\_/g;
6066: $namespace=~s/\W//g;
6067: my %hash;
1.1117 foxr 6068: my $path=LONCAPA::tempdir();
1.168 albertel 6069: if (tie(%hash,'GDBM_File',
6070: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6071: &GDBM_READER(),0640)) {
1.168 albertel 6072: my $version=$hash{"version:$symb"};
6073: $returnhash{'version'}=$version;
6074: my $scope;
6075: for ($scope=1;$scope<=$version;$scope++) {
6076: my $vkeys=$hash{"$scope:keys:$symb"};
6077: my @keys=split(/:/,$vkeys);
6078: my $key;
6079: $returnhash{"$scope:keys"}=$vkeys;
6080: foreach $key (@keys) {
1.591 albertel 6081: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6082: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6083: }
6084: }
1.168 albertel 6085: if (!(untie(%hash))) {
6086: return "error:$!";
6087: }
6088: } else {
6089: return "error:$!";
6090: }
6091: return %returnhash;
1.167 albertel 6092: }
6093:
1.9 www 6094: # ----------------------------------------------------------------------- Store
6095:
6096: sub store {
1.1172.2.64 raeburn 6097: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6098: my $home='';
6099:
1.168 albertel 6100: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6101:
1.213 www 6102: $symb=&symbclean($symb);
1.122 albertel 6103: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6104:
1.620 albertel 6105: if (!$domain) { $domain=$env{'user.domain'}; }
6106: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6107:
6108: &devalidate($symb,$stuname,$domain);
1.109 www 6109:
6110: $symb=escape($symb);
1.187 www 6111: if (!$namespace) {
1.620 albertel 6112: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6113: return '';
6114: }
6115: }
1.620 albertel 6116: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6117:
1.1172.2.138 raeburn 6118: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6119: $$storehash{'host'}=$perlvar{'lonHostID'};
6120:
1.12 www 6121: my $namevalue='';
1.800 albertel 6122: foreach my $key (keys(%$storehash)) {
6123: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6124: }
1.12 www 6125: $namevalue=~s/\&$//;
1.187 www 6126: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6127: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6128: }
6129:
1.47 www 6130: # -------------------------------------------------------------- Critical Store
6131:
6132: sub cstore {
1.1172.2.64 raeburn 6133: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6134: my $home='';
6135:
1.168 albertel 6136: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6137:
1.213 www 6138: $symb=&symbclean($symb);
1.122 albertel 6139: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6140:
1.620 albertel 6141: if (!$domain) { $domain=$env{'user.domain'}; }
6142: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6143:
6144: &devalidate($symb,$stuname,$domain);
1.109 www 6145:
6146: $symb=escape($symb);
1.187 www 6147: if (!$namespace) {
1.620 albertel 6148: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6149: return '';
6150: }
6151: }
1.620 albertel 6152: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6153:
1.1172.2.138 raeburn 6154: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6155: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6156:
1.47 www 6157: my $namevalue='';
1.800 albertel 6158: foreach my $key (keys(%$storehash)) {
6159: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6160: }
1.47 www 6161: $namevalue=~s/\&$//;
1.187 www 6162: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6163: return critical
1.1172.2.64 raeburn 6164: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6165: }
6166:
1.9 www 6167: # --------------------------------------------------------------------- Restore
6168:
6169: sub restore {
1.124 www 6170: my ($symb,$namespace,$domain,$stuname) = @_;
6171: my $home='';
6172:
1.168 albertel 6173: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6174:
1.122 albertel 6175: if (!$symb) {
1.1172.2.26 raeburn 6176: return if ($namespace eq 'courserequests');
6177: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6178: } else {
1.1172.2.26 raeburn 6179: unless ($namespace eq 'courserequests') {
6180: $symb=&escape(&symbclean($symb));
6181: }
1.122 albertel 6182: }
1.188 www 6183: if (!$namespace) {
1.620 albertel 6184: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6185: return '';
6186: }
6187: }
1.620 albertel 6188: if (!$domain) { $domain=$env{'user.domain'}; }
6189: if (!$stuname) { $stuname=$env{'user.name'}; }
6190: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6191: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6192:
1.12 www 6193: my %returnhash=();
1.800 albertel 6194: foreach my $line (split(/\&/,$answer)) {
6195: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6196: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6197: }
1.75 www 6198: my $version;
6199: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6200: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6201: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6202: }
1.75 www 6203: }
1.13 www 6204: return %returnhash;
1.34 www 6205: }
6206:
6207: # ---------------------------------------------------------- Course Description
1.1118 foxr 6208: #
6209: #
1.34 www 6210:
6211: sub coursedescription {
1.731 albertel 6212: my ($courseid,$args)=@_;
1.34 www 6213: $courseid=~s/^\///;
1.49 www 6214: $courseid=~s/\_/\//g;
1.34 www 6215: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6216: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6217: my $normalid=$cdomain.'_'.$cnum;
6218: # need to always cache even if we get errors otherwise we keep
6219: # trying and trying and trying to get the course description.
6220: my %envhash=();
6221: my %returnhash=();
1.731 albertel 6222:
6223: my $expiretime=600;
6224: if ($env{'request.course.id'} eq $normalid) {
6225: $expiretime=120;
6226: }
6227:
6228: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6229: if (!$args->{'freshen_cache'}
6230: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6231: foreach my $key (keys(%env)) {
6232: next if ($key !~ /^\Q$prefix\E(.*)/);
6233: my ($setting) = $1;
6234: $returnhash{$setting} = $env{$key};
6235: }
6236: return %returnhash;
6237: }
6238:
1.1118 foxr 6239: # get the data again
6240:
1.731 albertel 6241: if (!$args->{'one_time'}) {
6242: $envhash{'course.'.$normalid.'.last_cache'}=time;
6243: }
1.811 albertel 6244:
1.34 www 6245: if ($chome ne 'no_host') {
1.302 albertel 6246: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6247: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6248: my $username = $env{'user.name'}; # Defult username
6249: if(defined $args->{'user'}) {
6250: $username = $args->{'user'};
6251: }
1.129 albertel 6252: $returnhash{'home'}= $chome;
6253: $returnhash{'domain'} = $cdomain;
6254: $returnhash{'num'} = $cnum;
1.741 raeburn 6255: if (!defined($returnhash{'type'})) {
6256: $returnhash{'type'} = 'Course';
6257: }
1.130 albertel 6258: while (my ($name,$value) = each %returnhash) {
1.53 www 6259: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6260: }
1.270 www 6261: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6262: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6263: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6264: $envhash{'course.'.$normalid.'.home'}=$chome;
6265: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6266: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6267: }
6268: }
1.731 albertel 6269: if (!$args->{'one_time'}) {
1.949 raeburn 6270: &appenv(\%envhash);
1.731 albertel 6271: }
1.302 albertel 6272: return %returnhash;
1.461 www 6273: }
6274:
1.1080 raeburn 6275: sub update_released_required {
6276: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6277: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6278: $cid = $env{'request.course.id'};
6279: $cdom = $env{'course.'.$cid.'.domain'};
6280: $cnum = $env{'course.'.$cid.'.num'};
6281: $chome = $env{'course.'.$cid.'.home'};
6282: }
6283: if ($needsrelease) {
6284: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6285: my $needsupdate;
6286: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6287: $needsupdate = 1;
6288: } else {
6289: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6290: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6291: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6292: $needsupdate = 1;
6293: }
6294: }
6295: if ($needsupdate) {
6296: my %needshash = (
6297: 'internal.releaserequired' => $needsrelease,
6298: );
6299: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6300: if ($putresult eq 'ok') {
6301: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6302: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6303: if (ref($crsinfo{$cid}) eq 'HASH') {
6304: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6305: &courseidput($cdom,\%crsinfo,$chome,'notime');
6306: }
6307: }
6308: }
6309: }
6310: return;
6311: }
6312:
1.461 www 6313: # -------------------------------------------------See if a user is privileged
6314:
6315: sub privileged {
1.1172.2.23 raeburn 6316: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6317: my $now = time;
1.1172.2.23 raeburn 6318: my $roles;
6319: if (ref($possroles) eq 'ARRAY') {
6320: $roles = $possroles;
6321: } else {
6322: $roles = ['dc','su'];
6323: }
6324: if (ref($possdomains) eq 'ARRAY') {
6325: my %privileged = &privileged_by_domain($possdomains,$roles);
6326: foreach my $dom (@{$possdomains}) {
6327: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6328: (ref($privileged{$dom}) eq 'HASH')) {
6329: foreach my $role (@{$roles}) {
6330: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6331: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6332: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6333: return 1 unless (($end && $end < $now) ||
6334: ($start && $start > $now));
6335: }
6336: }
6337: }
6338: }
6339: }
6340: } else {
6341: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6342: my $now = time;
1.1170 droeschl 6343:
1.1172.2.58 raeburn 6344: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6345: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6346: if (grep(/^\Q$trole\E$/,@{$roles})) {
6347: return 1 unless ($tend && $tend < $now)
6348: or ($tstart && $tstart > $now);
1.1170 droeschl 6349: }
1.1172.2.23 raeburn 6350: }
6351: }
1.461 www 6352: return 0;
1.9 www 6353: }
1.1 albertel 6354:
1.1172.2.23 raeburn 6355: sub privileged_by_domain {
6356: my ($domains,$roles) = @_;
6357: my %privileged = ();
6358: my $cachetime = 60*60*24;
6359: my $now = time;
6360: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6361: return %privileged;
6362: }
6363: foreach my $dom (@{$domains}) {
6364: next if (ref($privileged{$dom}) eq 'HASH');
6365: my $needroles;
6366: foreach my $role (@{$roles}) {
6367: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6368: if (defined($cached)) {
6369: if (ref($result) eq 'HASH') {
6370: $privileged{$dom}{$role} = $result;
6371: }
6372: } else {
6373: $needroles = 1;
6374: }
6375: }
6376: if ($needroles) {
6377: my %dompersonnel = &get_domain_roles($dom,$roles);
6378: $privileged{$dom} = {};
6379: foreach my $server (keys(%dompersonnel)) {
6380: if (ref($dompersonnel{$server}) eq 'HASH') {
6381: foreach my $item (keys(%{$dompersonnel{$server}})) {
6382: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6383: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6384: next if ($end && $end < $now);
6385: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6386: $dompersonnel{$server}{$item};
6387: }
6388: }
6389: }
6390: if (ref($privileged{$dom}) eq 'HASH') {
6391: foreach my $role (@{$roles}) {
6392: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6393: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6394: } else {
6395: my %hash = ();
6396: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6397: }
6398: }
6399: }
6400: }
6401: }
6402: return %privileged;
6403: }
6404:
1.103 harris41 6405: # -------------------------------------------------------- Get user privileges
1.11 www 6406:
6407: sub rolesinit {
1.1169 droeschl 6408: my ($domain, $username) = @_;
6409: my %userroles = ('user.login.time' => time);
6410: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6411:
6412: # firstaccess and timerinterval are related to timed maps/resources.
6413: # also, blocking can be triggered by an activating timer
6414: # it's saved in the user's %env.
6415: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6416: my %timerinterval = &dump('timerinterval', $domain, $username);
6417: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6418: %timerintchk, %timerintenv);
6419:
1.1162 raeburn 6420: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6421: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6422: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6423: }
1.1169 droeschl 6424:
1.1162 raeburn 6425: foreach my $key (keys(%timerinterval)) {
6426: my ($cid,$rest) = split(/\0/,$key);
6427: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6428: }
1.1169 droeschl 6429:
1.11 www 6430: my %allroles=();
1.1162 raeburn 6431: my %allgroups=();
1.11 www 6432:
1.1172.2.58 raeburn 6433: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6434: my $role = $rolesdump{$area};
6435: $area =~ s/\_\w\w$//;
6436:
6437: my ($trole, $tend, $tstart, $group_privs);
6438:
6439: if ($role =~ /^cr/) {
6440: # Custom role, defined by a user
6441: # e.g., user.role.cr/msu/smith/mynewrole
6442: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6443: $trole = $1;
6444: ($tend, $tstart) = split('_', $2);
6445: } else {
6446: $trole = $role;
6447: }
6448: } elsif ($role =~ m|^gr/|) {
6449: # Role of member in a group, defined within a course/community
6450: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6451: ($trole, $tend, $tstart) = split(/_/, $role);
6452: next if $tstart eq '-1';
6453: ($trole, $group_privs) = split(/\//, $trole);
6454: $group_privs = &unescape($group_privs);
6455: } else {
6456: # Just a normal role, defined in roles.tab
6457: ($trole, $tend, $tstart) = split(/_/,$role);
6458: }
6459:
6460: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6461: $username);
6462: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6463:
6464: # role expired or not available yet?
6465: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6466: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6467:
6468: next if $area eq '' or $trole eq '';
6469:
6470: my $spec = "$trole.$area";
6471: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6472:
6473: if ($trole =~ /^cr\//) {
6474: # Custom role, defined by a user
6475: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6476: } elsif ($trole eq 'gr') {
6477: # Role of a member in a group, defined within a course/community
6478: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6479: next;
6480: } else {
6481: # Normal role, defined in roles.tab
6482: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6483: }
6484:
6485: my $cid = $tdomain.'_'.$trest;
6486: unless ($firstaccchk{$cid}) {
6487: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6488: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6489: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6490: $coursetimerstarts{$cid}{$item};
6491: }
6492: }
6493: $firstaccchk{$cid} = 1;
6494: }
6495: unless ($timerintchk{$cid}) {
6496: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6497: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6498: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6499: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6500: }
1.12 www 6501: }
1.1169 droeschl 6502: $timerintchk{$cid} = 1;
1.191 harris41 6503: }
1.11 www 6504: }
1.1169 droeschl 6505:
1.1172.2.91 raeburn 6506: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6507: \%allroles, \%allgroups);
1.1169 droeschl 6508: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6509: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6510:
1.1162 raeburn 6511: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6512: }
6513:
1.567 raeburn 6514: sub set_arearole {
1.1172.2.19 raeburn 6515: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6516: unless ($nolog) {
1.567 raeburn 6517: # log the associated role with the area
1.1172.2.19 raeburn 6518: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6519: }
1.743 albertel 6520: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6521: }
6522:
6523: sub custom_roleprivs {
6524: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6525: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6526: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6527: if (&hostname($homsvr) ne '') {
1.567 raeburn 6528: my ($rdummy,$roledef)=
6529: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6530: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6531: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6532: if (defined($syspriv)) {
1.1043 raeburn 6533: if ($trest =~ /^$match_community$/) {
6534: $syspriv =~ s/bre\&S//;
6535: }
1.567 raeburn 6536: $$allroles{'cm./'}.=':'.$syspriv;
6537: $$allroles{$spec.'./'}.=':'.$syspriv;
6538: }
6539: if ($tdomain ne '') {
6540: if (defined($dompriv)) {
6541: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6542: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6543: }
6544: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6545: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6546: my $rolename = $1;
6547: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6548: }
1.567 raeburn 6549: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6550: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6551: }
6552: }
6553: }
6554: }
6555: }
6556:
1.1172.2.89 raeburn 6557: sub course_adhocrole_privs {
6558: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6559: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6560: if ($overrides{"internal.adhocpriv.$rolename"}) {
6561: my (%currprivs,%storeprivs);
6562: foreach my $item (split(/:/,$coursepriv)) {
6563: my ($priv,$restrict) = split(/\&/,$item);
6564: $currprivs{$priv} = $restrict;
6565: }
6566: my (%possadd,%possremove,%full);
6567: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6568: my ($priv,$restrict)=split(/\&/,$item);
6569: $full{$priv} = $restrict;
6570: }
6571: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6572: next if ($item eq '');
6573: my ($rule,$rest) = split(/=/,$item);
6574: next unless (($rule eq 'off') || ($rule eq 'on'));
6575: foreach my $priv (split(/:/,$rest)) {
6576: if ($priv ne '') {
6577: if ($rule eq 'off') {
6578: $possremove{$priv} = 1;
6579: } else {
6580: $possadd{$priv} = 1;
6581: }
6582: }
6583: }
6584: }
6585: foreach my $priv (sort(keys(%full))) {
6586: if (exists($currprivs{$priv})) {
6587: unless (exists($possremove{$priv})) {
6588: $storeprivs{$priv} = $currprivs{$priv};
6589: }
6590: } elsif (exists($possadd{$priv})) {
6591: $storeprivs{$priv} = $full{$priv};
6592: }
6593: }
6594: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6595: }
6596: return $coursepriv;
6597: }
6598:
1.678 raeburn 6599: sub group_roleprivs {
6600: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6601: my $access = 1;
6602: my $now = time;
6603: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6604: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6605: if ($access) {
1.811 albertel 6606: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6607: $$allgroups{$course}{$group} .=':'.$group_privs;
6608: }
6609: }
1.567 raeburn 6610:
6611: sub standard_roleprivs {
6612: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6613: if (defined($pr{$trole.':s'})) {
6614: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6615: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6616: }
6617: if ($tdomain ne '') {
6618: if (defined($pr{$trole.':d'})) {
6619: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6620: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6621: }
6622: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6623: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6624: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6625: }
6626: }
6627: }
6628:
6629: sub set_userprivs {
1.1064 raeburn 6630: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6631: my $author=0;
6632: my $adv=0;
1.1172.2.91 raeburn 6633: my $rar=0;
1.678 raeburn 6634: my %grouproles = ();
6635: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6636: my @groupkeys;
1.1000 raeburn 6637: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6638: push(@groupkeys,$role);
6639: }
6640: if (ref($groups_roles) eq 'HASH') {
6641: foreach my $key (keys(%{$groups_roles})) {
6642: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6643: push(@groupkeys,$key);
6644: }
6645: }
6646: }
6647: if (@groupkeys > 0) {
6648: foreach my $role (@groupkeys) {
6649: my ($trole,$area,$sec,$extendedarea);
6650: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6651: $trole = $1;
6652: $area = $2;
6653: $sec = $3;
6654: $extendedarea = $area.$sec;
6655: if (exists($$allgroups{$area})) {
6656: foreach my $group (keys(%{$$allgroups{$area}})) {
6657: my $spec = $trole.'.'.$extendedarea;
6658: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6659: $$allgroups{$area}{$group};
1.1064 raeburn 6660: }
1.678 raeburn 6661: }
6662: }
6663: }
6664: }
6665: }
1.800 albertel 6666: foreach my $group (keys(%grouproles)) {
6667: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6668: }
1.800 albertel 6669: foreach my $role (keys(%{$allroles})) {
6670: my %thesepriv;
1.941 raeburn 6671: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6672: foreach my $item (split(/:/,$$allroles{$role})) {
6673: if ($item ne '') {
6674: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6675: if ($restrictions eq '') {
6676: $thesepriv{$privilege}='F';
6677: } elsif ($thesepriv{$privilege} ne 'F') {
6678: $thesepriv{$privilege}.=$restrictions;
6679: }
6680: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6681: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6682: }
6683: }
6684: my $thesestr='';
1.1104 raeburn 6685: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6686: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6687: }
6688: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6689: }
1.1172.2.91 raeburn 6690: return ($author,$adv,$rar);
1.567 raeburn 6691: }
6692:
1.994 raeburn 6693: sub role_status {
1.1104 raeburn 6694: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6695: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6696: my ($one,$two) = split(m{\./},$rolekey,2);
6697: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6698: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6699: $$where = '/'.$two;
1.994 raeburn 6700: $$trolecode=$$role.'.'.$$where;
6701: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6702: $$tstatus='is';
1.1104 raeburn 6703: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6704: $$tstatus='future';
1.1034 raeburn 6705: if ($$tstart<$now) {
6706: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6707: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6708: my (%allroles,%allgroups,$group_privs,
6709: %groups_roles,@rolecodes);
1.1002 raeburn 6710: my %userroles = (
6711: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6712: );
1.1064 raeburn 6713: @rolecodes = ('cm');
1.1002 raeburn 6714: my $spec=$$role.'.'.$$where;
6715: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6716: if ($$role =~ /^cr\//) {
6717: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6718: push(@rolecodes,'cr');
1.1002 raeburn 6719: } elsif ($$role eq 'gr') {
1.1064 raeburn 6720: push(@rolecodes,$$role);
1.1002 raeburn 6721: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6722: $env{'user.name'});
1.1064 raeburn 6723: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6724: (undef,my $group_privs) = split(/\//,$trole);
6725: $group_privs = &unescape($group_privs);
6726: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6727: 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 6728: &get_groups_roles($tdomain,$trest,
6729: \%course_roles,\@rolecodes,
6730: \%groups_roles);
1.1002 raeburn 6731: } else {
1.1064 raeburn 6732: push(@rolecodes,$$role);
1.1002 raeburn 6733: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6734: }
1.1172.2.91 raeburn 6735: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6736: \%groups_roles);
1.1064 raeburn 6737: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6738: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6739: }
6740: }
1.1034 raeburn 6741: $$tstatus = 'is';
1.1002 raeburn 6742: }
1.994 raeburn 6743: }
6744: if ($$tend) {
1.1104 raeburn 6745: if ($$tend<$update) {
1.994 raeburn 6746: $$tstatus='expired';
6747: } elsif ($$tend<$now) {
6748: $$tstatus='will_not';
6749: }
6750: }
6751: }
6752: }
6753: }
6754:
1.1104 raeburn 6755: sub get_groups_roles {
6756: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6757: return unless((ref($cdom_courseroles) eq 'HASH') &&
6758: (ref($rolecodes) eq 'ARRAY') &&
6759: (ref($groups_roles) eq 'HASH'));
6760: if (keys(%{$cdom_courseroles}) > 0) {
6761: my ($cnum) = ($rest =~ /^($match_courseid)/);
6762: if ($cdom ne '' && $cnum ne '') {
6763: foreach my $key (keys(%{$cdom_courseroles})) {
6764: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6765: my $crsrole = $1;
6766: my $crssec = $2;
6767: if ($crsrole =~ /^cr/) {
6768: unless (grep(/^cr$/,@{$rolecodes})) {
6769: push(@{$rolecodes},'cr');
6770: }
6771: } else {
6772: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6773: push(@{$rolecodes},$crsrole);
6774: }
6775: }
6776: my $rolekey = "$crsrole./$cdom/$cnum";
6777: if ($crssec ne '') {
6778: $rolekey .= "/$crssec";
6779: }
6780: $rolekey .= './';
6781: $groups_roles->{$rolekey} = $rolecodes;
6782: }
6783: }
6784: }
6785: }
6786: return;
6787: }
6788:
6789: sub delete_env_groupprivs {
6790: my ($where,$courseroles,$possroles) = @_;
6791: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6792: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6793: unless (ref($courseroles->{$udom}) eq 'HASH') {
6794: %{$courseroles->{$udom}} =
6795: &get_my_roles('','','userroles',['active'],
6796: $possroles,[$udom],1);
6797: }
6798: if (ref($courseroles->{$udom}) eq 'HASH') {
6799: foreach my $item (keys(%{$courseroles->{$udom}})) {
6800: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6801: my $area = '/'.$cdom.'/'.$cnum;
6802: my $privkey = "user.priv.$crsrole.$area";
6803: if ($crssec ne '') {
6804: $privkey .= '/'.$crssec;
6805: }
6806: $privkey .= ".$area/$group";
6807: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6808: }
6809: }
6810: return;
6811: }
6812:
1.994 raeburn 6813: sub check_adhoc_privs {
1.1172.2.86 raeburn 6814: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6815: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6816: if ($sec) {
6817: $cckey .= '/'.$sec;
6818: }
1.1172.2.9 raeburn 6819: my $setprivs;
1.994 raeburn 6820: if ($env{$cckey}) {
6821: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6822: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6823: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6824: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6825: $setprivs = 1;
1.994 raeburn 6826: }
6827: } else {
1.1172.2.87 raeburn 6828: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6829: $setprivs = 1;
1.994 raeburn 6830: }
1.1172.2.9 raeburn 6831: return $setprivs;
1.994 raeburn 6832: }
6833:
6834: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6835: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6836: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6837: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6838: if ($sec ne '') {
6839: $area .= '/'.$sec;
6840: }
1.994 raeburn 6841: my $spec = $role.'.'.$area;
6842: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6843: $env{'user.name'},1);
1.1172.2.84 raeburn 6844: my %rolehash = ();
1.1172.2.89 raeburn 6845: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6846: my $rolename = $1;
1.1172.2.84 raeburn 6847: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6848: my %domdef = &get_domain_defaults($dcdom);
6849: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6850: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6851: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6852: }
6853: }
1.1172.2.84 raeburn 6854: } else {
6855: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6856: }
1.1172.2.91 raeburn 6857: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6858: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6859: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6860: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6861: &appenv( {'request.role' => $spec,
6862: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6863: 'request.course.sec' => $sec,
1.1088 raeburn 6864: }
6865: );
6866: my $tadv=0;
6867: if (&allowed('adv') eq 'F') { $tadv=1; }
6868: &appenv({'request.role.adv' => $tadv});
6869: }
1.994 raeburn 6870: }
6871:
1.12 www 6872: # --------------------------------------------------------------- get interface
6873:
6874: sub get {
1.131 albertel 6875: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6876: my $items='';
1.800 albertel 6877: foreach my $item (@$storearr) {
6878: $items.=&escape($item).'&';
1.191 harris41 6879: }
1.12 www 6880: $items=~s/\&$//;
1.620 albertel 6881: if (!$udomain) { $udomain=$env{'user.domain'}; }
6882: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6883: my $uhome=&homeserver($uname,$udomain);
6884:
1.133 albertel 6885: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6886: my @pairs=split(/\&/,$rep);
1.273 albertel 6887: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6888: return @pairs;
6889: }
1.15 www 6890: my %returnhash=();
1.42 www 6891: my $i=0;
1.800 albertel 6892: foreach my $item (@$storearr) {
6893: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6894: $i++;
1.191 harris41 6895: }
1.15 www 6896: return %returnhash;
1.27 www 6897: }
6898:
6899: # --------------------------------------------------------------- del interface
6900:
6901: sub del {
1.133 albertel 6902: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6903: my $items='';
1.800 albertel 6904: foreach my $item (@$storearr) {
6905: $items.=&escape($item).'&';
1.191 harris41 6906: }
1.984 neumanie 6907:
1.27 www 6908: $items=~s/\&$//;
1.620 albertel 6909: if (!$udomain) { $udomain=$env{'user.domain'}; }
6910: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6911: my $uhome=&homeserver($uname,$udomain);
6912: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6913: }
6914:
6915: # -------------------------------------------------------------- dump interface
6916:
1.1172.2.22 raeburn 6917: sub unserialize {
6918: my ($rep, $escapedkeys) = @_;
6919:
6920: return {} if $rep =~ /^error/;
6921:
6922: my %returnhash=();
6923: foreach my $item (split(/\&/,$rep)) {
6924: my ($key, $value) = split(/=/, $item, 2);
6925: $key = unescape($key) unless $escapedkeys;
6926: next if $key =~ /^error: 2 /;
6927: $returnhash{$key} = &thaw_unescape($value);
6928: }
6929: return \%returnhash;
6930: }
6931:
6932: # see Lond::dump_with_regexp
6933: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6934: sub dump {
1.1172.2.22 raeburn 6935: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6936: if (!$udomain) { $udomain=$env{'user.domain'}; }
6937: if (!$uname) { $uname=$env{'user.name'}; }
6938: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6939:
1.1172.2.55 raeburn 6940: if ($regexp) {
6941: $regexp=&escape($regexp);
6942: } else {
6943: $regexp='.';
6944: }
1.1172.2.22 raeburn 6945: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6946: # user is hosted on this machine
1.1172.2.55 raeburn 6947: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6948: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6949: return %{&unserialize($reply, $escapedkeys)};
6950: }
1.1166 raeburn 6951: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6952: my @pairs=split(/\&/,$rep);
6953: my %returnhash=();
1.1098 foxr 6954: if (!($rep =~ /^error/ )) {
6955: foreach my $item (@pairs) {
6956: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6957: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6958: next if ($key =~ /^error: 2 /);
6959: $returnhash{$key}=&thaw_unescape($value);
6960: }
1.755 albertel 6961: }
6962: return %returnhash;
1.407 www 6963: }
6964:
1.1098 foxr 6965:
1.717 albertel 6966: # --------------------------------------------------------- dumpstore interface
6967:
6968: sub dumpstore {
6969: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6970: # same as dump but keys must be escaped. They may contain colon separated
6971: # lists of values that may themself contain colons (e.g. symbs).
6972: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6973: }
6974:
1.407 www 6975: # -------------------------------------------------------------- keys interface
6976:
6977: sub getkeys {
6978: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6979: if (!$udomain) { $udomain=$env{'user.domain'}; }
6980: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6981: my $uhome=&homeserver($uname,$udomain);
6982: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6983: my @keyarray=();
1.800 albertel 6984: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6985: next if ($key =~ /^error: 2 /);
1.800 albertel 6986: push(@keyarray,&unescape($key));
1.407 www 6987: }
6988: return @keyarray;
1.318 matthew 6989: }
6990:
1.319 matthew 6991: # --------------------------------------------------------------- currentdump
6992: sub currentdump {
1.328 matthew 6993: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6994: $courseid = $env{'request.course.id'} if (! defined($courseid));
6995: $sdom = $env{'user.domain'} if (! defined($sdom));
6996: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6997: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6998: my $rep;
6999:
7000: if (grep { $_ eq $uhome } current_machine_ids()) {
7001: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7002: $courseid)));
7003: } else {
7004: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7005: }
7006:
1.318 matthew 7007: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7008: #
1.318 matthew 7009: my %returnhash=();
1.319 matthew 7010: #
7011: if ($rep eq "unknown_cmd") {
7012: # an old lond will not know currentdump
7013: # Do a dump and make it look like a currentdump
1.822 albertel 7014: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7015: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7016: my %hash = @tmp;
7017: @tmp=();
1.424 matthew 7018: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7019: } else {
7020: my @pairs=split(/\&/,$rep);
1.800 albertel 7021: foreach my $pair (@pairs) {
7022: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7023: my ($symb,$param) = split(/:/,$key);
7024: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7025: &thaw_unescape($value);
1.319 matthew 7026: }
1.191 harris41 7027: }
1.12 www 7028: return %returnhash;
1.424 matthew 7029: }
7030:
7031: sub convert_dump_to_currentdump{
7032: my %hash = %{shift()};
7033: my %returnhash;
7034: # Code ripped from lond, essentially. The only difference
7035: # here is the unescaping done by lonnet::dump(). Conceivably
7036: # we might run in to problems with parameter names =~ /^v\./
7037: while (my ($key,$value) = each(%hash)) {
7038: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7039: $symb = &unescape($symb);
7040: $param = &unescape($param);
1.424 matthew 7041: next if ($v eq 'version' || $symb eq 'keys');
7042: next if (exists($returnhash{$symb}) &&
7043: exists($returnhash{$symb}->{$param}) &&
7044: $returnhash{$symb}->{'v.'.$param} > $v);
7045: $returnhash{$symb}->{$param}=$value;
7046: $returnhash{$symb}->{'v.'.$param}=$v;
7047: }
7048: #
7049: # Remove all of the keys in the hashes which keep track of
7050: # the version of the parameter.
7051: while (my ($symb,$param_hash) = each(%returnhash)) {
7052: # use a foreach because we are going to delete from the hash.
7053: foreach my $key (keys(%$param_hash)) {
7054: delete($param_hash->{$key}) if ($key =~ /^v\./);
7055: }
7056: }
7057: return \%returnhash;
1.12 www 7058: }
7059:
1.627 albertel 7060: # ------------------------------------------------------ critical inc interface
7061:
7062: sub cinc {
7063: return &inc(@_,'critical');
7064: }
7065:
1.449 matthew 7066: # --------------------------------------------------------------- inc interface
7067:
7068: sub inc {
1.627 albertel 7069: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7070: if (!$udomain) { $udomain=$env{'user.domain'}; }
7071: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7072: my $uhome=&homeserver($uname,$udomain);
7073: my $items='';
7074: if (! ref($store)) {
7075: # got a single value, so use that instead
7076: $items = &escape($store).'=&';
7077: } elsif (ref($store) eq 'SCALAR') {
7078: $items = &escape($$store).'=&';
7079: } elsif (ref($store) eq 'ARRAY') {
7080: $items = join('=&',map {&escape($_);} @{$store});
7081: } elsif (ref($store) eq 'HASH') {
7082: while (my($key,$value) = each(%{$store})) {
7083: $items.= &escape($key).'='.&escape($value).'&';
7084: }
7085: }
7086: $items=~s/\&$//;
1.627 albertel 7087: if ($critical) {
7088: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7089: } else {
7090: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7091: }
1.449 matthew 7092: }
7093:
1.12 www 7094: # --------------------------------------------------------------- put interface
7095:
7096: sub put {
1.134 albertel 7097: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7098: if (!$udomain) { $udomain=$env{'user.domain'}; }
7099: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7100: my $uhome=&homeserver($uname,$udomain);
1.12 www 7101: my $items='';
1.800 albertel 7102: foreach my $item (keys(%$storehash)) {
7103: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7104: }
1.12 www 7105: $items=~s/\&$//;
1.134 albertel 7106: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7107: }
7108:
1.631 albertel 7109: # ------------------------------------------------------------ newput interface
7110:
7111: sub newput {
7112: my ($namespace,$storehash,$udomain,$uname)=@_;
7113: if (!$udomain) { $udomain=$env{'user.domain'}; }
7114: if (!$uname) { $uname=$env{'user.name'}; }
7115: my $uhome=&homeserver($uname,$udomain);
7116: my $items='';
7117: foreach my $key (keys(%$storehash)) {
7118: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7119: }
7120: $items=~s/\&$//;
7121: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7122: }
7123:
7124: # --------------------------------------------------------- putstore interface
7125:
1.524 raeburn 7126: sub putstore {
1.1172.2.59 raeburn 7127: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7128: if (!$udomain) { $udomain=$env{'user.domain'}; }
7129: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7130: my $uhome=&homeserver($uname,$udomain);
7131: my $items='';
1.715 albertel 7132: foreach my $key (keys(%$storehash)) {
7133: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7134: }
1.715 albertel 7135: $items=~s/\&$//;
1.716 albertel 7136: my $esc_symb=&escape($symb);
7137: my $esc_v=&escape($version);
1.715 albertel 7138: my $reply =
1.716 albertel 7139: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7140: $uhome);
1.1172.2.59 raeburn 7141: if (($tolog) && ($reply eq 'ok')) {
7142: my $namevalue='';
7143: foreach my $key (keys(%{$storehash})) {
7144: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7145: }
1.1172.2.134 raeburn 7146: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7147: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7148: '&host='.&escape($perlvar{'lonHostID'}).
7149: '&version='.$esc_v.
7150: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7151: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7152: }
1.715 albertel 7153: if ($reply eq 'unknown_cmd') {
1.716 albertel 7154: # gfall back to way things use to be done
1.715 albertel 7155: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7156: $uname);
1.524 raeburn 7157: }
1.715 albertel 7158: return $reply;
7159: }
7160:
7161: sub old_putstore {
1.716 albertel 7162: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7163: if (!$udomain) { $udomain=$env{'user.domain'}; }
7164: if (!$uname) { $uname=$env{'user.name'}; }
7165: my $uhome=&homeserver($uname,$udomain);
7166: my %newstorehash;
1.800 albertel 7167: foreach my $item (keys(%$storehash)) {
7168: my $key = $version.':'.&escape($symb).':'.$item;
7169: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7170: }
7171: my $items='';
7172: my %allitems = ();
1.800 albertel 7173: foreach my $item (keys(%newstorehash)) {
7174: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7175: my $key = $1.':keys:'.$2;
7176: $allitems{$key} .= $3.':';
7177: }
1.800 albertel 7178: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7179: }
1.800 albertel 7180: foreach my $item (keys(%allitems)) {
7181: $allitems{$item} =~ s/\:$//;
7182: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7183: }
7184: $items=~s/\&$//;
7185: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7186: }
7187:
1.47 www 7188: # ------------------------------------------------------ critical put interface
7189:
7190: sub cput {
1.134 albertel 7191: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7192: if (!$udomain) { $udomain=$env{'user.domain'}; }
7193: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7194: my $uhome=&homeserver($uname,$udomain);
1.47 www 7195: my $items='';
1.800 albertel 7196: foreach my $item (keys(%$storehash)) {
7197: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7198: }
1.47 www 7199: $items=~s/\&$//;
1.134 albertel 7200: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7201: }
7202:
7203: # -------------------------------------------------------------- eget interface
7204:
7205: sub eget {
1.133 albertel 7206: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7207: my $items='';
1.800 albertel 7208: foreach my $item (@$storearr) {
7209: $items.=&escape($item).'&';
1.191 harris41 7210: }
1.12 www 7211: $items=~s/\&$//;
1.620 albertel 7212: if (!$udomain) { $udomain=$env{'user.domain'}; }
7213: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7214: my $uhome=&homeserver($uname,$udomain);
7215: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7216: my @pairs=split(/\&/,$rep);
7217: my %returnhash=();
1.42 www 7218: my $i=0;
1.800 albertel 7219: foreach my $item (@$storearr) {
7220: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7221: $i++;
1.191 harris41 7222: }
1.12 www 7223: return %returnhash;
7224: }
7225:
1.667 albertel 7226: # ------------------------------------------------------------ tmpput interface
7227: sub tmpput {
1.802 raeburn 7228: my ($storehash,$server,$context)=@_;
1.667 albertel 7229: my $items='';
1.800 albertel 7230: foreach my $item (keys(%$storehash)) {
7231: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7232: }
7233: $items=~s/\&$//;
1.802 raeburn 7234: if (defined($context)) {
7235: $items .= ':'.&escape($context);
7236: }
1.667 albertel 7237: return &reply("tmpput:$items",$server);
7238: }
7239:
7240: # ------------------------------------------------------------ tmpget interface
7241: sub tmpget {
1.688 albertel 7242: my ($token,$server)=@_;
7243: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7244: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7245: my %returnhash;
1.1172.2.85 raeburn 7246: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7247: return %returnhash;
7248: }
1.667 albertel 7249: foreach my $item (split(/\&/,$rep)) {
7250: my ($key,$value)=split(/=/,$item);
7251: $returnhash{&unescape($key)}=&thaw_unescape($value);
7252: }
7253: return %returnhash;
7254: }
7255:
1.1113 raeburn 7256: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7257: sub tmpdel {
7258: my ($token,$server)=@_;
7259: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7260: return &reply("tmpdel:$token",$server);
7261: }
7262:
1.1172.2.13 raeburn 7263: # ------------------------------------------------------------ get_timebased_id
7264:
7265: sub get_timebased_id {
7266: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7267: $maxtries) = @_;
7268: my ($newid,$error,$dellock);
7269: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7270: return ('','ok','invalid call to get suffix');
7271: }
7272:
7273: # set defaults for any optional args for which values were not supplied
7274: if ($who eq '') {
7275: $who = $env{'user.name'}.':'.$env{'user.domain'};
7276: }
7277: if (!$locktries) {
7278: $locktries = 3;
7279: }
7280: if (!$maxtries) {
7281: $maxtries = 10;
7282: }
7283:
7284: if (($cdom eq '') || ($cnum eq '')) {
7285: if ($env{'request.course.id'}) {
7286: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7287: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7288: }
7289: if (($cdom eq '') || ($cnum eq '')) {
7290: return ('','ok','call to get suffix not in course context');
7291: }
7292: }
7293:
7294: # construct locking item
7295: my $lockhash = {
7296: $prefix."\0".'locked_'.$keyid => $who,
7297: };
7298: my $tries = 0;
7299:
7300: # attempt to get lock on nohist_$namespace file
7301: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7302: while (($gotlock ne 'ok') && $tries <$locktries) {
7303: $tries ++;
7304: sleep 1;
7305: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7306: }
7307:
7308: # attempt to get unique identifier, based on current timestamp
7309: if ($gotlock eq 'ok') {
7310: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7311: my $id = time;
7312: $newid = $id;
1.1172.2.56 raeburn 7313: if ($idtype eq 'addcode') {
7314: $newid .= &sixnum_code();
7315: }
1.1172.2.13 raeburn 7316: my $idtries = 0;
7317: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7318: if ($idtype eq 'concat') {
7319: $newid = $id.$idtries;
1.1172.2.56 raeburn 7320: } elsif ($idtype eq 'addcode') {
7321: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7322: } else {
7323: $newid ++;
7324: }
7325: $idtries ++;
7326: }
7327: if (!exists($inuse{$prefix."\0".$newid})) {
7328: my %new_item = (
7329: $prefix."\0".$newid => $who,
7330: );
7331: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7332: $cdom,$cnum);
7333: if ($putresult ne 'ok') {
7334: undef($newid);
7335: $error = 'error saving new item: '.$putresult;
7336: }
7337: } else {
1.1172.2.56 raeburn 7338: undef($newid);
1.1172.2.13 raeburn 7339: $error = ('error: no unique suffix available for the new item ');
7340: }
7341: # remove lock
7342: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7343: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7344: } else {
7345: $error = "error: could not obtain lockfile\n";
7346: $dellock = 'ok';
1.1172.2.58 raeburn 7347: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7348: $dellock = 'nolock';
7349: }
1.1172.2.13 raeburn 7350: }
7351: return ($newid,$dellock,$error);
7352: }
7353:
1.1172.2.56 raeburn 7354: sub sixnum_code {
7355: my $code;
7356: for (0..6) {
7357: $code .= int( rand(9) );
7358: }
7359: return $code;
7360: }
7361:
1.765 albertel 7362: # -------------------------------------------------- portfolio access checking
7363:
7364: sub portfolio_access {
1.1172.2.77 raeburn 7365: my ($requrl,$clientip) = @_;
1.765 albertel 7366: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7367: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7368: if ($result) {
7369: my %setters;
7370: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7371: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7372: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7373: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7374: return 'B';
7375: }
7376: } else {
1.1172.2.142 raeburn 7377: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7378: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7379: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7380: return 'B';
7381: }
7382: }
7383: }
1.765 albertel 7384: if ($result eq 'ok') {
1.766 albertel 7385: return 'F';
1.765 albertel 7386: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7387: return 'A';
1.765 albertel 7388: }
1.766 albertel 7389: return '';
1.765 albertel 7390: }
7391:
7392: sub get_portfolio_access {
1.1172.2.77 raeburn 7393: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7394:
7395: if (!ref($access_hash)) {
7396: my $current_perms = &get_portfile_permissions($udom,$unum);
7397: my %access_controls = &get_access_controls($current_perms,$group,
7398: $file_name);
7399: $access_hash = $access_controls{$file_name};
7400: }
7401:
1.1172.2.77 raeburn 7402: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7403: my $now = time;
7404: if (ref($access_hash) eq 'HASH') {
7405: foreach my $key (keys(%{$access_hash})) {
7406: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7407: if ($start > $now) {
7408: next;
7409: }
7410: if ($end && $end<$now) {
7411: next;
7412: }
7413: if ($scope eq 'public') {
7414: $public = $key;
7415: last;
7416: } elsif ($scope eq 'guest') {
7417: $guest = $key;
7418: } elsif ($scope eq 'domains') {
7419: push(@domains,$key);
7420: } elsif ($scope eq 'users') {
7421: push(@users,$key);
7422: } elsif ($scope eq 'course') {
7423: push(@courses,$key);
7424: } elsif ($scope eq 'group') {
7425: push(@groups,$key);
1.1172.2.77 raeburn 7426: } elsif ($scope eq 'ip') {
7427: push(@ips,$key);
1.765 albertel 7428: }
7429: }
7430: if ($public) {
7431: return 'ok';
1.1172.2.77 raeburn 7432: } elsif (@ips > 0) {
7433: my $allowed;
7434: foreach my $ipkey (@ips) {
7435: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7436: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7437: $allowed = 1;
7438: last;
7439: }
7440: }
7441: }
7442: if ($allowed) {
7443: return 'ok';
7444: }
1.765 albertel 7445: }
7446: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7447: if ($guest) {
7448: return $guest;
7449: }
7450: } else {
7451: if (@domains > 0) {
7452: foreach my $domkey (@domains) {
7453: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7454: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7455: return 'ok';
7456: }
7457: }
7458: }
7459: }
7460: if (@users > 0) {
7461: foreach my $userkey (@users) {
1.865 raeburn 7462: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7463: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7464: if (ref($item) eq 'HASH') {
7465: if (($item->{'uname'} eq $env{'user.name'}) &&
7466: ($item->{'udom'} eq $env{'user.domain'})) {
7467: return 'ok';
7468: }
7469: }
7470: }
7471: }
1.765 albertel 7472: }
7473: }
7474: my %roleshash;
7475: my @courses_and_groups = @courses;
7476: push(@courses_and_groups,@groups);
7477: if (@courses_and_groups > 0) {
7478: my (%allgroups,%allroles);
7479: my ($start,$end,$role,$sec,$group);
7480: foreach my $envkey (%env) {
1.1060 raeburn 7481: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7482: my $cid = $2.'_'.$3;
7483: if ($1 eq 'gr') {
7484: $group = $4;
7485: $allgroups{$cid}{$group} = $env{$envkey};
7486: } else {
7487: if ($4 eq '') {
7488: $sec = 'none';
7489: } else {
7490: $sec = $4;
7491: }
7492: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7493: }
1.811 albertel 7494: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7495: my $cid = $2.'_'.$3;
7496: if ($4 eq '') {
7497: $sec = 'none';
7498: } else {
7499: $sec = $4;
7500: }
7501: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7502: }
7503: }
7504: if (keys(%allroles) == 0) {
7505: return;
7506: }
7507: foreach my $key (@courses_and_groups) {
7508: my %content = %{$$access_hash{$key}};
7509: my $cnum = $content{'number'};
7510: my $cdom = $content{'domain'};
7511: my $cid = $cdom.'_'.$cnum;
7512: if (!exists($allroles{$cid})) {
7513: next;
7514: }
7515: foreach my $role_id (keys(%{$content{'roles'}})) {
7516: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7517: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7518: my @status = @{$content{'roles'}{$role_id}{'access'}};
7519: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7520: foreach my $role (keys(%{$allroles{$cid}})) {
7521: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7522: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7523: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7524: if (grep/^all$/,@sections) {
7525: return 'ok';
7526: } else {
7527: if (grep/^$sec$/,@sections) {
7528: return 'ok';
7529: }
7530: }
7531: }
7532: }
7533: if (keys(%{$allgroups{$cid}}) == 0) {
7534: if (grep/^none$/,@groups) {
7535: return 'ok';
7536: }
7537: } else {
7538: if (grep/^all$/,@groups) {
7539: return 'ok';
7540: }
7541: foreach my $group (keys(%{$allgroups{$cid}})) {
7542: if (grep/^$group$/,@groups) {
7543: return 'ok';
7544: }
7545: }
7546: }
7547: }
7548: }
7549: }
7550: }
7551: }
7552: if ($guest) {
7553: return $guest;
7554: }
7555: }
7556: }
7557: return;
7558: }
7559:
7560: sub course_group_datechecker {
7561: my ($dates,$now,$status) = @_;
7562: my ($start,$end) = split(/\./,$dates);
7563: if (!$start && !$end) {
7564: return 'ok';
7565: }
7566: if (grep/^active$/,@{$status}) {
7567: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7568: return 'ok';
7569: }
7570: }
7571: if (grep/^previous$/,@{$status}) {
7572: if ($end > $now ) {
7573: return 'ok';
7574: }
7575: }
7576: if (grep/^future$/,@{$status}) {
7577: if ($start > $now) {
7578: return 'ok';
7579: }
7580: }
7581: return;
7582: }
7583:
7584: sub parse_portfolio_url {
7585: my ($url) = @_;
7586:
7587: my ($type,$udom,$unum,$group,$file_name);
7588:
1.823 albertel 7589: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7590: $type = 1;
7591: $udom = $1;
7592: $unum = $2;
7593: $file_name = $3;
1.823 albertel 7594: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7595: $type = 2;
7596: $udom = $1;
7597: $unum = $2;
7598: $group = $3;
7599: $file_name = $3.'/'.$4;
7600: }
7601: if (wantarray) {
7602: return ($type,$udom,$unum,$file_name,$group);
7603: }
7604: return $type;
7605: }
7606:
7607: sub is_portfolio_url {
7608: my ($url) = @_;
7609: return scalar(&parse_portfolio_url($url));
7610: }
7611:
1.798 raeburn 7612: sub is_portfolio_file {
7613: my ($file) = @_;
1.820 raeburn 7614: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7615: return 1;
7616: }
7617: return;
7618: }
7619:
1.976 raeburn 7620: sub usertools_access {
1.1084 raeburn 7621: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7622: my ($access,%tools);
7623: if ($context eq '') {
7624: $context = 'tools';
7625: }
7626: if ($context eq 'requestcourses') {
7627: %tools = (
7628: official => 1,
7629: unofficial => 1,
1.1006 raeburn 7630: community => 1,
1.1172.2.37 raeburn 7631: textbook => 1,
1.985 raeburn 7632: );
1.1172.2.9 raeburn 7633: } elsif ($context eq 'requestauthor') {
7634: %tools = (
7635: requestauthor => 1,
7636: );
1.985 raeburn 7637: } else {
7638: %tools = (
7639: aboutme => 1,
7640: blog => 1,
1.1172.2.6 raeburn 7641: webdav => 1,
1.985 raeburn 7642: portfolio => 1,
7643: );
7644: }
1.976 raeburn 7645: return if (!defined($tools{$tool}));
7646:
1.1172.2.35 raeburn 7647: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7648: $udom = $env{'user.domain'};
7649: $uname = $env{'user.name'};
7650: }
7651:
1.978 raeburn 7652: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7653: if ($action ne 'reload') {
1.985 raeburn 7654: if ($context eq 'requestcourses') {
7655: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7656: } elsif ($context eq 'requestauthor') {
7657: return $env{'environment.canrequest.author'};
1.985 raeburn 7658: } else {
7659: return $env{'environment.availabletools.'.$tool};
7660: }
7661: }
1.976 raeburn 7662: }
7663:
1.1172.2.9 raeburn 7664: my ($toolstatus,$inststatus,$envkey);
7665: if ($context eq 'requestauthor') {
7666: $envkey = $context;
7667: } else {
7668: $envkey = $context.'.'.$tool;
7669: }
1.976 raeburn 7670:
1.985 raeburn 7671: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7672: ($action ne 'reload')) {
1.1172.2.9 raeburn 7673: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7674: $inststatus = $env{'environment.inststatus'};
7675: } else {
1.1084 raeburn 7676: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7677: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7678: $inststatus = $userenvref->{'inststatus'};
7679: } else {
1.1172.2.9 raeburn 7680: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7681: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7682: $inststatus = $userenv{'inststatus'};
7683: }
1.976 raeburn 7684: }
7685:
7686: if ($toolstatus ne '') {
7687: if ($toolstatus) {
7688: $access = 1;
7689: } else {
7690: $access = 0;
7691: }
7692: return $access;
7693: }
7694:
1.1084 raeburn 7695: my ($is_adv,%domdef);
7696: if (ref($is_advref) eq 'HASH') {
7697: $is_adv = $is_advref->{'is_adv'};
7698: } else {
7699: $is_adv = &is_advanced_user($udom,$uname);
7700: }
7701: if (ref($domdefref) eq 'HASH') {
7702: %domdef = %{$domdefref};
7703: } else {
7704: %domdef = &get_domain_defaults($udom);
7705: }
1.976 raeburn 7706: if (ref($domdef{$tool}) eq 'HASH') {
7707: if ($is_adv) {
7708: if ($domdef{$tool}{'_LC_adv'} ne '') {
7709: if ($domdef{$tool}{'_LC_adv'}) {
7710: $access = 1;
7711: } else {
7712: $access = 0;
7713: }
7714: return $access;
7715: }
7716: }
7717: if ($inststatus ne '') {
7718: my ($hasaccess,$hasnoaccess);
7719: foreach my $affiliation (split(/:/,$inststatus)) {
7720: if ($domdef{$tool}{$affiliation} ne '') {
7721: if ($domdef{$tool}{$affiliation}) {
7722: $hasaccess = 1;
7723: } else {
7724: $hasnoaccess = 1;
7725: }
7726: }
7727: }
7728: if ($hasaccess || $hasnoaccess) {
7729: if ($hasaccess) {
7730: $access = 1;
7731: } elsif ($hasnoaccess) {
7732: $access = 0;
7733: }
7734: return $access;
7735: }
7736: } else {
7737: if ($domdef{$tool}{'default'} ne '') {
7738: if ($domdef{$tool}{'default'}) {
7739: $access = 1;
7740: } elsif ($domdef{$tool}{'default'} == 0) {
7741: $access = 0;
7742: }
7743: return $access;
7744: }
7745: }
7746: } else {
1.1172.2.6 raeburn 7747: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7748: $access = 1;
7749: } else {
7750: $access = 0;
7751: }
1.976 raeburn 7752: return $access;
7753: }
7754: }
7755:
1.1050 raeburn 7756: sub is_course_owner {
7757: my ($cdom,$cnum,$udom,$uname) = @_;
7758: if (($udom eq '') || ($uname eq '')) {
7759: $udom = $env{'user.domain'};
7760: $uname = $env{'user.name'};
7761: }
7762: unless (($udom eq '') || ($uname eq '')) {
7763: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7764: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7765: return 1;
7766: } else {
7767: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7768: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7769: return 1;
7770: }
7771: }
7772: }
7773: }
7774: return;
7775: }
7776:
1.976 raeburn 7777: sub is_advanced_user {
7778: my ($udom,$uname) = @_;
1.1085 raeburn 7779: if ($udom ne '' && $uname ne '') {
7780: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7781: if (wantarray) {
7782: return ($env{'user.adv'},$env{'user.author'});
7783: } else {
7784: return $env{'user.adv'};
7785: }
1.1085 raeburn 7786: }
7787: }
1.976 raeburn 7788: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7789: my %allroles;
1.1128 raeburn 7790: my ($is_adv,$is_author);
1.976 raeburn 7791: foreach my $role (keys(%roleshash)) {
7792: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7793: my $area = '/'.$tdomain.'/'.$trest;
7794: if ($sec ne '') {
7795: $area .= '/'.$sec;
7796: }
7797: if (($area ne '') && ($trole ne '')) {
7798: my $spec=$trole.'.'.$area;
7799: if ($trole =~ /^cr\//) {
7800: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7801: } elsif ($trole ne 'gr') {
7802: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7803: }
1.1128 raeburn 7804: if ($trole eq 'au') {
7805: $is_author = 1;
7806: }
1.976 raeburn 7807: }
7808: }
7809: foreach my $role (keys(%allroles)) {
7810: last if ($is_adv);
7811: foreach my $item (split(/:/,$allroles{$role})) {
7812: if ($item ne '') {
7813: my ($privilege,$restrictions)=split(/&/,$item);
7814: if ($privilege eq 'adv') {
7815: $is_adv = 1;
7816: last;
7817: }
7818: }
7819: }
7820: }
1.1128 raeburn 7821: if (wantarray) {
7822: return ($is_adv,$is_author);
7823: }
1.976 raeburn 7824: return $is_adv;
7825: }
1.798 raeburn 7826:
1.1035 raeburn 7827: sub check_can_request {
1.1036 raeburn 7828: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7829: my $canreq = 0;
7830: my ($types,$typename) = &Apache::loncommon::course_types();
7831: my @options = ('approval','validate','autolimit');
7832: my $optregex = join('|',@options);
7833: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7834: foreach my $type (@{$types}) {
7835: if (&usertools_access($env{'user.name'},
7836: $env{'user.domain'},
7837: $type,undef,'requestcourses')) {
7838: $canreq ++;
1.1036 raeburn 7839: if (ref($request_domains) eq 'HASH') {
7840: push(@{$request_domains->{$type}},$env{'user.domain'});
7841: }
1.1035 raeburn 7842: if ($dom eq $env{'user.domain'}) {
7843: $can_request->{$type} = 1;
7844: }
7845: }
7846: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7847: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7848: if (@curr > 0) {
1.1036 raeburn 7849: foreach my $item (@curr) {
7850: if (ref($request_domains) eq 'HASH') {
7851: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7852: if ($otherdom ne '') {
7853: if (ref($request_domains->{$type}) eq 'ARRAY') {
7854: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7855: push(@{$request_domains->{$type}},$otherdom);
7856: }
7857: } else {
7858: push(@{$request_domains->{$type}},$otherdom);
7859: }
7860: }
7861: }
7862: }
7863: unless($dom eq $env{'user.domain'}) {
7864: $canreq ++;
1.1035 raeburn 7865: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7866: $can_request->{$type} = 1;
7867: }
7868: }
7869: }
7870: }
7871: }
7872: }
7873: return $canreq;
7874: }
7875:
1.341 www 7876: # ---------------------------------------------- Custom access rule evaluation
7877:
7878: sub customaccess {
7879: my ($priv,$uri)=@_;
1.807 albertel 7880: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7881: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7882: $udom = &LONCAPA::clean_domain($udom);
7883: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7884: my $access=0;
1.800 albertel 7885: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7886: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7887: if ($type eq 'user') {
7888: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7889: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7890: if ($tdom) {
7891: if ($tdom ne $env{'user.domain'}) { next; }
7892: }
1.896 albertel 7893: if ($tuname) {
7894: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7895: }
7896: $access=($effect eq 'allow');
7897: last;
7898: }
7899: } else {
7900: if ($role) {
7901: if ($role ne $urole) { next; }
7902: }
7903: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7904: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7905: if ($tdom) {
7906: if ($tdom ne $udom) { next; }
7907: }
7908: if ($tcrs) {
7909: if ($tcrs ne $ucrs) { next; }
7910: }
7911: if ($tsec) {
7912: if ($tsec ne $usec) { next; }
7913: }
7914: $access=($effect eq 'allow');
7915: last;
7916: }
7917: if ($realm eq '' && $role eq '') {
7918: $access=($effect eq 'allow');
7919: }
1.402 bowersj2 7920: }
1.341 www 7921: }
7922: return $access;
7923: }
7924:
1.103 harris41 7925: # ------------------------------------------------- Check for a user privilege
1.12 www 7926:
7927: sub allowed {
1.1172.2.126 raeburn 7928: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7929: my $ver_orguri=$uri;
1.439 www 7930: $uri=&deversion($uri);
1.152 www 7931: my $orguri=$uri;
1.52 www 7932: $uri=&declutter($uri);
1.809 raeburn 7933:
1.810 raeburn 7934: if ($priv eq 'evb') {
7935: # Evade communication block restrictions for specified role in a course
7936: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7937: return $1;
7938: } else {
7939: return;
7940: }
7941: }
7942:
1.620 albertel 7943: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7944: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7945: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7946: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7947: && ($priv eq 'bre')) {
1.14 www 7948: return 'F';
1.159 www 7949: }
7950:
1.545 banghart 7951: # Free bre access to user's own portfolio contents
1.714 raeburn 7952: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7953: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7954: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7955: my %setters;
1.1172.2.142 raeburn 7956: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7957: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7958: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7959: return 'B';
7960: } else {
7961: return 'F';
7962: }
1.545 banghart 7963: }
7964:
1.762 raeburn 7965: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7966: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7967: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7968: if (exists($env{'request.course.id'})) {
7969: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7970: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7971: if (($domain eq $cdom) && ($name eq $cnum)) {
7972: my $courseprivid=$env{'request.course.id'};
7973: $courseprivid=~s/\_/\//;
7974: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7975: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7976: return $1;
1.762 raeburn 7977: } else {
7978: if ($env{'request.course.sec'}) {
7979: $courseprivid.='/'.$env{'request.course.sec'};
7980: }
7981: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7982: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7983: return $2;
7984: }
1.714 raeburn 7985: }
7986: }
7987: }
7988: }
7989:
1.159 www 7990: # Free bre to public access
7991:
7992: if ($priv eq 'bre') {
1.238 www 7993: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7994: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7995: return 'F';
7996: }
1.238 www 7997: if ($copyright eq 'priv') {
7998: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7999: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8000: return '';
8001: }
8002: }
8003: if ($copyright eq 'domain') {
8004: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8005: unless (($env{'user.domain'} eq $1) ||
8006: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8007: return '';
8008: }
1.262 matthew 8009: }
1.620 albertel 8010: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8011: # Library role, so allow browsing of resources in this domain.
8012: return 'F';
1.238 www 8013: }
1.341 www 8014: if ($copyright eq 'custom') {
8015: unless (&customaccess($priv,$uri)) { return ''; }
8016: }
1.14 www 8017: }
1.264 matthew 8018: # Domain coordinator is trying to create a course
1.620 albertel 8019: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8020: # uri is the requested domain in this case.
8021: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8022: # a role of dc for the domain in question.
1.620 albertel 8023: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8024: }
1.29 www 8025:
1.52 www 8026: my $thisallowed='';
8027: my $statecond=0;
8028: my $courseprivid='';
8029:
1.1039 raeburn 8030: my $ownaccess;
1.1043 raeburn 8031: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8032: if (($priv eq 'bro') && ($env{'user.author'})) {
8033: if ($uri eq '') {
8034: $ownaccess = 1;
8035: } else {
8036: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8037: my $udom = $env{'user.domain'};
8038: my $uname = $env{'user.name'};
8039: if ($uri =~ m{^\Q$udom\E/?$}) {
8040: $ownaccess = 1;
1.1040 raeburn 8041: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8042: unless ($uri =~ m{\.\./}) {
8043: $ownaccess = 1;
8044: }
8045: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8046: my $now = time;
8047: if ($uri =~ m{^([^/]+)/?$}) {
8048: my $adom = $1;
8049: foreach my $key (keys(%env)) {
1.1042 raeburn 8050: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8051: my ($start,$end) = split(/\./,$env{$key});
8052: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8053: $ownaccess = 1;
8054: last;
8055: }
8056: }
8057: }
8058: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8059: my $adom = $1;
8060: my $aname = $2;
1.1042 raeburn 8061: foreach my $role ('ca','aa') {
8062: if ($env{"user.role.$role./$adom/$aname"}) {
8063: my ($start,$end) =
1.1172.2.142 raeburn 8064: split(/\./,$env{"user.role.$role./$adom/$aname"});
8065: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8066: $ownaccess = 1;
8067: last;
8068: }
1.1039 raeburn 8069: }
8070: }
8071: }
8072: }
8073: }
8074: }
8075: }
8076:
1.52 www 8077: # Course
8078:
1.620 albertel 8079: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8080: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8081: $thisallowed.=$1;
8082: }
1.52 www 8083: }
1.29 www 8084:
1.52 www 8085: # Domain
8086:
1.620 albertel 8087: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8088: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8089: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8090: $thisallowed.=$1;
8091: }
1.12 www 8092: }
1.52 www 8093:
1.1141 raeburn 8094: # User who is not author or co-author might still be able to edit
8095: # resource of an author in the domain (e.g., if Domain Coordinator).
8096: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8097: (&allowed('mdc',$env{'request.course.id'}))) {
8098: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8099: $thisallowed.=$1;
8100: }
8101: }
8102:
1.52 www 8103: # Course: uri itself is a course
1.66 www 8104: my $courseuri=$uri;
8105: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8106: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8107:
1.620 albertel 8108: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8109: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8110: if ($priv eq 'mip') {
8111: my $rem = $1;
8112: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8113: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8114: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8115: if ($cdom ne '') {
8116: my %passwdconf = &get_passwdconf($cdom);
8117: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8118: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8119: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8120: my @inststatuses = split(':',$env{'environment.inststatus'});
8121: unless (@inststatuses) {
8122: @inststatuses = ('default');
8123: }
8124: foreach my $status (@inststatuses) {
8125: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8126: $thisallowed.=$rem;
8127: }
8128: }
8129: }
8130: }
8131: }
8132: }
8133: }
8134: } else {
8135: unless (($priv eq 'bro') && (!$ownaccess)) {
8136: $thisallowed.=$1;
8137: }
1.1039 raeburn 8138: }
1.12 www 8139: }
1.29 www 8140:
1.665 albertel 8141: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8142: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8143: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8144: $thisallowed='';
1.671 raeburn 8145: my ($match)=&is_on_map($uri);
8146: if ($match) {
8147: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8148: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8149: my $value = $1;
8150: if ($noblockcheck) {
8151: $thisallowed.=$value;
1.1162 raeburn 8152: } else {
1.1172.2.126 raeburn 8153: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8154: if (@blockers > 0) {
8155: $thisallowed = 'B';
8156: } else {
8157: $thisallowed.=$value;
8158: }
1.1162 raeburn 8159: }
1.671 raeburn 8160: }
8161: } else {
1.705 albertel 8162: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8163: if ($refuri) {
8164: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8165: $thisallowed='F';
1.671 raeburn 8166: } else {
8167: $refuri=&declutter($refuri);
8168: my ($match) = &is_on_map($refuri);
8169: if ($match) {
1.1172.2.65 raeburn 8170: if ($noblockcheck) {
1.1162 raeburn 8171: $thisallowed='F';
1.1172.2.65 raeburn 8172: } else {
1.1172.2.127 raeburn 8173: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8174: if (@blockers > 0) {
8175: $thisallowed = 'B';
8176: } else {
8177: $thisallowed='F';
8178: }
1.1162 raeburn 8179: }
1.671 raeburn 8180: }
1.669 raeburn 8181: }
1.671 raeburn 8182: }
8183: }
1.314 www 8184: }
1.492 albertel 8185:
1.766 albertel 8186: if ($priv eq 'bre'
8187: && $thisallowed ne 'F'
8188: && $thisallowed ne '2'
8189: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8190: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8191: }
8192:
1.52 www 8193: # Full access at system, domain or course-wide level? Exit.
1.29 www 8194: if ($thisallowed=~/F/) {
8195: return 'F';
8196: }
8197:
1.52 www 8198: # If this is generating or modifying users, exit with special codes
1.29 www 8199:
1.643 www 8200: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8201: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8202: my ($audom,$auname)=split('/',$uri);
1.643 www 8203: # no author name given, so this just checks on the general right to make a co-author in this domain
8204: unless ($auname) { return $thisallowed; }
8205: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8206: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8207: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8208: ($audom ne $env{'request.role.domain'}))) { return ''; }
8209: }
1.52 www 8210: return $thisallowed;
8211: }
8212: #
1.103 harris41 8213: # Gathered so far: system, domain and course wide privileges
1.52 www 8214: #
8215: # Course: See if uri or referer is an individual resource that is part of
8216: # the course
8217:
1.620 albertel 8218: if ($env{'request.course.id'}) {
1.232 www 8219:
1.1172.2.115 raeburn 8220: # If this is modifying password (internal auth) domains must match for user and user's role.
8221:
8222: if ($priv eq 'mip') {
8223: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8224: return $thisallowed;
8225: } else {
8226: return '';
8227: }
8228: }
8229:
1.620 albertel 8230: $courseprivid=$env{'request.course.id'};
8231: if ($env{'request.course.sec'}) {
8232: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8233: }
8234: $courseprivid=~s/\_/\//;
8235: my $checkreferer=1;
1.232 www 8236: my ($match,$cond)=&is_on_map($uri);
8237: if ($match) {
8238: $statecond=$cond;
1.620 albertel 8239: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8240: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8241: my $value = $1;
8242: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8243: if ($noblockcheck) {
1.1162 raeburn 8244: $thisallowed.=$value;
1.1172.2.65 raeburn 8245: } else {
1.1172.2.126 raeburn 8246: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8247: if (@blockers > 0) {
8248: $thisallowed = 'B';
8249: } else {
8250: $thisallowed.=$value;
8251: }
1.1162 raeburn 8252: }
8253: } else {
8254: $thisallowed.=$value;
8255: }
1.52 www 8256: $checkreferer=0;
8257: }
1.29 www 8258: }
1.1172.2.126 raeburn 8259:
1.148 www 8260: if ($checkreferer) {
1.620 albertel 8261: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8262: unless ($refuri) {
1.800 albertel 8263: foreach my $key (keys(%env)) {
8264: if ($key=~/^httpref\..*\*/) {
8265: my $pattern=$key;
1.156 www 8266: $pattern=~s/^httpref\.\/res\///;
1.148 www 8267: $pattern=~s/\*/\[\^\/\]\+/g;
8268: $pattern=~s/\//\\\//g;
1.152 www 8269: if ($orguri=~/$pattern/) {
1.800 albertel 8270: $refuri=$env{$key};
1.148 www 8271: }
8272: }
1.191 harris41 8273: }
1.148 www 8274: }
1.232 www 8275:
1.148 www 8276: if ($refuri) {
1.152 www 8277: $refuri=&declutter($refuri);
1.232 www 8278: my ($match,$cond)=&is_on_map($refuri);
8279: if ($match) {
8280: my $refstatecond=$cond;
1.620 albertel 8281: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8282: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8283: my $value = $1;
8284: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8285: if ($noblockcheck) {
1.1162 raeburn 8286: $thisallowed.=$value;
1.1172.2.65 raeburn 8287: } else {
1.1172.2.127 raeburn 8288: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8289: if (@blockers > 0) {
8290: $thisallowed = 'B';
8291: } else {
8292: $thisallowed.=$value;
8293: }
1.1162 raeburn 8294: }
8295: } else {
8296: $thisallowed.=$value;
8297: }
1.53 www 8298: $uri=$refuri;
8299: $statecond=$refstatecond;
1.52 www 8300: }
8301: }
1.148 www 8302: }
1.29 www 8303: }
1.52 www 8304: }
1.29 www 8305:
1.52 www 8306: #
1.103 harris41 8307: # Gathered now: all privileges that could apply, and condition number
1.52 www 8308: #
8309: #
8310: # Full or no access?
8311: #
1.29 www 8312:
1.52 www 8313: if ($thisallowed=~/F/) {
8314: return 'F';
8315: }
1.29 www 8316:
1.52 www 8317: unless ($thisallowed) {
8318: return '';
8319: }
1.29 www 8320:
1.52 www 8321: # Restrictions exist, deal with them
8322: #
8323: # C:according to course preferences
8324: # R:according to resource settings
8325: # L:unless locked
8326: # X:according to user session state
8327: #
8328:
8329: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8330: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8331: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8332: # courses, and 2 minutes for current course, in which user has st or ta role
8333: # which is neither expired nor a future role (unless current course).
1.52 www 8334:
1.1172.2.142 raeburn 8335: my ($needlockcheck,$now,$crsonly);
1.52 www 8336: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8337: $now = time;
8338: if ($priv eq 'bre') {
8339: if ($uri ne '') {
8340: if ($orguri =~ m{^/+res/}) {
8341: if ($uri =~ m{^lib/templates/}) {
8342: if ($env{'request.course.id'}) {
8343: $crsonly = 1;
8344: $needlockcheck = 1;
8345: }
8346: } else {
8347: $needlockcheck = 1;
8348: }
8349: } elsif ($env{'request.course.id'}) {
8350: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8351: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8352: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8353: $crsonly = 1;
8354: }
8355: $needlockcheck = 1;
8356: }
8357: }
8358: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8359: $needlockcheck = 1;
8360: }
8361: }
8362: if ($needlockcheck) {
8363: foreach my $envkey (keys(%env)) {
1.54 www 8364: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8365: my $courseid=$2;
8366: my $roleid=$1.'.'.$2;
1.92 www 8367: $courseid=~s/^\///;
1.1172.2.142 raeburn 8368: unless ($env{'request.role'} eq $roleid) {
8369: my ($start,$end) = split(/\./,$env{$envkey});
8370: next unless (($now >= $start) && (!$end || $end > $now));
8371: }
1.54 www 8372: my $expiretime=600;
1.620 albertel 8373: if ($env{'request.role'} eq $roleid) {
1.54 www 8374: $expiretime=120;
8375: }
8376: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8377: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8378: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8379: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8380: }
1.620 albertel 8381: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8382: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8383: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8384: &log($env{'user.domain'},$env{'user.name'},
8385: $env{'user.home'},
1.57 www 8386: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8387: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8388: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8389: return '';
8390: }
8391: }
1.620 albertel 8392: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8393: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8394: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8395: &log($env{'user.domain'},$env{'user.name'},
8396: $env{'user.home'},
1.57 www 8397: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8398: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8399: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8400: return '';
8401: }
8402: }
8403: }
1.29 www 8404: }
1.52 www 8405: }
1.1172.2.126 raeburn 8406:
1.52 www 8407: #
8408: # Rest of the restrictions depend on selected course
8409: #
8410:
1.620 albertel 8411: unless ($env{'request.course.id'}) {
1.766 albertel 8412: if ($thisallowed eq 'A') {
8413: return 'A';
1.814 raeburn 8414: } elsif ($thisallowed eq 'B') {
8415: return 'B';
1.766 albertel 8416: } else {
8417: return '1';
8418: }
1.52 www 8419: }
1.29 www 8420:
1.52 www 8421: #
8422: # Now user is definitely in a course
8423: #
1.53 www 8424:
8425:
8426: # Course preferences
8427:
8428: if ($thisallowed=~/C/) {
1.620 albertel 8429: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8430: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8431: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8432: =~/\Q$rolecode\E/) {
1.1103 raeburn 8433: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8434: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8435: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8436: $env{'request.course.id'});
8437: }
1.237 www 8438: return '';
8439: }
8440:
1.620 albertel 8441: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8442: =~/\Q$unamedom\E/) {
1.1103 raeburn 8443: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8444: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8445: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8446: $env{'request.course.id'});
8447: }
1.54 www 8448: return '';
8449: }
1.53 www 8450: }
8451:
8452: # Resource preferences
8453:
8454: if ($thisallowed=~/R/) {
1.620 albertel 8455: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8456: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8457: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8458: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8459: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8460: }
8461: return '';
1.54 www 8462: }
1.53 www 8463: }
1.30 www 8464:
1.246 www 8465: # Restricted by state or randomout?
1.30 www 8466:
1.52 www 8467: if ($thisallowed=~/X/) {
1.620 albertel 8468: if ($env{'acc.randomout'}) {
1.579 albertel 8469: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8470: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8471: return '';
8472: }
1.247 www 8473: }
8474: if (&condval($statecond)) {
1.52 www 8475: return '2';
8476: } else {
8477: return '';
8478: }
8479: }
1.30 www 8480:
1.766 albertel 8481: if ($thisallowed eq 'A') {
8482: return 'A';
1.814 raeburn 8483: } elsif ($thisallowed eq 'B') {
8484: return 'B';
1.766 albertel 8485: }
1.52 www 8486: return 'F';
1.232 www 8487: }
1.1162 raeburn 8488:
1.1172.2.13 raeburn 8489: # ------------------------------------------- Check construction space access
8490:
8491: sub constructaccess {
8492: my ($url,$setpriv)=@_;
8493:
8494: # We do not allow editing of previous versions of files
8495: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8496:
8497: # Get username and domain from URL
8498: my ($ownername,$ownerdomain,$ownerhome);
8499:
8500: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8501: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8502:
8503: # The URL does not really point to any authorspace, forget it
8504: unless (($ownername) && ($ownerdomain)) { return ''; }
8505:
8506: # Now we need to see if the user has access to the authorspace of
8507: # $ownername at $ownerdomain
8508:
8509: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8510: # Real author for this?
8511: $ownerhome = $env{'user.home'};
8512: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8513: return ($ownername,$ownerdomain,$ownerhome);
8514: }
8515: } else {
8516: # Co-author for this?
8517: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8518: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8519: $ownerhome = &homeserver($ownername,$ownerdomain);
8520: return ($ownername,$ownerdomain,$ownerhome);
8521: }
8522: }
8523:
8524: # We don't have any access right now. If we are not possibly going to do anything about this,
8525: # we might as well leave
8526: unless ($setpriv) { return ''; }
8527:
8528: # Backdoor access?
8529: my $allowed=&allowed('eco',$ownerdomain);
8530: # Nope
8531: unless ($allowed) { return ''; }
8532: # Looks like we may have access, but could be locked by the owner of the construction space
8533: if ($allowed eq 'U') {
8534: my %blocked=&get('environment',['domcoord.author'],
8535: $ownerdomain,$ownername);
8536: # Is blocked by owner
8537: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8538: }
8539: if (($allowed eq 'F') || ($allowed eq 'U')) {
8540: # Grant temporary access
8541: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8542: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8543: if (!$update) { $update = $then; }
8544: my $refresh=$env{'user.refresh.time'};
8545: if (!$refresh) { $refresh = $update; }
8546: my $now = time;
8547: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8548: $now,'ca','constructaccess');
8549: $ownerhome = &homeserver($ownername,$ownerdomain);
8550: return($ownername,$ownerdomain,$ownerhome);
8551: }
8552: # No business here
8553: return '';
8554: }
8555:
1.1172.2.66 raeburn 8556: # ----------------------------------------------------------- Content Blocking
8557:
8558: {
8559: # Caches for faster Course Contents display where content blocking
8560: # is in operation (i.e., interval param set) for timed quiz.
8561: #
8562: # User for whom data are being temporarily cached.
8563: my $cacheduser='';
1.1172.2.126 raeburn 8564: # Course for which data are being temporarily cached.
8565: my $cachedcid='';
1.1172.2.66 raeburn 8566: # Cached blockers for this user (a hash of blocking items).
8567: my %cachedblockers=();
8568: # When the data were last cached.
8569: my $cachedlast='';
8570:
8571: sub load_all_blockers {
1.1172.2.128 raeburn 8572: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8573: if (($uname ne '') && ($udom ne '')) {
8574: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8575: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8576: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8577: return;
8578: }
8579: }
8580: $cachedlast=time;
8581: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8582: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8583: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8584: return;
1.1172.2.66 raeburn 8585: }
8586:
1.1162 raeburn 8587: sub get_comm_blocks {
8588: my ($cdom,$cnum) = @_;
8589: if ($cdom eq '' || $cnum eq '') {
8590: return unless ($env{'request.course.id'});
8591: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8592: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8593: }
8594: my %commblocks;
8595: my $hashid=$cdom.'_'.$cnum;
8596: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8597: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8598: %commblocks = %{$blocksref};
8599: } else {
8600: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8601: my $cachetime = 600;
8602: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8603: }
8604: return %commblocks;
8605: }
8606:
1.1172.2.66 raeburn 8607: sub get_commblock_resources {
8608: my ($blocks) = @_;
8609: my %blockers = ();
8610: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8611: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8612: if ($env{'request.course.sec'}) {
8613: $courseurl .= '/'.$env{'request.course.sec'};
8614: }
8615: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8616: my %commblocks;
8617: if (ref($blocks) eq 'HASH') {
8618: %commblocks = %{$blocks};
8619: } else {
8620: %commblocks = &get_comm_blocks();
8621: }
1.1172.2.66 raeburn 8622: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8623: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8624: return %blockers unless (ref($navmap));
8625: my $now = time;
1.1162 raeburn 8626: foreach my $block (keys(%commblocks)) {
8627: if ($block =~ /^(\d+)____(\d+)$/) {
8628: my ($start,$end) = ($1,$2);
8629: if ($start <= $now && $end >= $now) {
8630: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8631: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8632: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8633: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8634: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8635: }
8636: }
8637: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8638: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8639: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8640: }
8641: }
8642: }
8643: }
8644: }
8645: } elsif ($block =~ /^firstaccess____(.+)$/) {
8646: my $item = $1;
8647: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8648: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8649: my (@interval,$mapname);
1.1172.2.66 raeburn 8650: my $type = 'map';
8651: if ($item eq 'course') {
8652: $type = 'course';
8653: @interval=&EXT("resource.0.interval");
8654: } else {
8655: if ($item =~ /___\d+___/) {
8656: $type = 'resource';
8657: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8658: } else {
1.1172.2.142 raeburn 8659: $mapname = &deversion($item);
8660: if (ref($navmap)) {
8661: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8662: @interval = ($timelimit,'map');
1.1162 raeburn 8663: }
8664: }
1.1172.2.66 raeburn 8665: }
8666: if ($interval[0] =~ /^\d+$/) {
8667: my $first_access;
8668: if ($type eq 'resource') {
8669: $first_access=&get_first_access($interval[1],$item);
8670: } elsif ($type eq 'map') {
8671: $first_access=&get_first_access($interval[1],undef,$item);
8672: } else {
8673: $first_access=&get_first_access($interval[1]);
8674: }
8675: if ($first_access) {
8676: my $timesup = $first_access+$interval[0];
8677: if ($timesup > $now) {
8678: my $activeblock;
1.1172.2.142 raeburn 8679: if ($type eq 'resource') {
8680: if (ref($navmap)) {
8681: my $res = $navmap->getBySymb($item);
8682: if ($res->answerable()) {
8683: $activeblock = 1;
8684: }
8685: }
8686: } elsif ($type eq 'map') {
8687: my $mapsymb = &symbread($mapname,1);
8688: if (($mapsymb) && (ref($navmap))) {
8689: my $mapres = $navmap->getBySymb($mapsymb);
8690: if (ref($mapres)) {
8691: my $first = $mapres->map_start();
8692: my $finish = $mapres->map_finish();
8693: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8694: if (ref($it)) {
8695: my $res;
8696: while ($res = $it->next(undef,1)) {
8697: next unless (ref($res));
8698: my $symb = $res->symb();
8699: next if (($symb eq $mapsymb) || ($symb eq ''));
8700: @interval=&EXT("resource.0.interval",$symb);
8701: if ($interval[1] eq 'map') {
8702: if ($res->answerable()) {
8703: $activeblock = 1;
8704: last;
8705: }
8706: }
8707: }
8708: }
8709: }
1.1172.2.66 raeburn 8710: }
8711: }
8712: if ($activeblock) {
8713: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8714: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8715: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8716: }
8717: }
8718: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8719: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8720: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8721: }
1.1162 raeburn 8722: }
8723: }
8724: }
8725: }
8726: }
8727: }
8728: }
8729: }
8730: }
1.1172.2.66 raeburn 8731: return %blockers;
1.1162 raeburn 8732: }
8733:
1.1172.2.66 raeburn 8734: sub has_comm_blocking {
1.1172.2.128 raeburn 8735: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8736: my @blockers;
8737: return unless ($env{'request.course.id'});
8738: return unless ($priv eq 'bre');
8739: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8740: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8741: if ($env{'request.course.sec'}) {
8742: $courseurl .= '/'.$env{'request.course.sec'};
8743: }
8744: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8745: my %blockinfo;
8746: if (ref($blocks) eq 'HASH') {
8747: %blockinfo = &get_commblock_resources($blocks);
8748: } else {
8749: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8750: %blockinfo = %cachedblockers;
8751: }
8752: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8753: my (%possibles,@symbs);
8754: if (!$symb) {
1.1172.2.128 raeburn 8755: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8756: }
1.1172.2.66 raeburn 8757: if ($symb) {
8758: @symbs = ($symb);
8759: } elsif (keys(%possibles)) {
8760: @symbs = keys(%possibles);
8761: }
8762: my $noblock;
8763: foreach my $symb (@symbs) {
8764: last if ($noblock);
8765: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8766: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8767: if ($block =~ /^firstaccess____(.+)$/) {
8768: my $item = $1;
1.1172.2.126 raeburn 8769: unless ($blocked) {
8770: if (($item eq $map) || ($item eq $symb)) {
8771: $noblock = 1;
8772: last;
8773: }
1.1172.2.66 raeburn 8774: }
1.1162 raeburn 8775: }
1.1172.2.128 raeburn 8776: if (ref($blockinfo{$block}) eq 'HASH') {
8777: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8778: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8779: unless (grep(/^\Q$block\E$/,@blockers)) {
8780: push(@blockers,$block);
8781: }
8782: }
8783: }
1.1172.2.128 raeburn 8784: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8785: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8786: unless (grep(/^\Q$block\E$/,@blockers)) {
8787: push(@blockers,$block);
8788: }
1.1172.2.66 raeburn 8789: }
8790: }
1.1162 raeburn 8791: }
8792: }
8793: }
1.1172.2.126 raeburn 8794: unless ($noblock) {
8795: return @blockers;
8796: }
8797: return;
1.1172.2.66 raeburn 8798: }
1.1162 raeburn 8799: }
8800:
1.1172.2.66 raeburn 8801: # -------------------------------- Deversion and split uri into path an filename
8802:
1.1133 foxr 8803: #
1.1172.2.66 raeburn 8804: # Removes the version from a URI and
1.1133 foxr 8805: # splits it in to its filename and path to the filename.
8806: # Seems like File::Basename could have done this more clearly.
8807: # Parameters:
8808: # $uri - input URI
8809: # Returns:
8810: # Two element list consisting of
8811: # $pathname - the URI up to and excluding the trailing /
8812: # $filename - The part of the URI following the last /
8813: # NOTE:
8814: # Another realization of this is simply:
8815: # use File::Basename;
8816: # ...
8817: # $uri = shift;
8818: # $filename = basename($uri);
8819: # $path = dirname($uri);
8820: # return ($filename, $path);
8821: #
8822: # The implementation below is probably faster however.
8823: #
1.710 albertel 8824: sub split_uri_for_cond {
8825: my $uri=&deversion(&declutter(shift));
8826: my @uriparts=split(/\//,$uri);
8827: my $filename=pop(@uriparts);
8828: my $pathname=join('/',@uriparts);
8829: return ($pathname,$filename);
8830: }
1.232 www 8831: # --------------------------------------------------- Is a resource on the map?
8832:
8833: sub is_on_map {
1.710 albertel 8834: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8835: #Trying to find the conditional for the file
1.620 albertel 8836: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8837: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8838: if ($match) {
1.289 bowersj2 8839: return (1,$1);
8840: } else {
1.434 www 8841: return (0,0);
1.289 bowersj2 8842: }
1.12 www 8843: }
8844:
1.427 www 8845: # --------------------------------------------------------- Get symb from alias
8846:
8847: sub get_symb_from_alias {
8848: my $symb=shift;
8849: my ($map,$resid,$url)=&decode_symb($symb);
8850: # Already is a symb
8851: if ($url) { return $symb; }
8852: # Must be an alias
8853: my $aliassymb='';
8854: my %bighash;
1.620 albertel 8855: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8856: &GDBM_READER(),0640)) {
8857: my $rid=$bighash{'mapalias_'.$symb};
8858: if ($rid) {
8859: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8860: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8861: $resid,$bighash{'src_'.$rid});
1.427 www 8862: }
8863: untie %bighash;
8864: }
8865: return $aliassymb;
8866: }
8867:
1.12 www 8868: # ----------------------------------------------------------------- Define Role
8869:
8870: sub definerole {
8871: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8872: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8873: foreach my $role (split(':',$sysrole)) {
8874: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8875: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8876: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8877: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8878: return "refused:s:$crole&$cqual";
8879: }
8880: }
1.191 harris41 8881: }
1.800 albertel 8882: foreach my $role (split(':',$domrole)) {
8883: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8884: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8885: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8886: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8887: return "refused:d:$crole&$cqual";
8888: }
8889: }
1.191 harris41 8890: }
1.800 albertel 8891: foreach my $role (split(':',$courole)) {
8892: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8893: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8894: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8895: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8896: return "refused:c:$crole&$cqual";
8897: }
8898: }
1.191 harris41 8899: }
1.1172.2.84 raeburn 8900: my $uhome;
8901: if (($uname ne '') && ($udom ne '')) {
8902: $uhome = &homeserver($uname,$udom);
8903: return $uhome if ($uhome eq 'no_host');
8904: } else {
8905: $uname = $env{'user.name'};
8906: $udom = $env{'user.domain'};
8907: $uhome = $env{'user.home'};
8908: }
1.620 albertel 8909: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8910: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8911: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8912: return reply($command,$uhome);
1.12 www 8913: } else {
8914: return 'refused';
8915: }
1.105 harris41 8916: }
8917:
8918: # ---------------- Make a metadata query against the network of library servers
8919:
8920: sub metadata_query {
1.1172.2.33 raeburn 8921: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8922: my %rhash;
1.845 albertel 8923: my %libserv = &all_library();
1.244 matthew 8924: my @server_list = (defined($server_array) ? @$server_array
8925: : keys(%libserv) );
8926: for my $server (@server_list) {
1.1172.2.33 raeburn 8927: my $domains = '';
8928: if (ref($domains_hash) eq 'HASH') {
8929: $domains = $domains_hash->{$server};
8930: }
1.118 harris41 8931: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8932: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8933: $rhash{$server}=$reply;
8934: }
8935: else {
8936: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8937: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8938: $server);
8939: $rhash{$server}=$reply;
8940: }
1.112 harris41 8941: }
1.118 harris41 8942: return \%rhash;
1.240 www 8943: }
8944:
8945: # ----------------------------------------- Send log queries and wait for reply
8946:
8947: sub log_query {
8948: my ($uname,$udom,$query,%filters)=@_;
8949: my $uhome=&homeserver($uname,$udom);
8950: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8951: my $uhost=&hostname($uhome);
1.800 albertel 8952: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8953: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8954: $uhome);
1.479 albertel 8955: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8956: return get_query_reply($queryid);
8957: }
8958:
1.818 raeburn 8959: # -------------------------- Update MySQL table for portfolio file
8960:
8961: sub update_portfolio_table {
1.821 raeburn 8962: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8963: if ($group ne '') {
8964: $file_name =~s /^\Q$group\E//;
8965: }
1.818 raeburn 8966: my $homeserver = &homeserver($uname,$udom);
8967: my $queryid=
1.821 raeburn 8968: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8969: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8970: my $reply = &get_query_reply($queryid);
8971: return $reply;
8972: }
8973:
1.899 raeburn 8974: # -------------------------- Update MySQL allusers table
8975:
8976: sub update_allusers_table {
8977: my ($uname,$udom,$names) = @_;
8978: my $homeserver = &homeserver($uname,$udom);
8979: my $queryid=
8980: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8981: 'lastname='.&escape($names->{'lastname'}).'%%'.
8982: 'firstname='.&escape($names->{'firstname'}).'%%'.
8983: 'middlename='.&escape($names->{'middlename'}).'%%'.
8984: 'generation='.&escape($names->{'generation'}).'%%'.
8985: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8986: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8987: return;
1.899 raeburn 8988: }
8989:
1.508 raeburn 8990: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8991:
8992: sub fetch_enrollment_query {
1.511 raeburn 8993: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8994: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8995: my $maxtries = 1;
1.508 raeburn 8996: if ($context eq 'automated') {
8997: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8998: $sleep = 2;
8999: $loopmax = 100;
1.547 raeburn 9000: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9001: } else {
9002: $homeserver = &homeserver($cnum,$dom);
9003: }
1.838 albertel 9004: my $host=&hostname($homeserver);
1.506 raeburn 9005: my $cmd = '';
1.1000 raeburn 9006: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9007: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9008: }
9009: $cmd =~ s/%%$//;
9010: $cmd = &escape($cmd);
9011: my $query = 'fetchenrollment';
1.620 albertel 9012: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9013: unless ($queryid=~/^\Q$host\E\_/) {
9014: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9015: return 'error: '.$queryid;
9016: }
1.1172.2.93 raeburn 9017: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9018: my $tries = 1;
9019: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 9020: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9021: $tries ++;
9022: }
1.526 raeburn 9023: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9024: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9025: } else {
1.901 albertel 9026: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9027: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9028: foreach my $line (@responses) {
9029: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9030: $$replyref{$key} = $value;
9031: }
9032: } else {
1.1117 foxr 9033: my $pathname = LONCAPA::tempdir();
1.800 albertel 9034: foreach my $line (@responses) {
9035: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9036: $$replyref{$key} = $value;
9037: if ($value > 0) {
1.800 albertel 9038: foreach my $item (@{$$affiliatesref{$key}}) {
9039: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9040: my $destname = $pathname.'/'.$filename;
9041: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9042: if ($xml_classlist =~ /^error/) {
9043: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9044: } else {
1.1172.2.96 raeburn 9045: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9046: print FILE &unescape($xml_classlist);
9047: close(FILE);
1.526 raeburn 9048: } else {
9049: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9050: }
9051: }
9052: }
9053: }
9054: }
9055: }
9056: return 'ok';
9057: }
9058: return 'error';
9059: }
9060:
1.242 www 9061: sub get_query_reply {
1.1172.2.79 raeburn 9062: my ($queryid,$sleep,$loopmax) = @_;
9063: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9064: $sleep = 0.2;
9065: }
9066: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9067: $loopmax = 100;
9068: }
1.1117 foxr 9069: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9070: my $reply='';
1.1172.2.79 raeburn 9071: for (1..$loopmax) {
9072: sleep($sleep);
1.240 www 9073: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9074: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9075: $reply = join('',<$fh>);
9076: close($fh);
1.240 www 9077: } else { return 'error: reply_file_error'; }
1.242 www 9078: return &unescape($reply);
9079: }
1.240 www 9080: }
1.242 www 9081: return 'timeout:'.$queryid;
1.240 www 9082: }
9083:
9084: sub courselog_query {
1.241 www 9085: #
9086: # possible filters:
9087: # url: url or symb
9088: # username
9089: # domain
9090: # action: view, submit, grade
9091: # start: timestamp
9092: # end: timestamp
9093: #
1.240 www 9094: my (%filters)=@_;
1.620 albertel 9095: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9096: if ($filters{'url'}) {
9097: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9098: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9099: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9100: }
1.620 albertel 9101: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9102: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9103: return &log_query($cname,$cdom,'courselog',%filters);
9104: }
9105:
9106: sub userlog_query {
1.858 raeburn 9107: #
9108: # possible filters:
9109: # action: log check role
9110: # start: timestamp
9111: # end: timestamp
9112: #
1.240 www 9113: my ($uname,$udom,%filters)=@_;
9114: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9115: }
9116:
1.506 raeburn 9117: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9118:
9119: sub auto_run {
1.508 raeburn 9120: my ($cnum,$cdom) = @_;
1.876 raeburn 9121: my $response = 0;
9122: my $settings;
9123: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9124: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9125: $settings = $domconfig{'autoenroll'};
9126: if ($settings->{'run'} eq '1') {
9127: $response = 1;
9128: }
9129: } else {
1.934 raeburn 9130: my $homeserver;
9131: if (&is_course($cdom,$cnum)) {
9132: $homeserver = &homeserver($cnum,$cdom);
9133: } else {
9134: $homeserver = &domain($cdom,'primary');
9135: }
9136: if ($homeserver ne 'no_host') {
9137: $response = &reply('autorun:'.$cdom,$homeserver);
9138: }
1.876 raeburn 9139: }
1.506 raeburn 9140: return $response;
9141: }
1.776 albertel 9142:
1.506 raeburn 9143: sub auto_get_sections {
1.508 raeburn 9144: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9145: my $homeserver;
9146: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9147: $homeserver = &homeserver($cnum,$cdom);
9148: }
9149: if (!defined($homeserver)) {
9150: if ($cdom =~ /^$match_domain$/) {
9151: $homeserver = &domain($cdom,'primary');
9152: }
9153: }
9154: my @secs;
9155: if (defined($homeserver)) {
9156: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9157: unless ($response eq 'refused') {
9158: @secs = split(/:/,$response);
9159: }
1.506 raeburn 9160: }
9161: return @secs;
9162: }
1.776 albertel 9163:
1.506 raeburn 9164: sub auto_new_course {
1.1099 raeburn 9165: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9166: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9167: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9168: return $response;
9169: }
1.776 albertel 9170:
1.506 raeburn 9171: sub auto_validate_courseID {
1.508 raeburn 9172: my ($cnum,$cdom,$inst_course_id) = @_;
9173: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9174: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9175: return $response;
9176: }
1.776 albertel 9177:
1.1007 raeburn 9178: sub auto_validate_instcode {
1.1020 raeburn 9179: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9180: my ($homeserver,$response);
9181: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9182: $homeserver = &homeserver($cnum,$cdom);
9183: }
9184: if (!defined($homeserver)) {
9185: if ($cdom =~ /^$match_domain$/) {
9186: $homeserver = &domain($cdom,'primary');
9187: }
9188: }
1.1065 raeburn 9189: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9190: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9191: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9192: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9193: }
9194:
1.1172.2.141 raeburn 9195: sub auto_validate_inst_crosslist {
9196: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9197: my ($homeserver,$response);
9198: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9199: $homeserver = &homeserver($cnum,$cdom);
9200: }
9201: if (!defined($homeserver)) {
9202: if ($cdom =~ /^$match_domain$/) {
9203: $homeserver = &domain($cdom,'primary');
9204: }
9205: }
9206: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9207: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9208: &escape($instcode).':'.&escape($inst_xlist).':'.
9209: &escape($coowner),$homeserver);
9210: }
9211: return $response;
9212: }
9213:
1.506 raeburn 9214: sub auto_create_password {
1.873 raeburn 9215: my ($cnum,$cdom,$authparam,$udom) = @_;
9216: my ($homeserver,$response);
1.506 raeburn 9217: my $create_passwd = 0;
9218: my $authchk = '';
1.873 raeburn 9219: if ($udom =~ /^$match_domain$/) {
9220: $homeserver = &domain($udom,'primary');
9221: }
9222: if ($homeserver eq '') {
9223: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9224: $homeserver = &homeserver($cnum,$cdom);
9225: }
9226: }
9227: if ($homeserver eq '') {
9228: $authchk = 'nodomain';
1.506 raeburn 9229: } else {
1.873 raeburn 9230: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9231: if ($response eq 'refused') {
9232: $authchk = 'refused';
9233: } else {
1.901 albertel 9234: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9235: }
1.506 raeburn 9236: }
9237: return ($authparam,$create_passwd,$authchk);
9238: }
9239:
1.706 raeburn 9240: sub auto_photo_permission {
9241: my ($cnum,$cdom,$students) = @_;
9242: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9243: my ($outcome,$perm_reqd,$conditions) =
9244: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9245: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9246: return (undef,undef);
9247: }
1.706 raeburn 9248: return ($outcome,$perm_reqd,$conditions);
9249: }
9250:
9251: sub auto_checkphotos {
9252: my ($uname,$udom,$pid) = @_;
9253: my $homeserver = &homeserver($uname,$udom);
9254: my ($result,$resulttype);
9255: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9256: &escape($uname).':'.&escape($pid),
9257: $homeserver));
1.709 albertel 9258: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9259: return (undef,undef);
9260: }
1.706 raeburn 9261: if ($outcome) {
9262: ($result,$resulttype) = split(/:/,$outcome);
9263: }
9264: return ($result,$resulttype);
9265: }
9266:
9267: sub auto_photochoice {
9268: my ($cnum,$cdom) = @_;
9269: my $homeserver = &homeserver($cnum,$cdom);
9270: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9271: &escape($cdom),
9272: $homeserver)));
1.709 albertel 9273: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9274: return (undef,undef);
9275: }
1.706 raeburn 9276: return ($update,$comment);
9277: }
9278:
9279: sub auto_photoupdate {
9280: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9281: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9282: my $host=&hostname($homeserver);
1.706 raeburn 9283: my $cmd = '';
9284: my $maxtries = 1;
1.800 albertel 9285: foreach my $affiliate (keys(%{$affiliatesref})) {
9286: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9287: }
9288: $cmd =~ s/%%$//;
9289: $cmd = &escape($cmd);
9290: my $query = 'institutionalphotos';
9291: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9292: unless ($queryid=~/^\Q$host\E\_/) {
9293: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9294: return 'error: '.$queryid;
9295: }
9296: my $reply = &get_query_reply($queryid);
9297: my $tries = 1;
9298: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9299: $reply = &get_query_reply($queryid);
9300: $tries ++;
9301: }
9302: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9303: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9304: } else {
9305: my @responses = split(/:/,$reply);
9306: my $outcome = shift(@responses);
9307: foreach my $item (@responses) {
9308: my ($key,$value) = split(/=/,$item);
9309: $$photo{$key} = $value;
9310: }
9311: return $outcome;
9312: }
9313: return 'error';
9314: }
9315:
1.521 raeburn 9316: sub auto_instcode_format {
1.793 albertel 9317: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9318: $cat_order) = @_;
1.521 raeburn 9319: my $courses = '';
1.772 raeburn 9320: my @homeservers;
1.521 raeburn 9321: if ($caller eq 'global') {
1.841 albertel 9322: my %servers = &get_servers($codedom,'library');
9323: foreach my $tryserver (keys(%servers)) {
9324: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9325: push(@homeservers,$tryserver);
9326: }
1.584 raeburn 9327: }
1.1022 raeburn 9328: } elsif ($caller eq 'requests') {
9329: if ($codedom =~ /^$match_domain$/) {
9330: my $chome = &domain($codedom,'primary');
9331: unless ($chome eq 'no_host') {
9332: push(@homeservers,$chome);
9333: }
9334: }
1.521 raeburn 9335: } else {
1.772 raeburn 9336: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9337: }
1.793 albertel 9338: foreach my $code (keys(%{$instcodes})) {
9339: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9340: }
9341: chop($courses);
1.772 raeburn 9342: my $ok_response = 0;
9343: my $response;
9344: while (@homeservers > 0 && $ok_response == 0) {
9345: my $server = shift(@homeservers);
9346: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9347: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9348: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9349: split(/:/,$response);
1.772 raeburn 9350: %{$codes} = (%{$codes},&str2hash($codes_str));
9351: push(@{$codetitles},&str2array($codetitles_str));
9352: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9353: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9354: $ok_response = 1;
9355: }
9356: }
9357: if ($ok_response) {
1.521 raeburn 9358: return 'ok';
1.772 raeburn 9359: } else {
9360: return $response;
1.521 raeburn 9361: }
9362: }
9363:
1.792 raeburn 9364: sub auto_instcode_defaults {
9365: my ($domain,$returnhash,$code_order) = @_;
9366: my @homeservers;
1.841 albertel 9367:
9368: my %servers = &get_servers($domain,'library');
9369: foreach my $tryserver (keys(%servers)) {
9370: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9371: push(@homeservers,$tryserver);
9372: }
1.792 raeburn 9373: }
1.841 albertel 9374:
1.792 raeburn 9375: my $response;
1.841 albertel 9376: foreach my $server (@homeservers) {
1.792 raeburn 9377: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9378: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9379:
9380: foreach my $pair (split(/\&/,$response)) {
9381: my ($name,$value)=split(/\=/,$pair);
9382: if ($name eq 'code_order') {
9383: @{$code_order} = split(/\&/,&unescape($value));
9384: } else {
9385: $returnhash->{&unescape($name)}=&unescape($value);
9386: }
9387: }
9388: return 'ok';
1.792 raeburn 9389: }
1.841 albertel 9390:
9391: return $response;
1.1003 raeburn 9392: }
9393:
9394: sub auto_possible_instcodes {
1.1007 raeburn 9395: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9396: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9397: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9398: return;
9399: }
1.1003 raeburn 9400: my (@homeservers,$uhome);
9401: if (defined(&domain($domain,'primary'))) {
9402: $uhome=&domain($domain,'primary');
9403: push(@homeservers,&domain($domain,'primary'));
9404: } else {
9405: my %servers = &get_servers($domain,'library');
9406: foreach my $tryserver (keys(%servers)) {
9407: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9408: push(@homeservers,$tryserver);
9409: }
9410: }
9411: }
9412: my $response;
9413: foreach my $server (@homeservers) {
9414: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9415: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9416: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9417: split(':',$response);
9418: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9419: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9420: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9421: my ($name,$value)=split('=',$item);
9422: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9423: }
9424: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9425: my ($name,$value)=split('=',$item);
9426: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9427: }
9428: return 'ok';
9429: }
9430: return $response;
9431: }
1.792 raeburn 9432:
1.1010 raeburn 9433: sub auto_courserequest_checks {
9434: my ($dom) = @_;
1.1020 raeburn 9435: my ($homeserver,%validations);
9436: if ($dom =~ /^$match_domain$/) {
9437: $homeserver = &domain($dom,'primary');
9438: }
9439: unless ($homeserver eq 'no_host') {
9440: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9441: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9442: my @items = split(/&/,$response);
9443: foreach my $item (@items) {
9444: my ($key,$value) = split('=',$item);
9445: $validations{&unescape($key)} = &thaw_unescape($value);
9446: }
9447: }
9448: }
1.1010 raeburn 9449: return %validations;
9450: }
9451:
1.1020 raeburn 9452: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9453: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9454: my ($homeserver,$response);
9455: if ($dom =~ /^$match_domain$/) {
9456: $homeserver = &domain($dom,'primary');
9457: }
1.1172.2.43 raeburn 9458: unless ($homeserver eq 'no_host') {
9459: my $customdata;
9460: if (ref($custominfo) eq 'HASH') {
9461: $customdata = &freeze_escape($custominfo);
9462: }
1.1020 raeburn 9463: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9464: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9465: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9466: $customdata,$homeserver));
1.1020 raeburn 9467: }
9468: return $response;
9469: }
9470:
1.777 albertel 9471: sub auto_validate_class_sec {
1.918 raeburn 9472: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9473: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9474: my $ownerlist;
9475: if (ref($owners) eq 'ARRAY') {
9476: $ownerlist = join(',',@{$owners});
9477: } else {
9478: $ownerlist = $owners;
9479: }
1.773 raeburn 9480: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9481: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9482: return $response;
9483: }
9484:
1.1172.2.141 raeburn 9485: sub auto_instsec_reformat {
9486: my ($cdom,$action,$instsecref) = @_;
9487: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9488: my @homeservers;
9489: if (defined(&domain($cdom,'primary'))) {
9490: push(@homeservers,&domain($cdom,'primary'));
9491: } else {
9492: my %servers = &get_servers($cdom,'library');
9493: foreach my $tryserver (keys(%servers)) {
9494: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9495: push(@homeservers,$tryserver);
9496: }
9497: }
9498: }
9499: my $response;
9500: my %reformatted = %{$instsecref};
9501: foreach my $server (@homeservers) {
9502: if (ref($instsecref) eq 'HASH') {
9503: my $info = &freeze_escape($instsecref);
9504: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9505: $action.':'.$info,$server);
9506: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9507: my @items = split(/&/,$response);
9508: foreach my $item (@items) {
9509: my ($key,$value) = split(/=/,$item);
9510: $reformatted{&unescape($key)} = &thaw_unescape($value);
9511: }
9512: }
9513: }
9514: return %reformatted;
9515: }
9516:
1.1172.2.94 raeburn 9517: sub auto_validate_instclasses {
9518: my ($cdom,$cnum,$owners,$classesref) = @_;
9519: my ($homeserver,%validations);
9520: $homeserver = &homeserver($cnum,$cdom);
9521: unless ($homeserver eq 'no_host') {
9522: my $ownerlist;
9523: if (ref($owners) eq 'ARRAY') {
9524: $ownerlist = join(',',@{$owners});
9525: } else {
9526: $ownerlist = $owners;
9527: }
9528: if (ref($classesref) eq 'HASH') {
9529: my $classes = &freeze_escape($classesref);
9530: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9531: ':'.$cdom.':'.$classes,$homeserver);
9532: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9533: my @items = split(/&/,$response);
9534: foreach my $item (@items) {
9535: my ($key,$value) = split('=',$item);
9536: $validations{&unescape($key)} = &thaw_unescape($value);
9537: }
9538: }
9539: }
9540: }
9541: return %validations;
9542: }
9543:
1.1172.2.38 raeburn 9544: sub auto_crsreq_update {
9545: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9546: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9547: my ($homeserver,%crsreqresponse);
9548: if ($cdom =~ /^$match_domain$/) {
9549: $homeserver = &domain($cdom,'primary');
9550: }
9551: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9552: my $info;
9553: if (ref($inbound) eq 'HASH') {
9554: $info = &freeze_escape($inbound);
9555: }
9556: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9557: ':'.&escape($action).':'.&escape($ownername).':'.
9558: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9559: &escape($title).':'.&escape($code).':'.
9560: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9561: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9562: my @items = split(/&/,$response);
9563: foreach my $item (@items) {
9564: my ($key,$value) = split('=',$item);
9565: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9566: }
9567: }
9568: }
9569: return \%crsreqresponse;
9570: }
9571:
1.1172.2.78 raeburn 9572: sub auto_export_grades {
9573: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9574: my ($homeserver,%exportresponse);
9575: if ($cdom =~ /^$match_domain$/) {
9576: $homeserver = &domain($cdom,'primary');
9577: }
9578: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9579: my $info;
9580: if (ref($inforef) eq 'HASH') {
9581: $info = &freeze_escape($inforef);
9582: }
9583: if (ref($gradesref) eq 'HASH') {
9584: my $grades = &freeze_escape($gradesref);
9585: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9586: $info.':'.$grades,$homeserver);
9587: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9588: my @items = split(/&/,$response);
9589: foreach my $item (@items) {
9590: my ($key,$value) = split('=',$item);
9591: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9592: }
9593: }
9594: }
9595: }
9596: return \%exportresponse;
9597: }
9598:
1.1172.2.68 raeburn 9599: sub check_instcode_cloning {
9600: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9601: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9602: return;
9603: }
9604: my $canclone;
9605: if (@{$code_order} > 0) {
9606: my $instcoderegexp ='^';
9607: my @clonecodes = split(/\&/,$cloner);
9608: foreach my $item (@{$code_order}) {
9609: if (grep(/^\Q$item\E=/,@clonecodes)) {
9610: foreach my $pair (@clonecodes) {
9611: my ($key,$val) = split(/\=/,$pair,2);
9612: $val = &unescape($val);
9613: if ($key eq $item) {
9614: $instcoderegexp .= '('.$val.')';
9615: last;
9616: }
9617: }
9618: } else {
9619: $instcoderegexp .= $codedefaults->{$item};
9620: }
9621: }
9622: $instcoderegexp .= '$';
9623: my (@from,@to);
9624: eval {
9625: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9626: (@to) = ($clonetocode =~ /$instcoderegexp/);
9627: };
9628: if ((@from > 0) && (@to > 0)) {
9629: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9630: if (!@diffs) {
9631: $canclone = 1;
9632: }
9633: }
9634: }
9635: return $canclone;
9636: }
9637:
9638: sub default_instcode_cloning {
9639: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9640: my (%codedefaults,@code_order,$canclone);
9641: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9642: %codedefaults = %{$codedefaultsref};
9643: @code_order = @{$codeorderref};
9644: } elsif ($clonedom) {
9645: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9646: }
9647: if (($domdefclone) && (@code_order)) {
9648: my @clonecodes = split(/\+/,$domdefclone);
9649: my $instcoderegexp ='^';
9650: foreach my $item (@code_order) {
9651: if (grep(/^\Q$item\E$/,@clonecodes)) {
9652: $instcoderegexp .= '('.$codedefaults{$item}.')';
9653: } else {
9654: $instcoderegexp .= $codedefaults{$item};
9655: }
9656: }
9657: $instcoderegexp .= '$';
9658: my (@from,@to);
9659: eval {
9660: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9661: (@to) = ($clonetocode =~ /$instcoderegexp/);
9662: };
9663: if ((@from > 0) && (@to > 0)) {
9664: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9665: if (!@diffs) {
9666: $canclone = 1;
9667: }
9668: }
9669: }
9670: return $canclone;
9671: }
9672:
1.679 raeburn 9673: # ------------------------------------------------------- Course Group routines
9674:
9675: sub get_coursegroups {
1.809 raeburn 9676: my ($cdom,$cnum,$group,$namespace) = @_;
9677: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9678: }
9679:
1.679 raeburn 9680: sub modify_coursegroup {
9681: my ($cdom,$cnum,$groupsettings) = @_;
9682: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9683: }
9684:
1.809 raeburn 9685: sub toggle_coursegroup_status {
9686: my ($cdom,$cnum,$group,$action) = @_;
9687: my ($from_namespace,$to_namespace);
9688: if ($action eq 'delete') {
9689: $from_namespace = 'coursegroups';
9690: $to_namespace = 'deleted_groups';
9691: } else {
9692: $from_namespace = 'deleted_groups';
9693: $to_namespace = 'coursegroups';
9694: }
9695: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9696: if (my $tmp = &error(%curr_group)) {
9697: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9698: return ('read error',$tmp);
9699: } else {
9700: my %savedsettings = %curr_group;
1.809 raeburn 9701: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9702: my $deloutcome;
9703: if ($result eq 'ok') {
1.809 raeburn 9704: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9705: } else {
9706: return ('write error',$result);
9707: }
9708: if ($deloutcome eq 'ok') {
9709: return 'ok';
9710: } else {
9711: return ('delete error',$deloutcome);
9712: }
9713: }
9714: }
9715:
1.679 raeburn 9716: sub modify_group_roles {
1.957 raeburn 9717: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9718: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9719: my $role = 'gr/'.&escape($userprivs);
9720: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9721: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9722: if ($result eq 'ok') {
9723: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9724: }
1.679 raeburn 9725: return $result;
9726: }
9727:
9728: sub modify_coursegroup_membership {
9729: my ($cdom,$cnum,$membership) = @_;
9730: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9731: return $result;
9732: }
9733:
1.682 raeburn 9734: sub get_active_groups {
9735: my ($udom,$uname,$cdom,$cnum) = @_;
9736: my $now = time;
9737: my %groups = ();
9738: foreach my $key (keys(%env)) {
1.811 albertel 9739: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9740: my ($start,$end) = split(/\./,$env{$key});
9741: if (($end!=0) && ($end<$now)) { next; }
9742: if (($start!=0) && ($start>$now)) { next; }
9743: if ($1 eq $cdom && $2 eq $cnum) {
9744: $groups{$3} = $env{$key} ;
9745: }
9746: }
9747: }
9748: return %groups;
9749: }
9750:
1.683 raeburn 9751: sub get_group_membership {
9752: my ($cdom,$cnum,$group) = @_;
9753: return(&dump('groupmembership',$cdom,$cnum,$group));
9754: }
9755:
9756: sub get_users_groups {
9757: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9758: my @usersgroups;
1.683 raeburn 9759: my $cachetime=1800;
9760:
9761: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9762: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9763: if (defined($cached)) {
1.734 albertel 9764: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9765: } else {
9766: $grouplist = '';
1.816 raeburn 9767: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9768: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9769: my $access_end = $env{'course.'.$courseid.
9770: '.default_enrollment_end_date'};
9771: my $now = time;
9772: foreach my $key (keys(%roleshash)) {
9773: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9774: my $group = $1;
9775: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9776: my $start = $2;
9777: my $end = $1;
9778: if ($start == -1) { next; } # deleted from group
9779: if (($start!=0) && ($start>$now)) { next; }
9780: if (($end!=0) && ($end<$now)) {
9781: if ($access_end && $access_end < $now) {
9782: if ($access_end - $end < 86400) {
9783: push(@usersgroups,$group);
1.733 raeburn 9784: }
9785: }
1.817 raeburn 9786: next;
1.733 raeburn 9787: }
1.817 raeburn 9788: push(@usersgroups,$group);
1.683 raeburn 9789: }
9790: }
9791: }
1.817 raeburn 9792: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9793: $grouplist = join(':',@usersgroups);
9794: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9795: }
1.733 raeburn 9796: return @usersgroups;
1.683 raeburn 9797: }
9798:
9799: sub devalidate_getgroups_cache {
9800: my ($udom,$uname,$cdom,$cnum)=@_;
9801: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9802:
1.683 raeburn 9803: my $hashid="$udom:$uname:$courseid";
9804: &devalidate_cache_new('getgroups',$hashid);
9805: }
9806:
1.12 www 9807: # ------------------------------------------------------------------ Plain Text
9808:
9809: sub plaintext {
1.988 raeburn 9810: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9811: if ($short =~ m{^cr/}) {
1.758 albertel 9812: return (split('/',$short))[-1];
9813: }
1.742 raeburn 9814: if (!defined($cid)) {
9815: $cid = $env{'request.course.id'};
9816: }
9817: my %rolenames = (
1.1008 raeburn 9818: Course => 'std',
9819: Community => 'alt1',
1.742 raeburn 9820: );
1.1037 raeburn 9821: if ($cid ne '') {
9822: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9823: unless ($forcedefault) {
9824: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9825: &Apache::lonlocal::mt_escape(\$roletext);
9826: return &Apache::lonlocal::mt($roletext);
9827: }
9828: }
9829: }
9830: if ((defined($type)) && (defined($rolenames{$type})) &&
9831: (defined($rolenames{$type})) &&
9832: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9833: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9834: } elsif ($cid ne '') {
9835: my $crstype = $env{'course.'.$cid.'.type'};
9836: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9837: (defined($prp{$short}{$rolenames{$crstype}}))) {
9838: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9839: }
1.742 raeburn 9840: }
1.1037 raeburn 9841: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9842: }
9843:
9844: # ----------------------------------------------------------------- Assign Role
9845:
9846: sub assignrole {
1.957 raeburn 9847: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9848: $context)=@_;
1.21 www 9849: my $mrole;
9850: if ($role =~ /^cr\//) {
1.393 www 9851: my $cwosec=$url;
1.811 albertel 9852: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9853: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9854: my $refused = 1;
9855: if ($context eq 'requestcourses') {
9856: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9857: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9858: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9859: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9860: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9861: if ($crsenv{'internal.courseowner'} eq
9862: $env{'user.name'}.':'.$env{'user.domain'}) {
9863: $refused = '';
9864: }
9865: }
9866: }
9867: }
9868: }
9869: if ($refused) {
9870: &logthis('Refused custom assignrole: '.
9871: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9872: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9873: return 'refused';
9874: }
1.104 www 9875: }
1.21 www 9876: $mrole='cr';
1.678 raeburn 9877: } elsif ($role =~ /^gr\//) {
9878: my $cwogrp=$url;
1.811 albertel 9879: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9880: unless (&allowed('mdg',$cwogrp)) {
9881: &logthis('Refused group assignrole: '.
9882: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9883: $env{'user.name'}.' at '.$env{'user.domain'});
9884: return 'refused';
9885: }
9886: $mrole='gr';
1.21 www 9887: } else {
1.82 www 9888: my $cwosec=$url;
1.811 albertel 9889: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9890: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9891: my $refused;
9892: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9893: if (!(&allowed('c'.$role,$url))) {
9894: $refused = 1;
9895: }
9896: } else {
9897: $refused = 1;
9898: }
1.947 raeburn 9899: if ($refused) {
1.1045 raeburn 9900: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9901: if (!$selfenroll && $context eq 'course') {
9902: my %crsenv;
9903: if ($role eq 'cc' || $role eq 'co') {
9904: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9905: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9906: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9907: if ($crsenv{'internal.courseowner'} eq
9908: $env{'user.name'}.':'.$env{'user.domain'}) {
9909: $refused = '';
9910: }
9911: }
9912: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9913: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9914: if ($crsenv{'internal.courseowner'} eq
9915: $env{'user.name'}.':'.$env{'user.domain'}) {
9916: $refused = '';
9917: }
9918: }
9919: }
9920: }
9921: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9922: $refused = '';
1.1017 raeburn 9923: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9924: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9925: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9926: my $wrongcc;
9927: if ($cnum =~ /^$match_community$/) {
9928: $wrongcc = 1 if ($role eq 'cc');
9929: } else {
9930: $wrongcc = 1 if ($role eq 'co');
9931: }
9932: unless ($wrongcc) {
9933: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9934: if ($crsenv{'internal.courseowner'} eq
9935: $env{'user.name'}.':'.$env{'user.domain'}) {
9936: $refused = '';
9937: }
1.1017 raeburn 9938: }
9939: }
1.1172.2.9 raeburn 9940: } elsif ($context eq 'requestauthor') {
9941: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9942: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9943: if ($env{'environment.requestauthor'} eq 'automatic') {
9944: $refused = '';
9945: } else {
9946: my %domdefaults = &get_domain_defaults($udom);
9947: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9948: my $checkbystatus;
9949: if ($env{'user.adv'}) {
9950: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9951: if ($disposition eq 'automatic') {
9952: $refused = '';
9953: } elsif ($disposition eq '') {
9954: $checkbystatus = 1;
9955: }
9956: } else {
9957: $checkbystatus = 1;
9958: }
9959: if ($checkbystatus) {
9960: if ($env{'environment.inststatus'}) {
9961: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9962: foreach my $type (@inststatuses) {
9963: if (($type ne '') &&
9964: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9965: $refused = '';
9966: }
9967: }
9968: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9969: $refused = '';
9970: }
9971: }
9972: }
9973: }
9974: }
1.1017 raeburn 9975: }
9976: if ($refused) {
1.947 raeburn 9977: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9978: ' '.$role.' '.$end.' '.$start.' by '.
9979: $env{'user.name'}.' at '.$env{'user.domain'});
9980: return 'refused';
9981: }
1.932 raeburn 9982: }
1.1131 raeburn 9983: } elsif ($role eq 'au') {
9984: if ($url ne '/'.$udom.'/') {
9985: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9986: ' to assign author role for '.$uname.':'.$udom.
9987: ' in domain: '.$url.' refused (wrong domain).');
9988: return 'refused';
9989: }
1.104 www 9990: }
1.21 www 9991: $mrole=$role;
9992: }
1.620 albertel 9993: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9994: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9995: if ($end) { $command.='_'.$end; }
1.21 www 9996: if ($start) {
9997: if ($end) {
1.81 www 9998: $command.='_'.$start;
1.21 www 9999: } else {
1.81 www 10000: $command.='_0_'.$start;
1.21 www 10001: }
10002: }
1.739 raeburn 10003: my $origstart = $start;
10004: my $origend = $end;
1.957 raeburn 10005: my $delflag;
1.357 www 10006: # actually delete
10007: if ($deleteflag) {
1.373 www 10008: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10009: # modify command to delete the role
1.620 albertel 10010: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10011: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10012: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10013: # set start and finish to negative values for userrolelog
10014: $start=-1;
10015: $end=-1;
1.957 raeburn 10016: $delflag = 1;
1.357 www 10017: }
10018: }
10019: # send command
1.349 www 10020: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10021: # log new user role if status is ok
1.349 www 10022: if ($answer eq 'ok') {
1.663 raeburn 10023: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 10024: if (($role eq 'cc') || ($role eq 'in') ||
10025: ($role eq 'ep') || ($role eq 'ad') ||
10026: ($role eq 'ta') || ($role eq 'st') ||
10027: ($role=~/^cr/) || ($role eq 'gr') ||
10028: ($role eq 'co')) {
1.1172.2.13 raeburn 10029: # for course roles, perform group memberships changes triggered by role change.
10030: unless ($role =~ /^gr/) {
10031: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10032: $origstart,$selfenroll,$context);
10033: }
1.1172.2.9 raeburn 10034: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10035: $selfenroll,$context);
10036: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10037: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10038: ($role eq 'da')) {
1.1172.2.9 raeburn 10039: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10040: $context);
10041: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10042: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10043: $context);
10044: }
1.1053 raeburn 10045: if ($role eq 'cc') {
10046: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10047: }
1.349 www 10048: }
10049: return $answer;
1.169 harris41 10050: }
10051:
1.1053 raeburn 10052: sub autoupdate_coowners {
10053: my ($url,$end,$start,$uname,$udom) = @_;
10054: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10055: if (($cdom ne '') && ($cnum ne '')) {
10056: my $now = time;
10057: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10058: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10059: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10060: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10061: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10062: if ($instcode ne '') {
1.1056 raeburn 10063: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10064: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10065: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10066: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10067: unless ($result eq 'valid') {
10068: if ($xlists ne '') {
10069: foreach my $xlist (split(',',$xlists)) {
10070: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10071: $result =
10072: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10073: $inst_crosslist,$uname.':'.$udom);
10074: last if ($result eq 'valid');
10075: }
10076: }
10077: }
1.1056 raeburn 10078: if ($result eq 'valid') {
10079: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10080: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10081: push(@newcoowners,$coowner);
10082: }
10083: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10084: push(@newcoowners,$uname.':'.$udom);
10085: }
10086: @newcoowners = sort(@newcoowners);
10087: } else {
10088: push(@newcoowners,$uname.':'.$udom);
10089: }
1.1172.2.141 raeburn 10090: } elsif ($coursehash{'internal.co-owners'}) {
10091: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10092: unless ($coowner eq $uname.':'.$udom) {
10093: push(@newcoowners,$coowner);
1.1053 raeburn 10094: }
10095: }
1.1172.2.141 raeburn 10096: unless (@newcoowners > 0) {
10097: $delcoowners = 1;
10098: $coowners = '';
10099: }
1.1053 raeburn 10100: }
10101: if (@newcoowners || $delcoowners) {
10102: &store_coowners($cdom,$cnum,$coursehash{'home'},
10103: $delcoowners,@newcoowners);
10104: }
10105: }
10106: }
10107: }
10108: }
10109: }
10110: }
10111:
10112: sub store_coowners {
10113: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10114: my $cid = $cdom.'_'.$cnum;
10115: my ($coowners,$delresult,$putresult);
10116: if (@newcoowners) {
10117: $coowners = join(',',@newcoowners);
10118: my %coownershash = (
10119: 'internal.co-owners' => $coowners,
10120: );
10121: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10122: if ($putresult eq 'ok') {
10123: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10124: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10125: }
10126: }
10127: }
10128: if ($delcoowners) {
10129: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10130: if ($delresult eq 'ok') {
10131: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10132: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10133: }
10134: }
10135: }
10136: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10137: my %crsinfo =
10138: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10139: if (ref($crsinfo{$cid}) eq 'HASH') {
10140: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10141: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10142: }
10143: }
10144: }
10145:
1.169 harris41 10146: # -------------------------------------------------- Modify user authentication
1.197 www 10147: # Overrides without validation
10148:
1.169 harris41 10149: sub modifyuserauth {
10150: my ($udom,$uname,$umode,$upass)=@_;
10151: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10152: my $allowed;
10153: if (&allowed('mau',$udom)) {
10154: $allowed = 1;
10155: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10156: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10157: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10158: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10159: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10160: if (($cdom ne '') && ($cnum ne '')) {
10161: my $is_owner = &is_course_owner($cdom,$cnum);
10162: if ($is_owner) {
10163: $allowed = 1;
10164: }
10165: }
10166: }
10167: unless ($allowed) { return 'refused'; }
1.197 www 10168: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10169: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10170: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10171: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10172: &escape($upass),$uhome);
1.1172.2.134 raeburn 10173: my $ip = &get_requestor_ip();
1.620 albertel 10174: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10175: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10176: '(Remote '.$ip.'): '.$reply);
1.197 www 10177: &log($udom,,$uname,$uhome,
1.620 albertel 10178: 'Authentication changed by '.$env{'user.domain'}.', '.
10179: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10180: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10181: unless ($reply eq 'ok') {
1.197 www 10182: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10183: return 'error: '.$reply;
10184: }
1.170 harris41 10185: return 'ok';
1.80 www 10186: }
10187:
1.81 www 10188: # --------------------------------------------------------------- Modify a user
1.80 www 10189:
1.81 www 10190: sub modifyuser {
1.206 matthew 10191: my ($udom, $uname, $uid,
10192: $umode, $upass, $first,
10193: $middle, $last, $gene,
1.1058 raeburn 10194: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10195: $udom= &LONCAPA::clean_domain($udom);
10196: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10197: my $showcandelete = 'none';
10198: if (ref($candelete) eq 'ARRAY') {
10199: if (@{$candelete} > 0) {
10200: $showcandelete = join(', ',@{$candelete});
10201: }
10202: }
1.81 www 10203: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10204: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10205: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10206: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10207: ' desiredhome not specified').
1.620 albertel 10208: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10209: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10210: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10211: my $newuser;
10212: if ($uhome eq 'no_host') {
10213: $newuser = 1;
10214: }
1.80 www 10215: # ----------------------------------------------------------------- Create User
1.406 albertel 10216: if (($uhome eq 'no_host') &&
10217: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10218: my $unhome='';
1.844 albertel 10219: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10220: $unhome = $desiredhome;
1.620 albertel 10221: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10222: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10223: } else { # load balancing routine for determining $unhome
1.81 www 10224: my $loadm=10000000;
1.841 albertel 10225: my %servers = &get_servers($udom,'library');
10226: foreach my $tryserver (keys(%servers)) {
10227: my $answer=reply('load',$tryserver);
10228: if (($answer=~/\d+/) && ($answer<$loadm)) {
10229: $loadm=$answer;
10230: $unhome=$tryserver;
10231: }
1.80 www 10232: }
10233: }
10234: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10235: return 'error: unable to find a home server for '.$uname.
10236: ' in domain '.$udom;
1.80 www 10237: }
10238: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10239: &escape($upass),$unhome);
10240: unless ($reply eq 'ok') {
10241: return 'error: '.$reply;
10242: }
1.230 stredwic 10243: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10244: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10245: return 'error: unable verify users home machine.';
1.80 www 10246: }
1.209 matthew 10247: } # End of creation of new user
1.80 www 10248: # ---------------------------------------------------------------------- Add ID
10249: if ($uid) {
10250: $uid=~tr/A-Z/a-z/;
10251: my %uidhash=&idrget($udom,$uname);
1.196 www 10252: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10253: && (!$forceid)) {
1.80 www 10254: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10255: return 'error: user id "'.$uid.'" does not match '.
10256: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10257: }
10258: } else {
10259: &idput($udom,($uname => $uid));
10260: }
10261: }
10262: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10263: my @tmp=&get('environment',
1.899 raeburn 10264: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10265: 'permanentemail','inststatus'],
1.134 albertel 10266: $udom,$uname);
1.1075 raeburn 10267: my (%names,%oldnames);
1.313 matthew 10268: if ($tmp[0] =~ m/^error:.*/) {
10269: %names=();
10270: } else {
10271: %names = @tmp;
1.1075 raeburn 10272: %oldnames = %names;
1.313 matthew 10273: }
1.388 www 10274: #
1.1058 raeburn 10275: # If name, email and/or uid are blank (e.g., because an uploaded file
10276: # of users did not contain them), do not overwrite existing values
10277: # unless field is in $candelete array ref.
10278: #
10279:
10280: my @fields = ('firstname','middlename','lastname','generation',
10281: 'permanentemail','id');
10282: my %newvalues;
10283: if (ref($candelete) eq 'ARRAY') {
10284: foreach my $field (@fields) {
10285: if (grep(/^\Q$field\E$/,@{$candelete})) {
10286: if ($field eq 'firstname') {
10287: $names{$field} = $first;
10288: } elsif ($field eq 'middlename') {
10289: $names{$field} = $middle;
10290: } elsif ($field eq 'lastname') {
10291: $names{$field} = $last;
10292: } elsif ($field eq 'generation') {
10293: $names{$field} = $gene;
10294: } elsif ($field eq 'permanentemail') {
10295: $names{$field} = $email;
10296: } elsif ($field eq 'id') {
10297: $names{$field} = $uid;
10298: }
10299: }
10300: }
10301: }
1.388 www 10302: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10303: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10304: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10305: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10306: if ($email) {
10307: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10308: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10309: }
1.899 raeburn 10310: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10311: if (defined($inststatus)) {
10312: $names{'inststatus'} = '';
10313: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10314: if (ref($usertypes) eq 'HASH') {
10315: my @okstatuses;
10316: foreach my $item (split(/:/,$inststatus)) {
10317: if (defined($usertypes->{$item})) {
10318: push(@okstatuses,$item);
10319: }
10320: }
10321: if (@okstatuses) {
10322: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10323: }
10324: }
10325: }
1.1075 raeburn 10326: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10327: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10328: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10329: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10330: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10331: } else {
10332: $logmsg .= ' during self creation';
10333: }
1.1075 raeburn 10334: my $changed;
10335: if ($newuser) {
10336: $changed = 1;
10337: } else {
10338: foreach my $field (@fields) {
10339: if ($names{$field} ne $oldnames{$field}) {
10340: $changed = 1;
10341: last;
10342: }
10343: }
10344: }
10345: unless ($changed) {
10346: $logmsg = 'No changes in user information needed for: '.$logmsg;
10347: &logthis($logmsg);
10348: return 'ok';
10349: }
10350: my $reply = &put('environment', \%names, $udom,$uname);
10351: if ($reply ne 'ok') {
10352: return 'error: '.$reply;
10353: }
1.1087 raeburn 10354: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10355: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10356: }
1.1075 raeburn 10357: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10358: &devalidate_cache_new('namescache',$uname.':'.$udom);
10359: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10360: &logthis($logmsg);
1.134 albertel 10361: return 'ok';
1.80 www 10362: }
10363:
1.81 www 10364: # -------------------------------------------------------------- Modify student
1.80 www 10365:
1.81 www 10366: sub modifystudent {
10367: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10368: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10369: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10370: if (!$cid) {
1.620 albertel 10371: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10372: return 'not_in_class';
10373: }
1.80 www 10374: }
10375: # --------------------------------------------------------------- Make the user
1.81 www 10376: my $reply=&modifyuser
1.209 matthew 10377: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10378: $desiredhome,$email,$inststatus);
1.80 www 10379: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10380: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10381: # student's environment
1.297 matthew 10382: $uid = undef if (!$forceid);
1.455 albertel 10383: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10384: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10385: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10386: return $reply;
10387: }
10388:
10389: sub modify_student_enrollment {
1.1172.2.23 raeburn 10390: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10391: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10392: my ($cdom,$cnum,$chome);
10393: if (!$cid) {
1.620 albertel 10394: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10395: return 'not_in_class';
10396: }
1.620 albertel 10397: $cdom=$env{'course.'.$cid.'.domain'};
10398: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10399: } else {
10400: ($cdom,$cnum)=split(/_/,$cid);
10401: }
1.620 albertel 10402: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10403: if (!$chome) {
1.457 raeburn 10404: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10405: }
1.455 albertel 10406: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10407: # Make sure the user exists
1.81 www 10408: my $uhome=&homeserver($uname,$udom);
10409: if (($uhome eq '') || ($uhome eq 'no_host')) {
10410: return 'error: no such user';
10411: }
1.297 matthew 10412: # Get student data if we were not given enough information
10413: if (!defined($first) || $first eq '' ||
10414: !defined($last) || $last eq '' ||
10415: !defined($uid) || $uid eq '' ||
10416: !defined($middle) || $middle eq '' ||
10417: !defined($gene) || $gene eq '') {
1.294 matthew 10418: # They did not supply us with enough data to enroll the student, so
10419: # we need to pick up more information.
1.297 matthew 10420: my %tmp = &get('environment',
1.294 matthew 10421: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10422: ,$udom,$uname);
10423:
1.800 albertel 10424: #foreach my $key (keys(%tmp)) {
10425: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10426: #}
1.294 matthew 10427: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10428: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10429: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10430: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10431: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10432: }
1.556 albertel 10433: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10434: my $user = "$uname:$udom";
10435: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10436: my $reply=cput('classlist',
1.1148 raeburn 10437: {$user =>
1.1172.2.76 raeburn 10438: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10439: $cdom,$cnum);
1.1148 raeburn 10440: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10441: &devalidate_getsection_cache($udom,$uname,$cid);
10442: } else {
1.81 www 10443: return 'error: '.$reply;
10444: }
1.297 matthew 10445: # Add student role to user
1.83 www 10446: my $uurl='/'.$cid;
1.81 www 10447: $uurl=~s/\_/\//g;
10448: if ($usec) {
10449: $uurl.='/'.$usec;
10450: }
1.1148 raeburn 10451: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10452: $selfenroll,$context);
10453: if ($result ne 'ok') {
10454: if ($old_entry{$user} ne '') {
10455: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10456: } else {
10457: $reply = &del('classlist',[$user],$cdom,$cnum);
10458: }
10459: }
10460: return $result;
1.21 www 10461: }
10462:
1.556 albertel 10463: sub format_name {
10464: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10465: my $name;
10466: if ($first ne 'lastname') {
10467: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10468: } else {
10469: if ($lastname=~/\S/) {
10470: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10471: $name=~s/\s+,/,/;
10472: } else {
10473: $name.= $firstname.' '.$middlename.' '.$generation;
10474: }
10475: }
10476: $name=~s/^\s+//;
10477: $name=~s/\s+$//;
10478: $name=~s/\s+/ /g;
10479: return $name;
10480: }
10481:
1.84 www 10482: # ------------------------------------------------- Write to course preferences
10483:
10484: sub writecoursepref {
10485: my ($courseid,%prefs)=@_;
10486: $courseid=~s/^\///;
10487: $courseid=~s/\_/\//g;
10488: my ($cdomain,$cnum)=split(/\//,$courseid);
10489: my $chome=homeserver($cnum,$cdomain);
10490: if (($chome eq '') || ($chome eq 'no_host')) {
10491: return 'error: no such course';
10492: }
10493: my $cstring='';
1.800 albertel 10494: foreach my $pref (keys(%prefs)) {
10495: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10496: }
1.84 www 10497: $cstring=~s/\&$//;
10498: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10499: }
10500:
10501: # ---------------------------------------------------------- Make/modify course
10502:
10503: sub createcourse {
1.741 raeburn 10504: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10505: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10506: $url=&declutter($url);
10507: my $cid='';
1.1028 raeburn 10508: if ($context eq 'requestcourses') {
10509: my $can_create = 0;
10510: my ($ownername,$ownerdom) = split(':',$course_owner);
10511: if ($udom eq $ownerdom) {
10512: if (&usertools_access($ownername,$ownerdom,$category,undef,
10513: $context)) {
10514: $can_create = 1;
10515: }
10516: } else {
10517: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10518: $category);
10519: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10520: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10521: if (@curr > 0) {
10522: my @options = qw(approval validate autolimit);
10523: my $optregex = join('|',@options);
10524: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10525: $can_create = 1;
10526: }
10527: }
10528: }
10529: }
10530: if ($can_create) {
10531: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10532: unless (&allowed('ccc',$udom)) {
10533: return 'refused';
10534: }
1.1017 raeburn 10535: }
10536: } else {
10537: return 'refused';
10538: }
1.1028 raeburn 10539: } elsif (!&allowed('ccc',$udom)) {
10540: return 'refused';
1.84 www 10541: }
1.1011 raeburn 10542: # --------------------------------------------------------------- Get Unique ID
10543: my $uname;
10544: if ($cnum =~ /^$match_courseid$/) {
10545: my $chome=&homeserver($cnum,$udom,'true');
10546: if (($chome eq '') || ($chome eq 'no_host')) {
10547: $uname = $cnum;
10548: } else {
1.1038 raeburn 10549: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10550: }
10551: } else {
1.1038 raeburn 10552: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10553: }
10554: return $uname if ($uname =~ /^error/);
10555: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10556: if (!defined($course_server)) {
10557: if (defined(&domain($udom,'primary'))) {
10558: $course_server = &domain($udom,'primary');
10559: } else {
10560: $course_server = $env{'user.home'};
10561: }
10562: }
10563: my %host_servers =
10564: &Apache::lonnet::get_servers($udom,'library');
10565: unless ($host_servers{$course_server}) {
10566: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10567: }
1.84 www 10568: # ------------------------------------------------------------- Make the course
10569: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10570: $course_server);
1.84 www 10571: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10572: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10573: if (($uhome eq '') || ($uhome eq 'no_host')) {
10574: return 'error: no such course';
10575: }
1.271 www 10576: # ----------------------------------------------------------------- Course made
1.516 raeburn 10577: # log existence
1.1029 raeburn 10578: my $now = time;
1.918 raeburn 10579: my $newcourse = {
10580: $udom.'_'.$uname => {
1.921 raeburn 10581: description => $description,
10582: inst_code => $inst_code,
10583: owner => $course_owner,
10584: type => $crstype,
1.1029 raeburn 10585: creator => $env{'user.name'}.':'.
10586: $env{'user.domain'},
10587: created => $now,
10588: context => $context,
1.918 raeburn 10589: },
10590: };
1.921 raeburn 10591: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10592: # set toplevel url
1.271 www 10593: my $topurl=$url;
10594: unless ($nonstandard) {
10595: # ------------------------------------------ For standard courses, make top url
10596: my $mapurl=&clutter($url);
1.278 www 10597: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10598: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10599: <map>
10600: <resource id="1" type="start"></resource>
10601: <resource id="2" src="$mapurl"></resource>
10602: <resource id="3" type="finish"></resource>
10603: <link index="1" from="1" to="2"></link>
10604: <link index="2" from="2" to="3"></link>
10605: </map>
10606: ENDINITMAP
10607: $topurl=&declutter(
1.638 albertel 10608: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10609: );
10610: }
10611: # ----------------------------------------------------------- Write preferences
1.84 www 10612: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10613: ('description' => $description,
10614: 'url' => $topurl,
10615: 'internal.creator' => $env{'user.name'}.':'.
10616: $env{'user.domain'},
10617: 'internal.created' => $now,
10618: 'internal.creationcontext' => $context)
10619: );
1.84 www 10620: return '/'.$udom.'/'.$uname;
10621: }
10622:
1.1011 raeburn 10623: # ------------------------------------------------------------------- Create ID
10624: sub generate_coursenum {
1.1038 raeburn 10625: my ($udom,$crstype) = @_;
1.1011 raeburn 10626: my $domdesc = &domain($udom);
10627: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10628: my $first;
10629: if ($crstype eq 'Community') {
10630: $first = '0';
10631: } else {
10632: $first = int(1+rand(9));
10633: }
10634: my $uname=$first.
1.1011 raeburn 10635: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10636: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10637: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10638: # ----------------------------------------------- Make sure that does not exist
10639: my $uhome=&homeserver($uname,$udom,'true');
10640: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10641: if ($crstype eq 'Community') {
10642: $first = '0';
10643: } else {
10644: $first = int(1+rand(9));
10645: }
10646: $uname=$first.
1.1011 raeburn 10647: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10648: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10649: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10650: $uhome=&homeserver($uname,$udom,'true');
10651: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10652: return 'error: unable to generate unique course-ID';
10653: }
10654: }
10655: return $uname;
10656: }
10657:
1.813 albertel 10658: sub is_course {
1.1167 droeschl 10659: my ($cdom, $cnum) = scalar(@_) == 1 ?
10660: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10661: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10662: my $uhome=&homeserver($cnum,$cdom);
10663: my $iscourse;
10664: if (grep { $_ eq $uhome } current_machine_ids()) {
10665: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10666: } else {
10667: my $hashid = $cdom.':'.$cnum;
10668: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10669: unless (defined($cached)) {
10670: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10671: $cnum,undef,undef,'.');
10672: $iscourse = 0;
10673: if (exists($courses{$cdom.'_'.$cnum})) {
10674: $iscourse = 1;
10675: }
10676: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10677: }
10678: }
10679: return unless($iscourse);
1.1167 droeschl 10680: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10681: }
10682:
1.1015 raeburn 10683: sub store_userdata {
10684: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10685: my $result;
1.1016 raeburn 10686: if ($datakey ne '') {
1.1013 raeburn 10687: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10688: if ($udom eq '' || $uname eq '') {
10689: $udom = $env{'user.domain'};
10690: $uname = $env{'user.name'};
10691: }
10692: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10693: if (($uhome eq '') || ($uhome eq 'no_host')) {
10694: $result = 'error: no_host';
10695: } else {
1.1172.2.138 raeburn 10696: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10697: $storehash->{'host'} = $perlvar{'lonHostID'};
10698:
10699: my $namevalue='';
10700: foreach my $key (keys(%{$storehash})) {
10701: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10702: }
10703: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10704: unless ($namespace eq 'courserequests') {
10705: $datakey = &escape($datakey);
10706: }
1.1105 raeburn 10707: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10708: $namevalue,$uhome);
1.1013 raeburn 10709: }
10710: } else {
10711: $result = 'error: data to store was not a hash reference';
10712: }
10713: } else {
10714: $result= 'error: invalid requestkey';
10715: }
10716: return $result;
10717: }
10718:
1.21 www 10719: # ---------------------------------------------------------- Assign Custom Role
10720:
10721: sub assigncustomrole {
1.957 raeburn 10722: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10723: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10724: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10725: }
10726:
10727: # ----------------------------------------------------------------- Revoke Role
10728:
10729: sub revokerole {
1.957 raeburn 10730: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10731: my $now=time;
1.965 raeburn 10732: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10733: }
10734:
10735: # ---------------------------------------------------------- Revoke Custom Role
10736:
10737: sub revokecustomrole {
1.957 raeburn 10738: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10739: my $now=time;
1.357 www 10740: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10741: $deleteflag,$selfenroll,$context);
1.17 www 10742: }
10743:
1.533 banghart 10744: # ------------------------------------------------------------ Disk usage
1.535 albertel 10745: sub diskusage {
1.955 raeburn 10746: my ($udom,$uname,$directorypath,$getpropath)=@_;
10747: $directorypath =~ s/\/$//;
10748: my $listing=&reply('du2:'.&escape($directorypath).':'
10749: .&escape($getpropath).':'.&escape($uname).':'
10750: .&escape($udom),homeserver($uname,$udom));
10751: if ($listing eq 'unknown_cmd') {
10752: if ($getpropath) {
10753: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10754: }
10755: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10756: }
1.514 albertel 10757: return $listing;
1.512 banghart 10758: }
10759:
1.566 banghart 10760: sub is_locked {
1.1096 raeburn 10761: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10762: my @check;
10763: my $is_locked;
1.1093 raeburn 10764: push (@check,$file_name);
1.613 albertel 10765: my %locked = &get('file_permissions',\@check,
1.620 albertel 10766: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10767: my ($tmp)=keys(%locked);
10768: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10769:
1.566 banghart 10770: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10771: $is_locked = 'false';
10772: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10773: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10774: $is_locked = 'true';
1.1096 raeburn 10775: if (ref($which) eq 'ARRAY') {
10776: push(@{$which},$entry);
10777: } else {
10778: last;
10779: }
1.745 raeburn 10780: }
10781: }
1.566 banghart 10782: } else {
10783: $is_locked = 'false';
10784: }
1.1093 raeburn 10785: return $is_locked;
1.566 banghart 10786: }
10787:
1.759 albertel 10788: sub declutter_portfile {
10789: my ($file) = @_;
1.833 albertel 10790: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10791: return $file;
10792: }
10793:
1.559 banghart 10794: # ------------------------------------------------------------- Mark as Read Only
10795:
10796: sub mark_as_readonly {
10797: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10798: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10799: my ($tmp)=keys(%current_permissions);
10800: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10801: foreach my $file (@{$files}) {
1.759 albertel 10802: $file = &declutter_portfile($file);
1.561 banghart 10803: push(@{$current_permissions{$file}},$what);
1.559 banghart 10804: }
1.613 albertel 10805: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10806: return;
10807: }
10808:
1.572 banghart 10809: # ------------------------------------------------------------Save Selected Files
10810:
10811: sub save_selected_files {
10812: my ($user, $path, @files) = @_;
10813: my $filename = $user."savedfiles";
1.573 banghart 10814: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10815: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10816: foreach my $file (@files) {
1.620 albertel 10817: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10818: }
10819: foreach my $file (@other_files) {
1.574 banghart 10820: print (OUT $file."\n");
1.572 banghart 10821: }
1.574 banghart 10822: close (OUT);
1.572 banghart 10823: return 'ok';
10824: }
10825:
1.574 banghart 10826: sub clear_selected_files {
10827: my ($user) = @_;
10828: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10829: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10830: print (OUT undef);
10831: close (OUT);
10832: return ("ok");
10833: }
10834:
1.572 banghart 10835: sub files_in_path {
10836: my ($user, $path) = @_;
10837: my $filename = $user."savedfiles";
10838: my %return_files;
1.1172.2.96 raeburn 10839: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10840: while (my $line_in = <IN>) {
1.574 banghart 10841: chomp ($line_in);
10842: my @paths_and_file = split (m!/!, $line_in);
10843: my $file_part = pop (@paths_and_file);
10844: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10845: $path_part.='/';
10846: my $path_and_file = $path_part.$file_part;
10847: if ($path_part eq $path) {
10848: $return_files{$file_part}= 'selected';
10849: }
10850: }
1.574 banghart 10851: close (IN);
10852: return (\%return_files);
1.572 banghart 10853: }
10854:
10855: # called in portfolio select mode, to show files selected NOT in current directory
10856: sub files_not_in_path {
10857: my ($user, $path) = @_;
10858: my $filename = $user."savedfiles";
10859: my @return_files;
10860: my $path_part;
1.1172.2.96 raeburn 10861: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10862: while (my $line = <IN>) {
1.572 banghart 10863: #ok, I know it's clunky, but I want it to work
1.800 albertel 10864: my @paths_and_file = split(m|/|, $line);
10865: my $file_part = pop(@paths_and_file);
10866: chomp($file_part);
10867: my $path_part = join('/', @paths_and_file);
1.572 banghart 10868: $path_part .= '/';
10869: my $path_and_file = $path_part.$file_part;
10870: if ($path_part ne $path) {
1.800 albertel 10871: push(@return_files, ($path_and_file));
1.572 banghart 10872: }
10873: }
1.800 albertel 10874: close(OUT);
1.574 banghart 10875: return (@return_files);
1.572 banghart 10876: }
10877:
1.745 raeburn 10878: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10879:
1.745 raeburn 10880: sub get_portfile_permissions {
10881: my ($domain,$user) = @_;
1.613 albertel 10882: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10883: my ($tmp)=keys(%current_permissions);
10884: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10885: return \%current_permissions;
10886: }
10887:
10888: #---------------------------------------------Get portfolio file access controls
10889:
1.749 raeburn 10890: sub get_access_controls {
1.745 raeburn 10891: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10892: my %access;
10893: my $real_file = $file;
10894: $file =~ s/\.meta$//;
1.745 raeburn 10895: if (defined($file)) {
1.749 raeburn 10896: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10897: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10898: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10899: }
10900: }
1.745 raeburn 10901: } else {
1.749 raeburn 10902: foreach my $key (keys(%{$current_permissions})) {
10903: if ($key =~ /\0accesscontrol$/) {
10904: if (defined($group)) {
10905: if ($key !~ m-^\Q$group\E/-) {
10906: next;
10907: }
10908: }
10909: my ($fullpath) = split(/\0/,$key);
10910: if (ref($$current_permissions{$key}) eq 'HASH') {
10911: foreach my $control (keys(%{$$current_permissions{$key}})) {
10912: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10913: }
10914: }
10915: }
10916: }
10917: }
10918: return %access;
10919: }
10920:
10921: sub modify_access_controls {
10922: my ($file_name,$changes,$domain,$user)=@_;
10923: my ($outcome,$deloutcome);
10924: my %store_permissions;
10925: my %new_values;
10926: my %new_control;
10927: my %translation;
10928: my @deletions = ();
10929: my $now = time;
10930: if (exists($$changes{'activate'})) {
10931: if (ref($$changes{'activate'}) eq 'HASH') {
10932: my @newitems = sort(keys(%{$$changes{'activate'}}));
10933: my $numnew = scalar(@newitems);
10934: for (my $i=0; $i<$numnew; $i++) {
10935: my $newkey = $newitems[$i];
10936: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10937: if ($newkey =~ /^\d+:/) {
10938: $newkey =~ s/^(\d+)/$newid/;
10939: $translation{$1} = $newid;
10940: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10941: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10942: $translation{$1} = $newid;
10943: }
1.749 raeburn 10944: $new_values{$file_name."\0".$newkey} =
10945: $$changes{'activate'}{$newitems[$i]};
10946: $new_control{$newkey} = $now;
10947: }
10948: }
10949: }
10950: my %todelete;
10951: my %changed_items;
10952: foreach my $action ('delete','update') {
10953: if (exists($$changes{$action})) {
10954: if (ref($$changes{$action}) eq 'HASH') {
10955: foreach my $key (keys(%{$$changes{$action}})) {
10956: my ($itemnum) = ($key =~ /^([^:]+):/);
10957: if ($action eq 'delete') {
10958: $todelete{$itemnum} = 1;
10959: } else {
10960: $changed_items{$itemnum} = $key;
10961: }
10962: }
1.745 raeburn 10963: }
10964: }
1.749 raeburn 10965: }
10966: # get lock on access controls for file.
10967: my $lockhash = {
10968: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10969: ':'.$env{'user.domain'},
10970: };
10971: my $tries = 0;
10972: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10973:
1.1172.2.79 raeburn 10974: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10975: $tries ++;
1.1172.2.79 raeburn 10976: sleep(0.1);
1.749 raeburn 10977: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10978: }
10979: if ($gotlock eq 'ok') {
10980: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10981: my ($tmp)=keys(%curr_permissions);
10982: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10983: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10984: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10985: if (ref($curr_controls) eq 'HASH') {
10986: foreach my $control_item (keys(%{$curr_controls})) {
10987: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10988: if (defined($todelete{$itemnum})) {
10989: push(@deletions,$file_name."\0".$control_item);
10990: } else {
10991: if (defined($changed_items{$itemnum})) {
10992: $new_control{$changed_items{$itemnum}} = $now;
10993: push(@deletions,$file_name."\0".$control_item);
10994: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10995: } else {
10996: $new_control{$control_item} = $$curr_controls{$control_item};
10997: }
10998: }
1.745 raeburn 10999: }
11000: }
11001: }
1.970 raeburn 11002: my ($group);
11003: if (&is_course($domain,$user)) {
11004: ($group,my $file) = split(/\//,$file_name,2);
11005: }
1.749 raeburn 11006: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11007: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11008: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11009: # remove lock
11010: my @del_lock = ($file_name."\0".'locked_access_records');
11011: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11012: my $sqlresult =
1.970 raeburn 11013: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11014: $group);
1.749 raeburn 11015: } else {
11016: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11017: }
1.749 raeburn 11018: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11019: }
11020:
1.827 raeburn 11021: sub make_public_indefinitely {
11022: my ($requrl) = @_;
11023: my $now = time;
11024: my $action = 'activate';
11025: my $aclnum = 0;
11026: if (&is_portfolio_url($requrl)) {
11027: my (undef,$udom,$unum,$file_name,$group) =
11028: &parse_portfolio_url($requrl);
11029: my $current_perms = &get_portfile_permissions($udom,$unum);
11030: my %access_controls = &get_access_controls($current_perms,
11031: $group,$file_name);
11032: foreach my $key (keys(%{$access_controls{$file_name}})) {
11033: my ($num,$scope,$end,$start) =
11034: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11035: if ($scope eq 'public') {
11036: if ($start <= $now && $end == 0) {
11037: $action = 'none';
11038: } else {
11039: $action = 'update';
11040: $aclnum = $num;
11041: }
11042: last;
11043: }
11044: }
11045: if ($action eq 'none') {
11046: return 'ok';
11047: } else {
11048: my %changes;
11049: my $newend = 0;
11050: my $newstart = $now;
11051: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11052: $changes{$action}{$newkey} = {
11053: type => 'public',
11054: time => {
11055: start => $newstart,
11056: end => $newend,
11057: },
11058: };
11059: my ($outcome,$deloutcome,$new_values,$translation) =
11060: &modify_access_controls($file_name,\%changes,$udom,$unum);
11061: return $outcome;
11062: }
11063: } else {
11064: return 'invalid';
11065: }
11066: }
11067:
1.745 raeburn 11068: #------------------------------------------------------Get Marked as Read Only
11069:
11070: sub get_marked_as_readonly {
11071: my ($domain,$user,$what,$group) = @_;
11072: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11073: my @readonly_files;
1.629 banghart 11074: my $cmp1=$what;
11075: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11076: while (my ($file_name,$value) = each(%{$current_permissions})) {
11077: if (defined($group)) {
11078: if ($file_name !~ m-^\Q$group\E/-) {
11079: next;
11080: }
11081: }
1.561 banghart 11082: if (ref($value) eq "ARRAY"){
11083: foreach my $stored_what (@{$value}) {
1.629 banghart 11084: my $cmp2=$stored_what;
1.759 albertel 11085: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11086: $cmp2=join('',@{$stored_what});
1.745 raeburn 11087: }
1.629 banghart 11088: if ($cmp1 eq $cmp2) {
1.561 banghart 11089: push(@readonly_files, $file_name);
1.745 raeburn 11090: last;
1.563 banghart 11091: } elsif (!defined($what)) {
11092: push(@readonly_files, $file_name);
1.745 raeburn 11093: last;
1.561 banghart 11094: }
11095: }
1.745 raeburn 11096: }
1.561 banghart 11097: }
11098: return @readonly_files;
11099: }
1.577 banghart 11100: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11101:
1.577 banghart 11102: sub get_marked_as_readonly_hash {
1.745 raeburn 11103: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11104: my %readonly_files;
1.745 raeburn 11105: while (my ($file_name,$value) = each(%{$current_permissions})) {
11106: if (defined($group)) {
11107: if ($file_name !~ m-^\Q$group\E/-) {
11108: next;
11109: }
11110: }
1.577 banghart 11111: if (ref($value) eq "ARRAY"){
11112: foreach my $stored_what (@{$value}) {
1.745 raeburn 11113: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11114: foreach my $lock_descriptor(@{$stored_what}) {
11115: if ($lock_descriptor eq 'graded') {
11116: $readonly_files{$file_name} = 'graded';
11117: } elsif ($lock_descriptor eq 'handback') {
11118: $readonly_files{$file_name} = 'handback';
11119: } else {
11120: if (!exists($readonly_files{$file_name})) {
11121: $readonly_files{$file_name} = 'locked';
11122: }
11123: }
1.745 raeburn 11124: }
1.750 banghart 11125: }
1.577 banghart 11126: }
11127: }
11128: }
11129: return %readonly_files;
11130: }
1.559 banghart 11131: # ------------------------------------------------------------ Unmark as Read Only
11132:
11133: sub unmark_as_readonly {
1.629 banghart 11134: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11135: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11136: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11137: $file_name = &declutter_portfile($file_name);
1.634 albertel 11138: my $symb_crs = $what;
11139: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11140: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11141: my ($tmp)=keys(%current_permissions);
11142: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11143: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11144: foreach my $file (@readonly_files) {
1.759 albertel 11145: my $clean_file = &declutter_portfile($file);
11146: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11147: my $current_locks = $current_permissions{$file};
1.563 banghart 11148: my @new_locks;
11149: my @del_keys;
11150: if (ref($current_locks) eq "ARRAY"){
11151: foreach my $locker (@{$current_locks}) {
1.632 albertel 11152: my $compare=$locker;
1.749 raeburn 11153: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11154: $compare=join('',@{$locker});
1.746 raeburn 11155: if ($compare ne $symb_crs) {
11156: push(@new_locks, $locker);
11157: }
1.563 banghart 11158: }
11159: }
1.650 albertel 11160: if (scalar(@new_locks) > 0) {
1.563 banghart 11161: $current_permissions{$file} = \@new_locks;
11162: } else {
11163: push(@del_keys, $file);
1.613 albertel 11164: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11165: delete($current_permissions{$file});
1.563 banghart 11166: }
11167: }
1.561 banghart 11168: }
1.613 albertel 11169: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11170: return;
11171: }
1.512 banghart 11172:
1.17 www 11173: # ------------------------------------------------------------ Directory lister
11174:
11175: sub dirlist {
1.955 raeburn 11176: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11177: $uri=~s/^\///;
11178: $uri=~s/\/$//;
1.253 stredwic 11179: my ($udom, $uname);
1.955 raeburn 11180: if ($getuserdir) {
1.253 stredwic 11181: $udom = $userdomain;
11182: $uname = $username;
1.955 raeburn 11183: } else {
11184: (undef,$udom,$uname)=split(/\//,$uri);
11185: if(defined($userdomain)) {
11186: $udom = $userdomain;
11187: }
11188: if(defined($username)) {
11189: $uname = $username;
11190: }
1.253 stredwic 11191: }
1.955 raeburn 11192: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11193:
1.955 raeburn 11194: $dirRoot = $perlvar{'lonDocRoot'};
11195: if (defined($getpropath)) {
11196: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11197: $dirRoot =~ s/\/$//;
1.955 raeburn 11198: } elsif (defined($getuserdir)) {
11199: my $subdir=$uname.'__';
11200: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11201: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11202: ."/$udom/$subdir/$uname";
11203: } elsif (defined($alternateRoot)) {
11204: $dirRoot = $alternateRoot;
1.751 banghart 11205: }
1.253 stredwic 11206:
11207: if($udom) {
11208: if($uname) {
1.1135 raeburn 11209: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11210: if ($uhome eq 'no_host') {
11211: return ([],'no_host');
11212: }
1.955 raeburn 11213: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11214: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11215: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11216: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11217: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11218: } else {
11219: @listing_results = map { &unescape($_); } split(/:/,$listing);
11220: }
1.605 matthew 11221: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11222: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11223: @listing_results = split(/:/,$listing);
11224: } else {
11225: @listing_results = map { &unescape($_); } split(/:/,$listing);
11226: }
1.1135 raeburn 11227: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11228: ($listing eq 'rejected') || ($listing eq 'refused') ||
11229: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11230: return ([],$listing);
11231: } else {
11232: return (\@listing_results);
1.1135 raeburn 11233: }
1.955 raeburn 11234: } elsif(!$alternateRoot) {
1.1136 raeburn 11235: my (%allusers,%listerror);
1.841 albertel 11236: my %servers = &get_servers($udom,'library');
1.955 raeburn 11237: foreach my $tryserver (keys(%servers)) {
11238: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11239: &escape($udom),$tryserver);
11240: if ($listing eq 'unknown_cmd') {
11241: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11242: $udom, $tryserver);
11243: } else {
11244: @listing_results = map { &unescape($_); } split(/:/,$listing);
11245: }
1.841 albertel 11246: if ($listing eq 'unknown_cmd') {
11247: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11248: $udom, $tryserver);
11249: @listing_results = split(/:/,$listing);
11250: } else {
11251: @listing_results =
11252: map { &unescape($_); } split(/:/,$listing);
11253: }
1.1136 raeburn 11254: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11255: ($listing eq 'rejected') || ($listing eq 'refused') ||
11256: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11257: $listerror{$tryserver} = $listing;
11258: } else {
1.841 albertel 11259: foreach my $line (@listing_results) {
11260: my ($entry) = split(/&/,$line,2);
11261: $allusers{$entry} = 1;
11262: }
11263: }
1.253 stredwic 11264: }
1.1136 raeburn 11265: my @alluserslist=();
1.800 albertel 11266: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11267: push(@alluserslist,$user.'&user');
1.253 stredwic 11268: }
1.1172.2.80 raeburn 11269: if (!%listerror) {
11270: # no errors
11271: return (\@alluserslist);
11272: } elsif (scalar(keys(%servers)) == 1) {
11273: # one library server, one error
11274: my ($key) = keys(%listerror);
11275: return (\@alluserslist, $listerror{$key});
11276: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11277: # con_lost indicates that we might miss data from at least one
11278: # library server
11279: return (\@alluserslist, 'con_lost');
11280: } else {
11281: # multiple library servers and no con_lost -> data should be
11282: # complete.
11283: return (\@alluserslist);
11284: }
11285:
1.253 stredwic 11286: } else {
1.1136 raeburn 11287: return ([],'missing username');
1.253 stredwic 11288: }
1.955 raeburn 11289: } elsif(!defined($getpropath)) {
1.1136 raeburn 11290: my $path = $perlvar{'lonDocRoot'}.'/res/';
11291: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11292: return (\@all_domains);
1.955 raeburn 11293: } else {
1.1136 raeburn 11294: return ([],'missing domain');
1.275 stredwic 11295: }
11296: }
11297:
11298: # --------------------------------------------- GetFileTimestamp
11299: # This function utilizes dirlist and returns the date stamp for
11300: # when it was last modified. It will also return an error of -1
11301: # if an error occurs
11302:
11303: sub GetFileTimestamp {
1.955 raeburn 11304: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11305: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11306: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11307: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11308: undef,$getuserdir);
11309: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11310: return -1;
11311: }
11312: if (ref($fileref) eq 'ARRAY') {
11313: my @stats = split('&',$fileref->[0]);
1.375 matthew 11314: # @stats contains first the filename, then the stat output
11315: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11316: } else {
11317: return -1;
1.253 stredwic 11318: }
1.26 www 11319: }
11320:
1.712 albertel 11321: sub stat_file {
11322: my ($uri) = @_;
1.787 albertel 11323: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11324:
1.955 raeburn 11325: my ($udom,$uname,$file);
1.712 albertel 11326: if ($uri =~ m-^/(uploaded|editupload)/-) {
11327: ($udom,$uname,$file) =
1.811 albertel 11328: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11329: $file = 'userfiles/'.$file;
11330: }
11331: if ($uri =~ m-^/res/-) {
11332: ($udom,$uname) =
1.807 albertel 11333: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11334: $file = $uri;
11335: }
11336:
11337: if (!$udom || !$uname || !$file) {
11338: # unable to handle the uri
11339: return ();
11340: }
1.956 raeburn 11341: my $getpropath;
11342: if ($file =~ /^userfiles\//) {
11343: $getpropath = 1;
11344: }
1.1136 raeburn 11345: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11346: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11347: return ();
11348: } else {
11349: if (ref($listref) eq 'ARRAY') {
11350: my @stats = split('&',$listref->[0]);
11351: shift(@stats); #filename is first
11352: return @stats;
11353: }
1.712 albertel 11354: }
11355: return ();
11356: }
11357:
1.26 www 11358: # -------------------------------------------------------- Value of a Condition
11359:
1.713 albertel 11360: # gets the value of a specific preevaluated condition
11361: # stored in the string $env{user.state.<cid>}
11362: # or looks up a condition reference in the bighash and if if hasn't
11363: # already been evaluated recurses into docondval to get the value of
11364: # the condition, then memoizing it to
11365: # $env{user.state.<cid>.<condition>}
1.40 www 11366: sub directcondval {
11367: my $number=shift;
1.620 albertel 11368: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11369: &Apache::lonuserstate::evalstate();
11370: }
1.713 albertel 11371: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11372: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11373: } elsif ($number =~ /^_/) {
11374: my $sub_condition;
11375: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11376: &GDBM_READER(),0640)) {
11377: $sub_condition=$bighash{'conditions'.$number};
11378: untie(%bighash);
11379: }
11380: my $value = &docondval($sub_condition);
1.949 raeburn 11381: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11382: return $value;
11383: }
1.620 albertel 11384: if ($env{'user.state.'.$env{'request.course.id'}}) {
11385: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11386: } else {
11387: return 2;
11388: }
11389: }
11390:
1.713 albertel 11391: # get the collection of conditions for this resource
1.26 www 11392: sub condval {
11393: my $condidx=shift;
1.54 www 11394: my $allpathcond='';
1.713 albertel 11395: foreach my $cond (split(/\|/,$condidx)) {
11396: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11397: $allpathcond.=
11398: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11399: }
1.191 harris41 11400: }
1.54 www 11401: $allpathcond=~s/\|$//;
1.713 albertel 11402: return &docondval($allpathcond);
11403: }
11404:
11405: #evaluates an expression of conditions
11406: sub docondval {
11407: my ($allpathcond) = @_;
11408: my $result=0;
11409: if ($env{'request.course.id'}
11410: && defined($allpathcond)) {
11411: my $operand='|';
11412: my @stack;
11413: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11414: if ($chunk eq '(') {
11415: push @stack,($operand,$result);
11416: } elsif ($chunk eq ')') {
11417: my $before=pop @stack;
11418: if (pop @stack eq '&') {
11419: $result=$result>$before?$before:$result;
11420: } else {
11421: $result=$result>$before?$result:$before;
11422: }
11423: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11424: $operand=$chunk;
11425: } else {
11426: my $new=directcondval($chunk);
11427: if ($operand eq '&') {
11428: $result=$result>$new?$new:$result;
11429: } else {
11430: $result=$result>$new?$result:$new;
11431: }
11432: }
11433: }
1.26 www 11434: }
11435: return $result;
1.421 albertel 11436: }
11437:
11438: # ---------------------------------------------------- Devalidate courseresdata
11439:
11440: sub devalidatecourseresdata {
11441: my ($coursenum,$coursedomain)=@_;
11442: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11443: &devalidate_cache_new('courseres',$hashid);
1.28 www 11444: }
11445:
1.763 www 11446:
1.200 www 11447: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11448: #
11449: # Parameters:
11450: # $coursenum - Number of the course.
11451: # $coursedomain - Domain at which the course was created.
11452: # Returns:
11453: # A hash of the course parameters along (I think) with timestamps
11454: # and version info.
1.877 foxr 11455:
1.624 albertel 11456: sub get_courseresdata {
11457: my ($coursenum,$coursedomain)=@_;
1.200 www 11458: my $coursehom=&homeserver($coursenum,$coursedomain);
11459: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11460: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11461: my %dumpreply;
1.417 albertel 11462: unless (defined($cached)) {
1.624 albertel 11463: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11464: $result=\%dumpreply;
1.251 albertel 11465: my ($tmp) = keys(%dumpreply);
11466: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11467: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11468: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11469: return $tmp;
1.416 albertel 11470: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11471: $result=undef;
1.599 albertel 11472: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11473: }
11474: }
1.624 albertel 11475: return $result;
11476: }
11477:
1.633 albertel 11478: sub devalidateuserresdata {
11479: my ($uname,$udom)=@_;
11480: my $hashid="$udom:$uname";
11481: &devalidate_cache_new('userres',$hashid);
11482: }
11483:
1.624 albertel 11484: sub get_userresdata {
11485: my ($uname,$udom)=@_;
11486: #most student don\'t have any data set, check if there is some data
11487: if (&EXT_cache_status($udom,$uname)) { return undef; }
11488:
11489: my $hashid="$udom:$uname";
11490: my ($result,$cached)=&is_cached_new('userres',$hashid);
11491: if (!defined($cached)) {
11492: my %resourcedata=&dump('resourcedata',$udom,$uname);
11493: $result=\%resourcedata;
11494: &do_cache_new('userres',$hashid,$result,600);
11495: }
11496: my ($tmp)=keys(%$result);
11497: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11498: return $result;
11499: }
11500: #error 2 occurs when the .db doesn't exist
11501: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11502: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11503: &logthis("<font color=\"blue\">WARNING:".
11504: " Trying to get resource data for ".
11505: $uname." at ".$udom.": ".
11506: $tmp."</font>");
11507: }
1.624 albertel 11508: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11509: #&EXT_cache_set($udom,$uname);
11510: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11511: undef($tmp); # not really an error so don't send it back
1.624 albertel 11512: }
11513: return $tmp;
11514: }
1.879 foxr 11515: #----------------------------------------------- resdata - return resource data
11516: # Purpose:
11517: # Return resource data for either users or for a course.
11518: # Parameters:
11519: # $name - Course/user name.
11520: # $domain - Name of the domain the user/course is registered on.
11521: # $type - Type of thing $name is (must be 'course' or 'user'
11522: # @which - Array of names of resources desired.
11523: # Returns:
11524: # The value of the first reasource in @which that is found in the
11525: # resource hash.
11526: # Exceptional Conditions:
11527: # If the $type passed in is not valid (not the string 'course' or
11528: # 'user', an undefined reference is returned.
11529: # If none of the resources are found, an undef is returned
1.624 albertel 11530: sub resdata {
11531: my ($name,$domain,$type,@which)=@_;
11532: my $result;
11533: if ($type eq 'course') {
11534: $result=&get_courseresdata($name,$domain);
11535: } elsif ($type eq 'user') {
11536: $result=&get_userresdata($name,$domain);
11537: }
11538: if (!ref($result)) { return $result; }
1.251 albertel 11539: foreach my $item (@which) {
1.927 albertel 11540: if (defined($result->{$item->[0]})) {
11541: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11542: }
1.250 albertel 11543: }
1.291 albertel 11544: return undef;
1.200 www 11545: }
11546:
1.1172.2.31 raeburn 11547: sub get_numsuppfiles {
11548: my ($cnum,$cdom,$ignorecache)=@_;
11549: my $hashid=$cnum.':'.$cdom;
11550: my ($suppcount,$cached);
11551: unless ($ignorecache) {
11552: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11553: }
11554: unless (defined($cached)) {
11555: my $chome=&homeserver($cnum,$cdom);
11556: unless ($chome eq 'no_host') {
11557: ($suppcount,my $errors) = (0,0);
11558: my $suppmap = 'supplemental.sequence';
11559: ($suppcount,$errors) =
11560: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11561: }
11562: &do_cache_new('suppcount',$hashid,$suppcount,600);
11563: }
11564: return $suppcount;
11565: }
11566:
1.379 matthew 11567: #
11568: # EXT resource caching routines
11569: #
11570:
11571: sub clear_EXT_cache_status {
1.383 albertel 11572: &delenv('cache.EXT.');
1.379 matthew 11573: }
11574:
11575: sub EXT_cache_status {
11576: my ($target_domain,$target_user) = @_;
1.383 albertel 11577: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11578: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11579: # We know already the user has no data
11580: return 1;
11581: } else {
11582: return 0;
11583: }
11584: }
11585:
11586: sub EXT_cache_set {
11587: my ($target_domain,$target_user) = @_;
1.383 albertel 11588: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11589: #&appenv({$cachename => time});
1.379 matthew 11590: }
11591:
1.28 www 11592: # --------------------------------------------------------- Value of a Variable
1.58 www 11593: sub EXT {
1.715 albertel 11594:
1.1172.2.28 raeburn 11595: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11596: unless ($varname) { return ''; }
1.218 albertel 11597: #get real user name/domain, courseid and symb
11598: my $courseid;
1.359 albertel 11599: my $publicuser;
1.427 www 11600: if ($symbparm) {
11601: $symbparm=&get_symb_from_alias($symbparm);
11602: }
1.218 albertel 11603: if (!($uname && $udom)) {
1.790 albertel 11604: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11605: if (!$symbparm) { $symbparm=$cursymb; }
11606: } else {
1.620 albertel 11607: $courseid=$env{'request.course.id'};
1.218 albertel 11608: }
1.48 www 11609: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11610: my $rest;
1.320 albertel 11611: if (defined($therest[0])) {
1.48 www 11612: $rest=join('.',@therest);
11613: } else {
11614: $rest='';
11615: }
1.320 albertel 11616:
1.57 www 11617: my $qualifierrest=$qualifier;
11618: if ($rest) { $qualifierrest.='.'.$rest; }
11619: my $spacequalifierrest=$space;
11620: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11621: if ($realm eq 'user') {
1.48 www 11622: # --------------------------------------------------------------- user.resource
11623: if ($space eq 'resource') {
1.651 albertel 11624: if ( (defined($Apache::lonhomework::parsing_a_problem)
11625: || defined($Apache::lonhomework::parsing_a_task))
11626: &&
1.1172.2.142 raeburn 11627: ($symbparm eq &symbread()) ) {
1.744 albertel 11628: # if we are in the middle of processing the resource the
11629: # get the value we are planning on committing
11630: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11631: return $Apache::lonhomework::results{$qualifierrest};
11632: } else {
11633: return $Apache::lonhomework::history{$qualifierrest};
11634: }
1.335 albertel 11635: } else {
1.359 albertel 11636: my %restored;
1.620 albertel 11637: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11638: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11639: } else {
11640: %restored=&restore($symbparm,$courseid,$udom,$uname);
11641: }
1.335 albertel 11642: return $restored{$qualifierrest};
11643: }
1.48 www 11644: # ----------------------------------------------------------------- user.access
11645: } elsif ($space eq 'access') {
1.218 albertel 11646: # FIXME - not supporting calls for a specific user
1.48 www 11647: return &allowed($qualifier,$rest);
11648: # ------------------------------------------ user.preferences, user.environment
11649: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11650: if (($uname eq $env{'user.name'}) &&
11651: ($udom eq $env{'user.domain'})) {
11652: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11653: } else {
1.359 albertel 11654: my %returnhash;
11655: if (!$publicuser) {
11656: %returnhash=&userenvironment($udom,$uname,
11657: $qualifierrest);
11658: }
1.218 albertel 11659: return $returnhash{$qualifierrest};
11660: }
1.48 www 11661: # ----------------------------------------------------------------- user.course
11662: } elsif ($space eq 'course') {
1.218 albertel 11663: # FIXME - not supporting calls for a specific user
1.620 albertel 11664: return $env{join('.',('request.course',$qualifier))};
1.48 www 11665: # ------------------------------------------------------------------- user.role
11666: } elsif ($space eq 'role') {
1.218 albertel 11667: # FIXME - not supporting calls for a specific user
1.620 albertel 11668: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11669: if ($qualifier eq 'value') {
11670: return $role;
11671: } elsif ($qualifier eq 'extent') {
11672: return $where;
11673: }
11674: # ----------------------------------------------------------------- user.domain
11675: } elsif ($space eq 'domain') {
1.218 albertel 11676: return $udom;
1.48 www 11677: # ------------------------------------------------------------------- user.name
11678: } elsif ($space eq 'name') {
1.218 albertel 11679: return $uname;
1.48 www 11680: # ---------------------------------------------------- Any other user namespace
1.29 www 11681: } else {
1.359 albertel 11682: my %reply;
11683: if (!$publicuser) {
11684: %reply=&get($space,[$qualifierrest],$udom,$uname);
11685: }
11686: return $reply{$qualifierrest};
1.48 www 11687: }
1.236 www 11688: } elsif ($realm eq 'query') {
11689: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11690: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11691: [$spacequalifierrest]);
1.620 albertel 11692: return $env{'form.'.$spacequalifierrest};
1.236 www 11693: } elsif ($realm eq 'request') {
1.48 www 11694: # ------------------------------------------------------------- request.browser
11695: if ($space eq 'browser') {
1.1145 bisitz 11696: return $env{'browser.'.$qualifier};
1.57 www 11697: # ------------------------------------------------------------ request.filename
11698: } else {
1.620 albertel 11699: return $env{'request.'.$spacequalifierrest};
1.29 www 11700: }
1.28 www 11701: } elsif ($realm eq 'course') {
1.48 www 11702: # ---------------------------------------------------------- course.description
1.620 albertel 11703: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11704: } elsif ($realm eq 'resource') {
1.165 www 11705:
1.620 albertel 11706: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11707: if (!$symbparm) { $symbparm=&symbread(); }
11708: }
1.693 albertel 11709:
1.1172.2.30 raeburn 11710: if ($qualifier eq '') {
11711: if ($space eq 'title') {
11712: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11713: return &gettitle($symbparm);
11714: }
1.693 albertel 11715:
1.1172.2.30 raeburn 11716: if ($space eq 'map') {
11717: my ($map) = &decode_symb($symbparm);
11718: return &symbread($map);
11719: }
11720: if ($space eq 'maptitle') {
11721: my ($map) = &decode_symb($symbparm);
11722: return &gettitle($map);
11723: }
11724: if ($space eq 'filename') {
11725: if ($symbparm) {
11726: return &clutter((&decode_symb($symbparm))[2]);
11727: }
11728: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11729: }
1.1172.2.30 raeburn 11730:
11731: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11732: if ($space eq 'visibleparts') {
11733: my $navmap = Apache::lonnavmaps::navmap->new();
11734: my $item;
11735: if (ref($navmap)) {
11736: my $res = $navmap->getBySymb($symbparm);
11737: my $parts = $res->parts();
11738: if (ref($parts) eq 'ARRAY') {
11739: $item = join(',',@{$parts});
11740: }
11741: undef($navmap);
11742: }
11743: return $item;
11744: }
11745: }
11746: }
1.693 albertel 11747:
11748: my ($section, $group, @groups);
1.593 albertel 11749: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11750: if (($courseid eq '') && ($cid)) {
11751: $courseid = $cid;
11752: }
11753: if (($symbparm && $courseid) &&
11754: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11755:
1.218 albertel 11756: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11757:
1.60 www 11758: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11759: my $symbp=$symbparm;
1.735 albertel 11760: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11761:
11762: my $symbparm=$symbp.'.'.$spacequalifierrest;
11763: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11764:
1.620 albertel 11765: if (($env{'user.name'} eq $uname) &&
11766: ($env{'user.domain'} eq $udom)) {
11767: $section=$env{'request.course.sec'};
1.733 raeburn 11768: @groups = split(/:/,$env{'request.course.groups'});
11769: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11770: } else {
1.539 albertel 11771: if (! defined($usection)) {
1.551 albertel 11772: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11773: } else {
11774: $section = $usection;
11775: }
1.733 raeburn 11776: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11777: }
11778:
11779: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11780: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11781: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11782:
1.593 albertel 11783: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11784: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11785: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11786:
1.60 www 11787: # ----------------------------------------------------------- first, check user
1.624 albertel 11788:
11789: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11790: ([$courselevelr,'resource'],
11791: [$courselevelm,'map' ],
11792: [$courselevel, 'course' ]));
1.931 albertel 11793: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11794:
1.594 albertel 11795: # ------------------------------------------------ second, check some of course
1.684 raeburn 11796: my $coursereply;
1.691 raeburn 11797: if (@groups > 0) {
11798: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11799: $mapparm,$spacequalifierrest);
1.927 albertel 11800: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11801: }
1.96 www 11802:
1.684 raeburn 11803: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11804: $env{'course.'.$courseid.'.domain'},
11805: 'course',
11806: ([$seclevelr, 'resource'],
11807: [$seclevelm, 'map' ],
11808: [$seclevel, 'course' ],
11809: [$courselevelr,'resource']));
11810: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11811:
1.60 www 11812: # ------------------------------------------------------ third, check map parms
1.218 albertel 11813: my %parmhash=();
11814: my $thisparm='';
11815: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11816: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11817: &GDBM_READER(),0640)) {
1.218 albertel 11818: $thisparm=$parmhash{$symbparm};
11819: untie(%parmhash);
11820: }
1.927 albertel 11821: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11822: }
1.594 albertel 11823: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11824:
1.218 albertel 11825: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11826: my $filename;
11827: if (!$symbparm) { $symbparm=&symbread(); }
11828: if ($symbparm) {
1.409 www 11829: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11830: } else {
1.620 albertel 11831: $filename=$env{'request.filename'};
1.282 albertel 11832: }
11833: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11834: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11835: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11836: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11837:
1.927 albertel 11838: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11839: if ($symbparm && defined($courseid) &&
1.620 albertel 11840: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11841: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11842: $env{'course.'.$courseid.'.domain'},
11843: 'course',
1.927 albertel 11844: ([$courselevelm,'map' ],
11845: [$courselevel, 'course']));
11846: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11847: }
1.145 www 11848: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11849: unless ($space eq '0') {
1.336 albertel 11850: my @parts=split(/_/,$space);
11851: my $id=pop(@parts);
11852: my $part=join('_',@parts);
11853: if ($part eq '') { $part='0'; }
1.927 albertel 11854: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11855: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11856: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11857: }
1.395 albertel 11858: if ($recurse) { return undef; }
11859: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11860: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11861: # ---------------------------------------------------- Any other user namespace
11862: } elsif ($realm eq 'environment') {
11863: # ----------------------------------------------------------------- environment
1.620 albertel 11864: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11865: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11866: } else {
1.770 albertel 11867: if ($uname eq 'anonymous' && $udom eq '') {
11868: return '';
11869: }
1.219 albertel 11870: my %returnhash=&userenvironment($udom,$uname,
11871: $spacequalifierrest);
11872: return $returnhash{$spacequalifierrest};
11873: }
1.28 www 11874: } elsif ($realm eq 'system') {
1.48 www 11875: # ----------------------------------------------------------------- system.time
11876: if ($space eq 'time') {
11877: return time;
11878: }
1.696 albertel 11879: } elsif ($realm eq 'server') {
11880: # ----------------------------------------------------------------- system.time
11881: if ($space eq 'name') {
11882: return $ENV{'SERVER_NAME'};
11883: }
1.28 www 11884: }
1.48 www 11885: return '';
1.61 www 11886: }
11887:
1.927 albertel 11888: sub get_reply {
11889: my ($reply_value) = @_;
1.940 raeburn 11890: if (ref($reply_value) eq 'ARRAY') {
11891: if (wantarray) {
11892: return @$reply_value;
11893: }
11894: return $reply_value->[0];
11895: } else {
11896: return $reply_value;
1.927 albertel 11897: }
11898: }
11899:
1.691 raeburn 11900: sub check_group_parms {
11901: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11902: my @groupitems = ();
11903: my $resultitem;
1.927 albertel 11904: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11905: foreach my $group (@{$groups}) {
11906: foreach my $level (@levels) {
1.927 albertel 11907: my $item = $courseid.'.['.$group.'].'.$level->[0];
11908: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11909: }
11910: }
11911: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11912: $env{'course.'.$courseid.'.domain'},
11913: 'course',@groupitems);
11914: return $coursereply;
11915: }
11916:
11917: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11918: my ($courseid,@groups) = @_;
11919: @groups = sort(@groups);
1.691 raeburn 11920: return @groups;
11921: }
11922:
1.395 albertel 11923: sub packages_tab_default {
11924: my ($uri,$varname)=@_;
11925: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11926:
11927: my (@extension,@specifics,$do_default);
11928: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11929: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11930: if ($pack_type eq 'default') {
11931: $do_default=1;
11932: } elsif ($pack_type eq 'extension') {
11933: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11934: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11935: # only look at packages defaults for packages that this id is
1.738 albertel 11936: push(@specifics,[$package,$pack_type,$pack_part]);
11937: }
11938: }
11939: # first look for a package that matches the requested part id
11940: foreach my $package (@specifics) {
11941: my (undef,$pack_type,$pack_part)=@{$package};
11942: next if ($pack_part ne $part);
11943: if (defined($packagetab{"$pack_type&$name&default"})) {
11944: return $packagetab{"$pack_type&$name&default"};
11945: }
11946: }
11947: # look for any possible matching non extension_ package
11948: foreach my $package (@specifics) {
11949: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11950: if (defined($packagetab{"$pack_type&$name&default"})) {
11951: return $packagetab{"$pack_type&$name&default"};
11952: }
1.585 albertel 11953: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11954: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11955: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11956: }
11957: }
1.738 albertel 11958: # look for any posible extension_ match
11959: foreach my $package (@extension) {
11960: my ($package,$pack_type)=@{$package};
11961: if (defined($packagetab{"$pack_type&$name&default"})) {
11962: return $packagetab{"$pack_type&$name&default"};
11963: }
11964: if (defined($packagetab{$package."&$name&default"})) {
11965: return $packagetab{$package."&$name&default"};
11966: }
11967: }
11968: # look for a global default setting
11969: if ($do_default && defined($packagetab{"default&$name&default"})) {
11970: return $packagetab{"default&$name&default"};
11971: }
1.395 albertel 11972: return undef;
11973: }
11974:
1.334 albertel 11975: sub add_prefix_and_part {
11976: my ($prefix,$part)=@_;
11977: my $keyroot;
11978: if (defined($prefix) && $prefix !~ /^__/) {
11979: # prefix that has a part already
11980: $keyroot=$prefix;
11981: } elsif (defined($prefix)) {
11982: # prefix that is missing a part
11983: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11984: } else {
11985: # no prefix at all
11986: if (defined($part)) { $keyroot='_'.$part; }
11987: }
11988: return $keyroot;
11989: }
11990:
1.71 www 11991: # ---------------------------------------------------------------- Get metadata
11992:
1.599 albertel 11993: my %metaentry;
1.1070 www 11994: my %importedpartids;
1.1172.2.99 raeburn 11995: my %importedrespids;
1.71 www 11996: sub metadata {
1.176 www 11997: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11998: $uri=&declutter($uri);
1.288 albertel 11999: # if it is a non metadata possible uri return quickly
1.529 albertel 12000: if (($uri eq '') ||
12001: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 12002: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 12003: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12004: return undef;
12005: }
1.1172.2.49 raeburn 12006: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12007: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12008: return undef;
1.288 albertel 12009: }
1.73 www 12010: my $filename=$uri;
12011: $uri=~s/\.meta$//;
1.172 www 12012: #
12013: # Is the metadata already cached?
1.177 www 12014: # Look at timestamp of caching
1.172 www 12015: # Everything is cached by the main uri, libraries are never directly cached
12016: #
1.428 albertel 12017: if (!defined($liburi)) {
1.599 albertel 12018: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12019: if (defined($cached)) { return $result->{':'.$what}; }
12020: }
12021: {
1.1069 www 12022: # Imported parts would go here
1.1172.2.99 raeburn 12023: my @origfiletagids=();
1.1069 www 12024: my $importedparts=0;
1.1172.2.99 raeburn 12025:
12026: # Imported responseids would go here
12027: my $importedresponses=0;
1.172 www 12028: #
12029: # Is this a recursive call for a library?
12030: #
1.599 albertel 12031: # if (! exists($metacache{$uri})) {
12032: # $metacache{$uri}={};
12033: # }
1.924 albertel 12034: my $cachetime = 60*60;
1.171 www 12035: if ($liburi) {
12036: $liburi=&declutter($liburi);
12037: $filename=$liburi;
1.401 bowersj2 12038: } else {
1.599 albertel 12039: &devalidate_cache_new('meta',$uri);
12040: undef(%metaentry);
1.401 bowersj2 12041: }
1.140 www 12042: my %metathesekeys=();
1.73 www 12043: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12044: my $metastring;
1.1140 www 12045: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12046: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12047: $metastring =
1.929 albertel 12048: &Apache::lonnet::ssi_body($which,
1.924 albertel 12049: ('grade_target' => 'meta'));
12050: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12051: } elsif (($uri !~ m -^(editupload)/-) &&
12052: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12053: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12054: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12055: $metastring=&getfile($file);
1.489 albertel 12056: }
1.208 albertel 12057: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12058: my $token;
1.140 www 12059: undef %metathesekeys;
1.71 www 12060: while ($token=$parser->get_token) {
1.339 albertel 12061: if ($token->[0] eq 'S') {
12062: if (defined($token->[2]->{'package'})) {
1.172 www 12063: #
12064: # This is a package - get package info
12065: #
1.339 albertel 12066: my $package=$token->[2]->{'package'};
12067: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12068: if (defined($token->[2]->{'id'})) {
12069: $keyroot.='_'.$token->[2]->{'id'};
12070: }
1.599 albertel 12071: if ($metaentry{':packages'}) {
12072: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12073: } else {
1.599 albertel 12074: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12075: }
1.736 albertel 12076: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12077: my $part=$keyroot;
12078: $part=~s/^\_//;
1.736 albertel 12079: if ($pack_entry=~/^\Q$package\E\&/ ||
12080: $pack_entry=~/^\Q$package\E_0\&/) {
12081: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12082: # ignore package.tab specified default values
12083: # here &package_tab_default() will fetch those
12084: if ($subp eq 'default') { next; }
1.736 albertel 12085: my $value=$packagetab{$pack_entry};
1.432 albertel 12086: my $unikey;
12087: if ($pack =~ /_0$/) {
12088: $unikey='parameter_0_'.$name;
12089: $part=0;
12090: } else {
12091: $unikey='parameter'.$keyroot.'_'.$name;
12092: }
1.339 albertel 12093: if ($subp eq 'display') {
12094: $value.=' [Part: '.$part.']';
12095: }
1.599 albertel 12096: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12097: $metathesekeys{$unikey}=1;
1.599 albertel 12098: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12099: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12100: }
1.599 albertel 12101: if (defined($metaentry{':'.$unikey.'.default'})) {
12102: $metaentry{':'.$unikey}=
12103: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12104: }
1.339 albertel 12105: }
12106: }
12107: } else {
1.172 www 12108: #
12109: # This is not a package - some other kind of start tag
1.339 albertel 12110: #
12111: my $entry=$token->[1];
1.1068 www 12112: my $unikey='';
1.175 www 12113:
1.339 albertel 12114: if ($entry eq 'import') {
1.175 www 12115: #
12116: # Importing a library here
1.339 albertel 12117: #
1.1067 www 12118: my $location=$parser->get_text('/import');
12119: my $dir=$filename;
12120: $dir=~s|[^/]*$||;
12121: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12122:
12123: my $importid=$token->[2]->{'id'};
1.1068 www 12124: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12125: #
12126: # Check metadata for imported file to
12127: # see if it contained response items
12128: #
12129: my %currmetaentry = %metaentry;
12130: my $libresponseorder = &metadata($location,'responseorder');
12131: my $origfile;
12132: if ($libresponseorder ne '') {
12133: if ($#origfiletagids<0) {
12134: undef(%importedrespids);
12135: undef(%importedpartids);
12136: }
12137: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12138: if (@{$importedrespids{$importid}} > 0) {
12139: $importedresponses = 1;
12140: # We need to get the original file and the imported file to get the response order correct
12141: # Load and inspect original file
12142: if ($#origfiletagids<0) {
12143: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12144: $origfile=&getfile($origfilelocation);
12145: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12146: }
12147: }
12148: }
12149: # Do not overwrite contents of %metaentry hash for resource itself with
12150: # hash populated for imported library file
12151: %metaentry = %currmetaentry;
12152: undef(%currmetaentry);
1.1068 www 12153: if ($importmode eq 'problem') {
1.1069 www 12154: # Import as problem/response
1.1068 www 12155: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12156: } elsif ($importmode eq 'part') {
12157: # Import as part(s)
1.1069 www 12158: $importedparts=1;
12159: # We need to get the original file and the imported file to get the part order correct
12160: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12161: # Load and inspect original file if we didn't do that already
12162: if ($#origfiletagids<0) {
12163: undef(%importedrespids);
12164: undef(%importedpartids);
12165: if ($origfile eq '') {
12166: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12167: $origfile=&getfile($origfilelocation);
12168: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12169: }
1.1070 www 12170: }
12171:
1.1069 www 12172: # Load and inspect imported file
12173: my $impfile=&getfile($location);
12174: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12175: if ($#impfilepartids>=0) {
12176: # This problem had parts
1.1070 www 12177: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12178: } else {
12179: # Importing by turning a single problem into a problem part
12180: # It gets the import-tags ID as part-ID
12181: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12182: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12183: }
1.1068 www 12184: } else {
12185: # Normal import
12186: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12187: if (defined($token->[2]->{'id'})) {
12188: $unikey.='_'.$token->[2]->{'id'};
12189: }
1.1067 www 12190: }
12191:
1.339 albertel 12192: if ($depthcount<20) {
1.736 albertel 12193: my $metadata =
12194: &metadata($uri,'keys', $location,$unikey,
12195: $depthcount+1);
12196: foreach my $meta (split(',',$metadata)) {
12197: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12198: $metathesekeys{$meta}=1;
1.339 albertel 12199: }
1.1068 www 12200:
12201: }
1.1067 www 12202: } else {
12203: #
12204: # Not importing, some other kind of non-package, non-library start tag
12205: #
12206: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12207: if (defined($token->[2]->{'id'})) {
12208: $unikey.='_'.$token->[2]->{'id'};
12209: }
1.339 albertel 12210: if (defined($token->[2]->{'name'})) {
12211: $unikey.='_'.$token->[2]->{'name'};
12212: }
12213: $metathesekeys{$unikey}=1;
1.736 albertel 12214: foreach my $param (@{$token->[3]}) {
12215: $metaentry{':'.$unikey.'.'.$param} =
12216: $token->[2]->{$param};
1.339 albertel 12217: }
12218: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12219: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12220: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12221: # only ws inside the tag, and not in default, so use default
12222: # as value
1.599 albertel 12223: $metaentry{':'.$unikey}=$default;
1.908 albertel 12224: } elsif ( $internaltext =~ /\S/ ) {
12225: # something interesting inside the tag
12226: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12227: } else {
1.908 albertel 12228: # no interesting values, don't set a default
1.339 albertel 12229: }
1.172 www 12230: # end of not-a-package not-a-library import
1.339 albertel 12231: }
1.172 www 12232: # end of not-a-package start tag
1.339 albertel 12233: }
1.172 www 12234: # the next is the end of "start tag"
1.339 albertel 12235: }
12236: }
1.483 albertel 12237: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12238: $extension = lc($extension);
12239: if ($extension eq 'htm') { $extension='html'; }
12240:
1.737 albertel 12241: foreach my $key (keys(%packagetab)) {
1.483 albertel 12242: #no specific packages #how's our extension
12243: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12244: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12245: \%metathesekeys);
12246: }
1.883 albertel 12247:
12248: if (!exists($metaentry{':packages'})
12249: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12250: foreach my $key (keys(%packagetab)) {
1.483 albertel 12251: #no specific packages well let's get default then
12252: if ($key!~/^default&/) { next; }
1.488 albertel 12253: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12254: \%metathesekeys);
12255: }
12256: }
1.338 www 12257: # are there custom rights to evaluate
1.599 albertel 12258: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12259:
1.338 www 12260: #
12261: # Importing a rights file here
1.339 albertel 12262: #
12263: unless ($depthcount) {
1.599 albertel 12264: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12265: my $dir=$filename;
12266: $dir=~s|[^/]*$||;
12267: $location=&filelocation($dir,$location);
1.736 albertel 12268: my $rights_metadata =
12269: &metadata($uri,'keys',$location,'_rights',
12270: $depthcount+1);
12271: foreach my $rights (split(',',$rights_metadata)) {
12272: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12273: $metathesekeys{$rights}=1;
1.339 albertel 12274: }
12275: }
12276: }
1.737 albertel 12277: # uniqifiy package listing
12278: my %seen;
12279: my @uniq_packages =
12280: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12281: $metaentry{':packages'} = join(',',@uniq_packages);
12282:
1.1172.2.99 raeburn 12283: if (($importedresponses) || ($importedparts)) {
12284: if ($importedparts) {
1.1070 www 12285: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12286: $metaentry{':partorder'}='';
12287: $metathesekeys{'partorder'}=1;
12288: }
12289: if ($importedresponses) {
12290: # We had imported responses and need to rebuild responseorder
12291: $metaentry{':responseorder'}='';
12292: $metathesekeys{'responseorder'}=1;
12293: }
12294: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12295: my $origid = $origfiletagids[$index+1];
12296: if ($origfiletagids[$index] eq 'part') {
12297: # Original part, part of the problem
12298: if ($importedparts) {
12299: $metaentry{':partorder'}.=','.$origid;
12300: }
12301: } elsif ($origfiletagids[$index] eq 'import') {
12302: if ($importedparts) {
12303: # We have imported parts at this position
12304: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12305: }
12306: if ($importedresponses) {
12307: # We have imported responses at this position
12308: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12309: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12310: }
12311: }
12312: } else {
12313: # Original response item, part of the problem
12314: if ($importedresponses) {
12315: $metaentry{':responseorder'}.=','.$origid;
12316: }
12317: }
12318: }
12319: if ($importedparts) {
12320: $metaentry{':partorder'}=~s/^\,//;
12321: }
12322: if ($importedresponses) {
12323: $metaentry{':responseorder'}=~s/^\,//;
12324: }
1.1070 www 12325: }
12326:
1.737 albertel 12327: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12328: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12329: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12330: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12331: # this is the end of "was not already recently cached
1.71 www 12332: }
1.599 albertel 12333: return $metaentry{':'.$what};
1.261 albertel 12334: }
12335:
1.488 albertel 12336: sub metadata_create_package_def {
1.483 albertel 12337: my ($uri,$key,$package,$metathesekeys)=@_;
12338: my ($pack,$name,$subp)=split(/\&/,$key);
12339: if ($subp eq 'default') { next; }
12340:
1.599 albertel 12341: if (defined($metaentry{':packages'})) {
12342: $metaentry{':packages'}.=','.$package;
1.483 albertel 12343: } else {
1.599 albertel 12344: $metaentry{':packages'}=$package;
1.483 albertel 12345: }
12346: my $value=$packagetab{$key};
12347: my $unikey;
12348: $unikey='parameter_0_'.$name;
1.599 albertel 12349: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12350: $$metathesekeys{$unikey}=1;
1.599 albertel 12351: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12352: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12353: }
1.599 albertel 12354: if (defined($metaentry{':'.$unikey.'.default'})) {
12355: $metaentry{':'.$unikey}=
12356: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12357: }
12358: }
12359:
1.261 albertel 12360: sub metadata_generate_part0 {
12361: my ($metadata,$metacache,$uri) = @_;
12362: my %allnames;
1.737 albertel 12363: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12364: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12365: my $part=$$metacache{':'.$metakey.'.part'};
12366: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12367: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12368: $allnames{$name}=$part;
12369: }
12370: }
12371: }
12372: foreach my $name (keys(%allnames)) {
12373: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12374: my $key=":parameter_0_$name";
1.261 albertel 12375: $$metacache{"$key.part"}='0';
12376: $$metacache{"$key.name"}=$name;
1.428 albertel 12377: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12378: $allnames{$name}.'_'.$name.
12379: '.type'};
1.428 albertel 12380: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12381: '.display'};
1.644 www 12382: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12383: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12384: $$metacache{"$key.display"}=$olddis;
12385: }
1.71 www 12386: }
12387:
1.764 albertel 12388: # ------------------------------------------------------ Devalidate title cache
12389:
12390: sub devalidate_title_cache {
12391: my ($url)=@_;
12392: if (!$env{'request.course.id'}) { return; }
12393: my $symb=&symbread($url);
12394: if (!$symb) { return; }
12395: my $key=$env{'request.course.id'}."\0".$symb;
12396: &devalidate_cache_new('title',$key);
12397: }
12398:
1.1014 droeschl 12399: # ------------------------------------------------- Get the title of a course
12400:
12401: sub current_course_title {
12402: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12403: }
1.301 www 12404: # ------------------------------------------------- Get the title of a resource
12405:
12406: sub gettitle {
12407: my $urlsymb=shift;
12408: my $symb=&symbread($urlsymb);
1.534 albertel 12409: if ($symb) {
1.620 albertel 12410: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12411: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12412: if (defined($cached)) {
12413: return $result;
12414: }
1.534 albertel 12415: my ($map,$resid,$url)=&decode_symb($symb);
12416: my $title='';
1.907 albertel 12417: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12418: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12419: } else {
12420: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12421: &GDBM_READER(),0640)) {
12422: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12423: $title=$bighash{'title_'.$mapid.'.'.$resid};
12424: untie(%bighash);
12425: }
1.534 albertel 12426: }
12427: $title=~s/\&colon\;/\:/gs;
12428: if ($title) {
1.1159 www 12429: # Remember both $symb and $title for dynamic metadata
12430: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12431: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12432: # Cache this title and then return it
1.599 albertel 12433: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12434: }
12435: $urlsymb=$url;
12436: }
12437: my $title=&metadata($urlsymb,'title');
12438: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12439: return $title;
1.301 www 12440: }
1.613 albertel 12441:
1.614 albertel 12442: sub get_slot {
12443: my ($which,$cnum,$cdom)=@_;
12444: if (!$cnum || !$cdom) {
1.790 albertel 12445: (undef,my $courseid)=&whichuser();
1.620 albertel 12446: $cdom=$env{'course.'.$courseid.'.domain'};
12447: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12448: }
1.703 albertel 12449: my $key=join("\0",'slots',$cdom,$cnum,$which);
12450: my %slotinfo;
12451: if (exists($remembered{$key})) {
12452: $slotinfo{$which} = $remembered{$key};
12453: } else {
12454: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12455: &Apache::lonhomework::showhash(%slotinfo);
12456: my ($tmp)=keys(%slotinfo);
12457: if ($tmp=~/^error:/) { return (); }
12458: $remembered{$key} = $slotinfo{$which};
12459: }
1.616 albertel 12460: if (ref($slotinfo{$which}) eq 'HASH') {
12461: return %{$slotinfo{$which}};
12462: }
12463: return $slotinfo{$which};
1.614 albertel 12464: }
1.1150 raeburn 12465:
12466: sub get_reservable_slots {
12467: my ($cnum,$cdom,$uname,$udom) = @_;
12468: my $now = time;
12469: my $reservable_info;
12470: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12471: if (exists($remembered{$key})) {
12472: $reservable_info = $remembered{$key};
12473: } else {
12474: my %resv;
12475: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12476: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12477: $reservable_info = \%resv;
12478: $remembered{$key} = $reservable_info;
12479: }
12480: return $reservable_info;
12481: }
12482:
12483: sub get_course_slots {
12484: my ($cnum,$cdom) = @_;
12485: my $hashid=$cnum.':'.$cdom;
12486: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12487: if (defined($cached)) {
12488: if (ref($result) eq 'HASH') {
12489: return %{$result};
12490: }
12491: } else {
12492: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12493: my ($tmp) = keys(%slots);
12494: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12495: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12496: return %slots;
12497: }
12498: }
12499: return;
12500: }
12501:
12502: sub devalidate_slots_cache {
12503: my ($cnum,$cdom)=@_;
12504: my $hashid=$cnum.':'.$cdom;
12505: &devalidate_cache_new('allslots',$hashid);
12506: }
12507:
1.1172.2.8 raeburn 12508: sub get_coursechange {
12509: my ($cdom,$cnum) = @_;
12510: if ($cdom eq '' || $cnum eq '') {
12511: return unless ($env{'request.course.id'});
12512: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12513: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12514: }
12515: my $hashid=$cdom.'_'.$cnum;
12516: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12517: if ((defined($cached)) && ($change ne '')) {
12518: return $change;
12519: } else {
12520: my %crshash;
12521: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12522: if ($crshash{'internal.contentchange'} eq '') {
12523: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12524: if ($change eq '') {
12525: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12526: $change = $crshash{'internal.created'};
12527: }
12528: } else {
12529: $change = $crshash{'internal.contentchange'};
12530: }
12531: my $cachetime = 600;
12532: &do_cache_new('crschange',$hashid,$change,$cachetime);
12533: }
12534: return $change;
12535: }
12536:
12537: sub devalidate_coursechange_cache {
12538: my ($cnum,$cdom)=@_;
12539: my $hashid=$cnum.':'.$cdom;
12540: &devalidate_cache_new('crschange',$hashid);
12541: }
12542:
1.31 www 12543: # ------------------------------------------------- Update symbolic store links
12544:
12545: sub symblist {
12546: my ($mapname,%newhash)=@_;
1.438 www 12547: $mapname=&deversion(&declutter($mapname));
1.31 www 12548: my %hash;
1.620 albertel 12549: if (($env{'request.course.fn'}) && (%newhash)) {
12550: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12551: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12552: foreach my $url (keys(%newhash)) {
1.711 albertel 12553: next if ($url eq 'last_known'
12554: && $env{'form.no_update_last_known'});
12555: $hash{declutter($url)}=&encode_symb($mapname,
12556: $newhash{$url}->[1],
12557: $newhash{$url}->[0]);
1.191 harris41 12558: }
1.31 www 12559: if (untie(%hash)) {
12560: return 'ok';
12561: }
12562: }
12563: }
12564: return 'error';
1.212 www 12565: }
12566:
12567: # --------------------------------------------------------------- Verify a symb
12568:
12569: sub symbverify {
1.1172.2.11 raeburn 12570: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12571: my $thisfn=$thisurl;
1.439 www 12572: $thisfn=&declutter($thisfn);
1.215 www 12573: # direct jump to resource in page or to a sequence - will construct own symbs
12574: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12575: # check URL part
1.409 www 12576: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12577:
1.431 www 12578: unless ($url eq $thisfn) { return 0; }
1.213 www 12579:
1.216 www 12580: $symb=&symbclean($symb);
1.510 www 12581: $thisurl=&deversion($thisurl);
1.439 www 12582: $thisfn=&deversion($thisfn);
1.213 www 12583:
12584: my %bighash;
12585: my $okay=0;
1.431 www 12586:
1.620 albertel 12587: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12588: &GDBM_READER(),0640)) {
1.1032 raeburn 12589: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12590: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12591: if ($map =~ m{^uploaded/.+\.page$}) {
12592: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12593: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12594: }
12595: }
12596: my $ids;
1.1172.2.122 raeburn 12597: if ($map =~ m{^uploaded/.+\.page$}) {
12598: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12599: } else {
12600: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12601: }
1.1102 raeburn 12602: unless ($ids) {
1.1172.2.13 raeburn 12603: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12604: $ids=$bighash{$idkey};
1.216 www 12605: }
12606: if ($ids) {
12607: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12608: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12609: $symb =~ s/\?.+$//;
12610: }
1.800 albertel 12611: foreach my $id (split(/\,/,$ids)) {
12612: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12613: if (
12614: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12615: eq $symb) {
1.1172.2.11 raeburn 12616: if (ref($encstate)) {
12617: $$encstate = $bighash{'encrypted_'.$id};
12618: }
1.1172.2.13 raeburn 12619: if (($env{'request.role.adv'}) ||
12620: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12621: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12622: $okay=1;
12623: last;
12624: }
12625: }
12626: }
1.216 www 12627: }
1.213 www 12628: untie(%bighash);
12629: }
12630: return $okay;
1.31 www 12631: }
12632:
1.210 www 12633: # --------------------------------------------------------------- Clean-up symb
12634:
12635: sub symbclean {
12636: my $symb=shift;
1.568 albertel 12637: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12638: # remove version from map
12639: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12640:
1.210 www 12641: # remove version from URL
12642: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12643:
1.507 www 12644: # remove wrapper
12645:
1.510 www 12646: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12647: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12648: return $symb;
1.409 www 12649: }
12650:
12651: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12652:
12653: sub encode_symb {
12654: my ($map,$resid,$url)=@_;
12655: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12656: }
1.409 www 12657:
12658: sub decode_symb {
1.568 albertel 12659: my $symb=shift;
12660: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12661: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12662: return (&fixversion($map),$resid,&fixversion($url));
12663: }
12664:
12665: sub fixversion {
12666: my $fn=shift;
1.609 banghart 12667: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12668: my %bighash;
12669: my $uri=&clutter($fn);
1.620 albertel 12670: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12671: # is this cached?
1.599 albertel 12672: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12673: if (defined($cached)) { return $result; }
12674: # unfortunately not cached, or expired
1.620 albertel 12675: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12676: &GDBM_READER(),0640)) {
12677: if ($bighash{'version_'.$uri}) {
12678: my $version=$bighash{'version_'.$uri};
1.444 www 12679: unless (($version eq 'mostrecent') ||
12680: ($version==&getversion($uri))) {
1.440 www 12681: $uri=~s/\.(\w+)$/\.$version\.$1/;
12682: }
12683: }
12684: untie %bighash;
1.413 www 12685: }
1.599 albertel 12686: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12687: }
12688:
12689: sub deversion {
12690: my $url=shift;
12691: $url=~s/\.\d+\.(\w+)$/\.$1/;
12692: return $url;
1.210 www 12693: }
12694:
1.31 www 12695: # ------------------------------------------------------ Return symb list entry
12696:
12697: sub symbread {
1.1172.2.126 raeburn 12698: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12699: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12700: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12701: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12702: unless (ref($possibles) eq 'HASH') {
12703: if ($ignorecachednull) {
12704: return $env{$cache_str} unless ($env{$cache_str} eq '');
12705: } else {
12706: return $env{$cache_str};
12707: }
1.1172.2.66 raeburn 12708: }
12709: }
1.242 www 12710: # no filename provided? try from environment
1.1172.2.54 raeburn 12711: unless ($thisfn) {
1.620 albertel 12712: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12713: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12714: }
12715: $thisfn=$env{'request.filename'};
1.44 www 12716: }
1.569 albertel 12717: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12718: # is that filename actually a symb? Verify, clean, and return
12719: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12720: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12721: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12722: }
1.242 www 12723: }
1.44 www 12724: $thisfn=declutter($thisfn);
1.31 www 12725: my %hash;
1.37 www 12726: my %bighash;
12727: my $syval='';
1.620 albertel 12728: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128 raeburn 12729: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12730: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12731: &GDBM_READER(),0640)) {
1.1172.2.150 raeburn 12732: $syval=$hash{$thisfn};
1.1172.2.126 raeburn 12733: untie(%hash);
12734: }
1.1172.2.128 raeburn 12735: if ($syval && $checkforblock) {
12736: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12737: if (@blockers) {
12738: $syval='';
12739: }
12740: }
1.37 www 12741: }
12742: # ---------------------------------------------------------- There was an entry
12743: if ($syval) {
1.601 albertel 12744: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12745: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12746: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12747: #return $env{$cache_str}='';
1.601 albertel 12748: #}
12749: #$syval.=$1;
12750: #}
1.37 www 12751: } else {
12752: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12753: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12754: &GDBM_READER(),0640)) {
1.37 www 12755: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12756: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12757: unless ($ids) {
12758: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12759: }
12760: unless ($ids) {
12761: # alias?
12762: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12763: }
1.37 www 12764: if ($ids) {
12765: # ------------------------------------------------------------------- Has ID(s)
12766: my @possibilities=split(/\,/,$ids);
1.39 www 12767: if ($#possibilities==0) {
12768: # ----------------------------------------------- There is only one possibility
1.37 www 12769: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12770: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12771: $resid,$thisfn);
1.1172.2.66 raeburn 12772: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12773: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12774: $possibles->{$syval} = 1;
12775: }
1.1172.2.66 raeburn 12776: }
12777: if ($checkforblock) {
1.1172.2.126 raeburn 12778: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12779: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12780: if (@blockers) {
12781: $syval = '';
12782: untie(%bighash);
12783: return $env{$cache_str}='';
12784: }
1.1172.2.66 raeburn 12785: }
12786: }
12787: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12788: # ------------------------------------------ There is more than one possibility
12789: my $realpossible=0;
1.800 albertel 12790: foreach my $id (@possibilities) {
12791: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12792: my $canaccess;
12793: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12794: $canaccess = 1;
12795: } else {
12796: $canaccess = &allowed('bre',$file);
12797: }
12798: if ($canaccess) {
12799: my ($mapid,$resid)=split(/\./,$id);
12800: if ($bighash{'map_type_'.$mapid} ne 'page') {
12801: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12802: $resid,$thisfn);
1.1172.2.126 raeburn 12803: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12804: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12805: if ($checkforblock) {
1.1172.2.127 raeburn 12806: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12807: if (@blockers > 0) {
12808: $syval = '';
12809: } else {
1.1172.2.66 raeburn 12810: $syval = $poss_syval;
12811: $realpossible++;
12812: }
12813: } else {
12814: $syval = $poss_syval;
12815: $realpossible++;
12816: }
1.1172.2.126 raeburn 12817: if ($syval) {
12818: if (ref($possibles) eq 'HASH') {
12819: $possibles->{$syval} = 1;
12820: }
12821: }
1.1172.2.66 raeburn 12822: }
1.39 www 12823: }
1.191 harris41 12824: }
1.39 www 12825: if ($realpossible!=1) { $syval=''; }
1.249 www 12826: } else {
12827: $syval='';
1.37 www 12828: }
12829: }
1.1172.2.66 raeburn 12830: untie(%bighash);
1.481 raeburn 12831: }
1.31 www 12832: }
1.62 www 12833: if ($syval) {
1.1172.2.128 raeburn 12834: return $env{$cache_str}=$syval;
1.62 www 12835: }
1.31 www 12836: }
1.949 raeburn 12837: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12838: return $env{$cache_str}='';
1.31 www 12839: }
12840:
12841: # ---------------------------------------------------------- Return random seed
12842:
1.32 www 12843: sub numval {
12844: my $txt=shift;
12845: $txt=~tr/A-J/0-9/;
12846: $txt=~tr/a-j/0-9/;
12847: $txt=~tr/K-T/0-9/;
12848: $txt=~tr/k-t/0-9/;
12849: $txt=~tr/U-Z/0-5/;
12850: $txt=~tr/u-z/0-5/;
12851: $txt=~s/\D//g;
1.564 albertel 12852: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12853: return int($txt);
1.368 albertel 12854: }
12855:
1.484 albertel 12856: sub numval2 {
12857: my $txt=shift;
12858: $txt=~tr/A-J/0-9/;
12859: $txt=~tr/a-j/0-9/;
12860: $txt=~tr/K-T/0-9/;
12861: $txt=~tr/k-t/0-9/;
12862: $txt=~tr/U-Z/0-5/;
12863: $txt=~tr/u-z/0-5/;
12864: $txt=~s/\D//g;
12865: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12866: my $total;
12867: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12868: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12869: return int($total);
12870: }
12871:
1.575 albertel 12872: sub numval3 {
12873: use integer;
12874: my $txt=shift;
12875: $txt=~tr/A-J/0-9/;
12876: $txt=~tr/a-j/0-9/;
12877: $txt=~tr/K-T/0-9/;
12878: $txt=~tr/k-t/0-9/;
12879: $txt=~tr/U-Z/0-5/;
12880: $txt=~tr/u-z/0-5/;
12881: $txt=~s/\D//g;
12882: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12883: my $total;
12884: foreach my $val (@txts) { $total+=$val; }
12885: if ($_64bit) { $total=(($total<<32)>>32); }
12886: return $total;
12887: }
12888:
1.675 albertel 12889: sub digest {
12890: my ($data)=@_;
12891: my $digest=&Digest::MD5::md5($data);
12892: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12893: my ($e,$f);
12894: {
12895: use integer;
12896: $e=($a+$b);
12897: $f=($c+$d);
12898: if ($_64bit) {
12899: $e=(($e<<32)>>32);
12900: $f=(($f<<32)>>32);
12901: }
12902: }
12903: if (wantarray) {
12904: return ($e,$f);
12905: } else {
12906: my $g;
12907: {
12908: use integer;
12909: $g=($e+$f);
12910: if ($_64bit) {
12911: $g=(($g<<32)>>32);
12912: }
12913: }
12914: return $g;
12915: }
12916: }
12917:
1.368 albertel 12918: sub latest_rnd_algorithm_id {
1.675 albertel 12919: return '64bit5';
1.366 albertel 12920: }
1.32 www 12921:
1.503 albertel 12922: sub get_rand_alg {
12923: my ($courseid)=@_;
1.790 albertel 12924: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12925: if ($courseid) {
1.620 albertel 12926: return $env{"course.$courseid.rndseed"};
1.503 albertel 12927: }
12928: return &latest_rnd_algorithm_id();
12929: }
12930:
1.562 albertel 12931: sub validCODE {
12932: my ($CODE)=@_;
12933: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12934: return 0;
12935: }
12936:
1.491 albertel 12937: sub getCODE {
1.620 albertel 12938: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12939: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12940: defined($Apache::lonhomework::parsing_a_task) ) &&
12941: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12942: return $Apache::lonhomework::history{'resource.CODE'};
12943: }
12944: return undef;
12945: }
1.1133 foxr 12946: #
12947: # Determines the random seed for a specific context:
12948: #
12949: # parameters:
12950: # symb - in course context the symb for the seed.
12951: # course_id - The course id of the form domain_coursenum.
12952: # domain - Domain for the user.
12953: # course - Course for the user.
12954: # cenv - environment of the course.
12955: #
12956: # NOTE:
12957: # All parameters are picked out of the environment if missing
12958: # or not defined.
12959: # If a symb cannot be determined the current time is used instead.
12960: #
12961: # For a given well defined symb, courside, domain, username,
12962: # and course environment, the seed is reproducible.
12963: #
1.31 www 12964: sub rndseed {
1.1133 foxr 12965: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12966: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12967: if (!defined($symb)) {
1.366 albertel 12968: unless ($symb=$wsymb) { return time; }
12969: }
1.1146 foxr 12970: if (!defined $courseid) {
12971: $courseid=$wcourseid;
12972: }
12973: if (!defined $domain) { $domain=$wdomain; }
12974: if (!defined $username) { $username=$wusername }
1.1133 foxr 12975:
12976: my $which;
12977: if (defined($cenv->{'rndseed'})) {
12978: $which = $cenv->{'rndseed'};
12979: } else {
12980: $which =&get_rand_alg($courseid);
12981: }
1.491 albertel 12982: if (defined(&getCODE())) {
1.675 albertel 12983: if ($which eq '64bit5') {
12984: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12985: } elsif ($which eq '64bit4') {
1.575 albertel 12986: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12987: } else {
12988: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12989: }
1.675 albertel 12990: } elsif ($which eq '64bit5') {
12991: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12992: } elsif ($which eq '64bit4') {
12993: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12994: } elsif ($which eq '64bit3') {
12995: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12996: } elsif ($which eq '64bit2') {
12997: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12998: } elsif ($which eq '64bit') {
12999: return &rndseed_64bit($symb,$courseid,$domain,$username);
13000: }
13001: return &rndseed_32bit($symb,$courseid,$domain,$username);
13002: }
13003:
13004: sub rndseed_32bit {
13005: my ($symb,$courseid,$domain,$username)=@_;
13006: {
13007: use integer;
13008: my $symbchck=unpack("%32C*",$symb) << 27;
13009: my $symbseed=numval($symb) << 22;
13010: my $namechck=unpack("%32C*",$username) << 17;
13011: my $nameseed=numval($username) << 12;
13012: my $domainseed=unpack("%32C*",$domain) << 7;
13013: my $courseseed=unpack("%32C*",$courseid);
13014: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13015: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13016: #&logthis("rndseed :$num:$symb");
1.564 albertel 13017: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13018: return $num;
13019: }
13020: }
13021:
13022: sub rndseed_64bit {
13023: my ($symb,$courseid,$domain,$username)=@_;
13024: {
13025: use integer;
13026: my $symbchck=unpack("%32S*",$symb) << 21;
13027: my $symbseed=numval($symb) << 10;
13028: my $namechck=unpack("%32S*",$username);
13029:
13030: my $nameseed=numval($username) << 21;
13031: my $domainseed=unpack("%32S*",$domain) << 10;
13032: my $courseseed=unpack("%32S*",$courseid);
13033:
13034: my $num1=$symbchck+$symbseed+$namechck;
13035: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13036: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13037: #&logthis("rndseed :$num:$symb");
1.564 albertel 13038: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13039: return "$num1,$num2";
1.155 albertel 13040: }
1.366 albertel 13041: }
13042:
1.443 albertel 13043: sub rndseed_64bit2 {
13044: my ($symb,$courseid,$domain,$username)=@_;
13045: {
13046: use integer;
13047: # strings need to be an even # of cahracters long, it it is odd the
13048: # last characters gets thrown away
13049: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13050: my $symbseed=numval($symb) << 10;
13051: my $namechck=unpack("%32S*",$username.' ');
13052:
13053: my $nameseed=numval($username) << 21;
1.501 albertel 13054: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13055: my $courseseed=unpack("%32S*",$courseid.' ');
13056:
13057: my $num1=$symbchck+$symbseed+$namechck;
13058: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13059: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13060: #&logthis("rndseed :$num:$symb");
1.803 albertel 13061: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13062: return "$num1,$num2";
13063: }
13064: }
13065:
13066: sub rndseed_64bit3 {
13067: my ($symb,$courseid,$domain,$username)=@_;
13068: {
13069: use integer;
13070: # strings need to be an even # of cahracters long, it it is odd the
13071: # last characters gets thrown away
13072: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13073: my $symbseed=numval2($symb) << 10;
13074: my $namechck=unpack("%32S*",$username.' ');
13075:
13076: my $nameseed=numval2($username) << 21;
1.443 albertel 13077: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13078: my $courseseed=unpack("%32S*",$courseid.' ');
13079:
13080: my $num1=$symbchck+$symbseed+$namechck;
13081: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13082: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13083: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13084: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13085:
1.503 albertel 13086: return "$num1:$num2";
1.443 albertel 13087: }
13088: }
13089:
1.575 albertel 13090: sub rndseed_64bit4 {
13091: my ($symb,$courseid,$domain,$username)=@_;
13092: {
13093: use integer;
13094: # strings need to be an even # of cahracters long, it it is odd the
13095: # last characters gets thrown away
13096: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13097: my $symbseed=numval3($symb) << 10;
13098: my $namechck=unpack("%32S*",$username.' ');
13099:
13100: my $nameseed=numval3($username) << 21;
13101: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13102: my $courseseed=unpack("%32S*",$courseid.' ');
13103:
13104: my $num1=$symbchck+$symbseed+$namechck;
13105: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13106: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13107: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13108: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13109:
1.575 albertel 13110: return "$num1:$num2";
13111: }
13112: }
13113:
1.675 albertel 13114: sub rndseed_64bit5 {
13115: my ($symb,$courseid,$domain,$username)=@_;
13116: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13117: return "$num1:$num2";
13118: }
13119:
1.366 albertel 13120: sub rndseed_CODE_64bit {
13121: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13122: {
1.366 albertel 13123: use integer;
1.443 albertel 13124: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13125: my $symbseed=numval2($symb);
1.491 albertel 13126: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13127: my $CODEseed=numval(&getCODE());
1.443 albertel 13128: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13129: my $num1=$symbseed+$CODEchck;
13130: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13131: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13132: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13133: if ($_64bit) { $num1=(($num1<<32)>>32); }
13134: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13135: return "$num1:$num2";
1.366 albertel 13136: }
13137: }
13138:
1.575 albertel 13139: sub rndseed_CODE_64bit4 {
13140: my ($symb,$courseid,$domain,$username)=@_;
13141: {
13142: use integer;
13143: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13144: my $symbseed=numval3($symb);
13145: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13146: my $CODEseed=numval3(&getCODE());
13147: my $courseseed=unpack("%32S*",$courseid.' ');
13148: my $num1=$symbseed+$CODEchck;
13149: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13150: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13151: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13152: if ($_64bit) { $num1=(($num1<<32)>>32); }
13153: if ($_64bit) { $num2=(($num2<<32)>>32); }
13154: return "$num1:$num2";
13155: }
13156: }
13157:
1.675 albertel 13158: sub rndseed_CODE_64bit5 {
13159: my ($symb,$courseid,$domain,$username)=@_;
13160: my $code = &getCODE();
13161: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13162: return "$num1:$num2";
13163: }
13164:
1.366 albertel 13165: sub setup_random_from_rndseed {
13166: my ($rndseed)=@_;
1.503 albertel 13167: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13168: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13169: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13170: &Math::Random::random_set_seed_from_phrase($rndseed);
13171: } else {
13172: &Math::Random::random_set_seed($num1,$num2);
13173: }
1.366 albertel 13174: } else {
13175: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13176: }
1.36 albertel 13177: }
13178:
1.474 albertel 13179: sub latest_receipt_algorithm_id {
1.835 albertel 13180: return 'receipt3';
1.474 albertel 13181: }
13182:
1.480 www 13183: sub recunique {
13184: my $fucourseid=shift;
13185: my $unique;
1.835 albertel 13186: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13187: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13188: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13189: } else {
13190: $unique=$perlvar{'lonReceipt'};
13191: }
13192: return unpack("%32C*",$unique);
13193: }
13194:
13195: sub recprefix {
13196: my $fucourseid=shift;
13197: my $prefix;
1.835 albertel 13198: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13199: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13200: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13201: } else {
13202: $prefix=$perlvar{'lonHostID'};
13203: }
13204: return unpack("%32C*",$prefix);
13205: }
13206:
1.76 www 13207: sub ireceipt {
1.474 albertel 13208: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13209:
13210: my $return =&recprefix($fucourseid).'-';
13211:
13212: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13213: $env{'request.state'} eq 'construct') {
13214: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13215: return $return;
13216: }
13217:
1.76 www 13218: my $cuname=unpack("%32C*",$funame);
13219: my $cudom=unpack("%32C*",$fudom);
13220: my $cucourseid=unpack("%32C*",$fucourseid);
13221: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13222: my $cunique=&recunique($fucourseid);
1.474 albertel 13223: my $cpart=unpack("%32S*",$part);
1.835 albertel 13224: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13225:
1.790 albertel 13226: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13227:
13228: $return.= ($cunique%$cuname+
13229: $cunique%$cudom+
13230: $cusymb%$cuname+
13231: $cusymb%$cudom+
13232: $cucourseid%$cuname+
13233: $cucourseid%$cudom+
13234: $cpart%$cuname+
13235: $cpart%$cudom);
13236: } else {
13237: $return.= ($cunique%$cuname+
13238: $cunique%$cudom+
13239: $cusymb%$cuname+
13240: $cusymb%$cudom+
13241: $cucourseid%$cuname+
13242: $cucourseid%$cudom);
13243: }
13244: return $return;
1.76 www 13245: }
13246:
13247: sub receipt {
1.474 albertel 13248: my ($part)=@_;
1.790 albertel 13249: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13250: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13251: }
1.260 ng 13252:
1.790 albertel 13253: sub whichuser {
13254: my ($passedsymb)=@_;
13255: my ($symb,$courseid,$domain,$name,$publicuser);
13256: if (defined($env{'form.grade_symb'})) {
13257: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13258: my $allowed=&allowed('vgr',$tmp_courseid);
13259: if (!$allowed &&
13260: exists($env{'request.course.sec'}) &&
13261: $env{'request.course.sec'} !~ /^\s*$/) {
13262: $allowed=&allowed('vgr',$tmp_courseid.
13263: '/'.$env{'request.course.sec'});
13264: }
13265: if ($allowed) {
13266: ($symb)=&get_env_multiple('form.grade_symb');
13267: $courseid=$tmp_courseid;
13268: ($domain)=&get_env_multiple('form.grade_domain');
13269: ($name)=&get_env_multiple('form.grade_username');
13270: return ($symb,$courseid,$domain,$name,$publicuser);
13271: }
13272: }
13273: if (!$passedsymb) {
13274: $symb=&symbread();
13275: } else {
13276: $symb=$passedsymb;
13277: }
13278: $courseid=$env{'request.course.id'};
13279: $domain=$env{'user.domain'};
13280: $name=$env{'user.name'};
13281: if ($name eq 'public' && $domain eq 'public') {
13282: if (!defined($env{'form.username'})) {
13283: $env{'form.username'}.=time.rand(10000000);
13284: }
13285: $name.=$env{'form.username'};
13286: }
13287: return ($symb,$courseid,$domain,$name,$publicuser);
13288:
13289: }
13290:
1.36 albertel 13291: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13292: # returns either the contents of the file or
13293: # -1 if the file doesn't exist
1.481 raeburn 13294: #
13295: # if the target is a file that was uploaded via DOCS,
13296: # a check will be made to see if a current copy exists on the local server,
13297: # if it does this will be served, otherwise a copy will be retrieved from
13298: # the home server for the course and stored in /home/httpd/html/userfiles on
13299: # the local server.
1.472 albertel 13300:
1.36 albertel 13301: sub getfile {
1.538 albertel 13302: my ($file) = @_;
1.609 banghart 13303: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13304: &repcopy($file);
13305: return &readfile($file);
13306: }
13307:
13308: sub repcopy_userfile {
13309: my ($file)=@_;
1.1142 raeburn 13310: my $londocroot = $perlvar{'lonDocRoot'};
13311: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13312: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13313: my ($cdom,$cnum,$filename) =
1.811 albertel 13314: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13315: my $uri="/uploaded/$cdom/$cnum/$filename";
13316: if (-e "$file") {
1.828 www 13317: # we already have a local copy, check it out
1.538 albertel 13318: my @fileinfo = stat($file);
1.828 www 13319: my $rtncode;
13320: my $info;
1.538 albertel 13321: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13322: if ($lwpresp ne 'ok') {
1.828 www 13323: # there is no such file anymore, even though we had a local copy
1.482 albertel 13324: if ($rtncode eq '404') {
1.538 albertel 13325: unlink($file);
1.482 albertel 13326: }
13327: return -1;
13328: }
13329: if ($info < $fileinfo[9]) {
1.828 www 13330: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13331: return 'ok';
1.828 www 13332: } else {
13333: # the file is outdated, get rid of it
13334: unlink($file);
1.482 albertel 13335: }
1.828 www 13336: }
13337: # one way or the other, at this point, we don't have the file
13338: # construct the correct path for the file
13339: my @parts = ($cdom,$cnum);
13340: if ($filename =~ m|^(.+)/[^/]+$|) {
13341: push @parts, split(/\//,$1);
13342: }
13343: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13344: foreach my $part (@parts) {
13345: $path .= '/'.$part;
13346: if (!-e $path) {
13347: mkdir($path,0770);
1.482 albertel 13348: }
13349: }
1.828 www 13350: # now the path exists for sure
13351: # get a user agent
13352: my $ua=new LWP::UserAgent;
13353: my $transferfile=$file.'.in.transfer';
13354: # FIXME: this should flock
13355: if (-e $transferfile) { return 'ok'; }
13356: my $request;
13357: $uri=~s/^\///;
1.980 raeburn 13358: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13359: my $hostname = &hostname($homeserver);
1.980 raeburn 13360: my $protocol = $protocol{$homeserver};
13361: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13362: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13363: my $response=$ua->request($request,$transferfile);
13364: # did it work?
13365: if ($response->is_error()) {
13366: unlink($transferfile);
13367: &logthis("Userfile repcopy failed for $uri");
13368: return -1;
13369: }
13370: # worked, rename the transfer file
13371: rename($transferfile,$file);
1.607 raeburn 13372: return 'ok';
1.481 raeburn 13373: }
13374:
1.517 albertel 13375: sub tokenwrapper {
13376: my $uri=shift;
1.980 raeburn 13377: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13378: $uri=~s|^/||;
1.620 albertel 13379: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13380: my $token=$1;
1.552 albertel 13381: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13382: if ($udom && $uname && $file) {
13383: $file=~s|(\?\.*)*$||;
1.949 raeburn 13384: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13385: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13386: my $hostname = &hostname($homeserver);
1.980 raeburn 13387: my $protocol = $protocol{$homeserver};
13388: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13389: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13390: (($uri=~/\?/)?'&':'?').'token='.$token.
13391: '&tokenissued='.$perlvar{'lonHostID'};
13392: } else {
13393: return '/adm/notfound.html';
13394: }
13395: }
13396:
1.828 www 13397: # call with reqtype HEAD: get last modification time
13398: # call with reqtype GET: get the file contents
13399: # Do not call this with reqtype GET for large files! It loads everything into memory
13400: #
1.481 raeburn 13401: sub getuploaded {
13402: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13403: $uri=~s/^\///;
1.980 raeburn 13404: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13405: my $hostname = &hostname($homeserver);
1.980 raeburn 13406: my $protocol = $protocol{$homeserver};
13407: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13408: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13409: my $ua=new LWP::UserAgent;
13410: my $request=new HTTP::Request($reqtype,$uri);
13411: my $response=$ua->request($request);
13412: $$rtncode = $response->code;
1.482 albertel 13413: if (! $response->is_success()) {
13414: return 'failed';
13415: }
13416: if ($reqtype eq 'HEAD') {
1.486 www 13417: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13418: } elsif ($reqtype eq 'GET') {
13419: $$info = $response->content;
1.472 albertel 13420: }
1.482 albertel 13421: return 'ok';
1.36 albertel 13422: }
13423:
1.481 raeburn 13424: sub readfile {
13425: my $file = shift;
13426: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13427: my $fh;
1.1172.2.96 raeburn 13428: open($fh,"<",$file);
1.481 raeburn 13429: my $a='';
1.800 albertel 13430: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13431: return $a;
13432: }
13433:
1.36 albertel 13434: sub filelocation {
1.590 banghart 13435: my ($dir,$file) = @_;
13436: my $location;
13437: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13438:
13439: if ($file =~ m-^/adm/-) {
13440: $file=~s-^/adm/wrapper/-/-;
13441: $file=~s-^/adm/coursedocs/showdoc/-/-;
13442: }
1.882 albertel 13443:
1.1139 www 13444: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13445: $location = $file;
1.609 banghart 13446: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13447: my ($udom,$uname,$filename)=
1.811 albertel 13448: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13449: my $home=&homeserver($uname,$udom);
13450: my $is_me=0;
13451: my @ids=¤t_machine_ids();
13452: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13453: if ($is_me) {
1.1117 foxr 13454: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13455: } else {
13456: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13457: $udom.'/'.$uname.'/'.$filename;
13458: }
1.882 albertel 13459: } elsif ($file =~ m-^/adm/-) {
13460: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13461: } else {
13462: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13463: $file=~s:^/(res|priv)/:/:;
13464: my $space=$1;
1.590 banghart 13465: if ( !( $file =~ m:^/:) ) {
13466: $location = $dir. '/'.$file;
13467: } else {
1.1142 raeburn 13468: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13469: }
1.59 albertel 13470: }
1.590 banghart 13471: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13472: while ($location=~m{/\.\./}) {
13473: if ($location =~ m{/[^/]+/\.\./}) {
13474: $location=~ s{/[^/]+/\.\./}{/}g;
13475: } else {
13476: $location=~ s{/\.\./}{/}g;
13477: }
13478: } #remove dir/..
1.590 banghart 13479: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13480: return $location;
1.46 www 13481: }
1.36 albertel 13482:
1.46 www 13483: sub hreflocation {
13484: my ($dir,$file)=@_;
1.980 raeburn 13485: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13486: $file=filelocation($dir,$file);
1.700 albertel 13487: } elsif ($file=~m-^/adm/-) {
13488: $file=~s-^/adm/wrapper/-/-;
13489: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13490: }
13491: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13492: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13493: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13494: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13495: {/uploaded/$1/$2/}x;
1.46 www 13496: }
1.913 albertel 13497: if ($file=~ m{^/userfiles/}) {
13498: $file =~ s{^/userfiles/}{/uploaded/};
13499: }
1.462 albertel 13500: return $file;
1.465 albertel 13501: }
13502:
1.1139 www 13503:
13504:
13505:
13506:
1.465 albertel 13507: sub current_machine_domains {
1.853 albertel 13508: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13509: }
13510:
13511: sub machine_domains {
13512: my ($hostname) = @_;
1.465 albertel 13513: my @domains;
1.838 albertel 13514: my %hostname = &all_hostnames();
1.465 albertel 13515: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13516: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13517: if ($hostname eq $name) {
1.844 albertel 13518: push(@domains,&host_domain($id));
1.465 albertel 13519: }
13520: }
13521: return @domains;
13522: }
13523:
13524: sub current_machine_ids {
1.853 albertel 13525: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13526: }
13527:
13528: sub machine_ids {
13529: my ($hostname) = @_;
13530: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13531: my @ids;
1.888 albertel 13532: my %name_to_host = &all_names();
1.889 albertel 13533: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13534: return @{ $name_to_host{$hostname} };
13535: }
13536: return;
1.31 www 13537: }
13538:
1.824 raeburn 13539: sub additional_machine_domains {
13540: my @domains;
1.1172.2.142 raeburn 13541: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13542: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13543: while( my $line = <$fh>) {
13544: chomp($line);
13545: $line =~ s/\s//g;
13546: push(@domains,$line);
13547: }
13548: close($fh);
13549: }
1.824 raeburn 13550: }
13551: return @domains;
13552: }
13553:
13554: sub default_login_domain {
13555: my $domain = $perlvar{'lonDefDomain'};
13556: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13557: foreach my $posdom (¤t_machine_domains(),
13558: &additional_machine_domains()) {
13559: if (lc($posdom) eq lc($testdomain)) {
13560: $domain=$posdom;
13561: last;
13562: }
13563: }
13564: return $domain;
13565: }
13566:
1.1172.2.106 raeburn 13567: sub shared_institution {
1.1172.2.136 raeburn 13568: my ($dom,$lonhost) = @_;
13569: if ($lonhost eq '') {
13570: $lonhost = $perlvar{'lonHostID'};
13571: }
1.1172.2.106 raeburn 13572: my $same_intdom;
1.1172.2.136 raeburn 13573: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13574: if ($hostintdom ne '') {
13575: my %iphost = &get_iphost();
13576: my $primary_id = &domain($dom,'primary');
13577: my $primary_ip = &get_host_ip($primary_id);
13578: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13579: foreach my $id (@{$iphost{$primary_ip}}) {
13580: my $intdom = &internet_dom($id);
13581: if ($intdom eq $hostintdom) {
13582: $same_intdom = 1;
13583: last;
13584: }
13585: }
13586: }
13587: }
13588: return $same_intdom;
13589: }
13590:
1.1172.2.120 raeburn 13591: sub uses_sts {
13592: my ($ignore_cache) = @_;
13593: my $lonhost = $perlvar{'lonHostID'};
13594: my $hostname = &hostname($lonhost);
13595: my $sts_on;
13596: if ($protocol{$lonhost} eq 'https') {
13597: my $cachetime = 12*3600;
13598: if (!$ignore_cache) {
13599: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13600: if (defined($cached)) {
13601: return $sts_on;
13602: }
13603: }
1.1172.2.121 raeburn 13604: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13605: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13606: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13607: my $response=$ua->request($request);
1.1172.2.120 raeburn 13608: if ($response->is_success) {
13609: my $has_sts = $response->header('Strict-Transport-Security');
13610: if ($has_sts eq '') {
13611: $sts_on = 0;
13612: } else {
13613: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13614: my $maxage = $1;
13615: if ($maxage) {
13616: $sts_on = 1;
13617: } else {
13618: $sts_on = 0;
13619: }
13620: } else {
13621: $sts_on = 0;
13622: }
13623: }
13624: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13625: }
13626: }
13627: return;
13628: }
13629:
1.1172.2.142 raeburn 13630: sub waf_allssl {
13631: my ($host_name) = @_;
13632: my $alias = &get_proxy_alias();
13633: if ($host_name eq '') {
13634: $host_name = $ENV{'SERVER_NAME'};
13635: }
13636: if (($host_name ne '') && ($alias eq $host_name)) {
13637: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13638: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13639: if ($defdomdefaults{'waf_sslopt'}) {
13640: return $defdomdefaults{'waf_sslopt'};
13641: }
13642: }
13643: return;
13644: }
13645:
1.1172.2.134 raeburn 13646: sub get_requestor_ip {
13647: my ($r,$nolookup,$noproxy) = @_;
13648: my $from_ip;
13649: if (ref($r)) {
1.1172.2.142 raeburn 13650: if ($r->can('useragent_ip')) {
13651: if ($noproxy && $r->can('client_ip')) {
13652: $from_ip = $r->client_ip();
13653: } else {
13654: $from_ip = $r->useragent_ip();
13655: }
13656: } elsif ($r->connection->can('remote_ip')) {
13657: $from_ip = $r->connection->remote_ip();
13658: } else {
13659: $from_ip = $r->get_remote_host($nolookup);
13660: }
1.1172.2.134 raeburn 13661: } else {
13662: $from_ip = $ENV{'REMOTE_ADDR'};
13663: }
1.1172.2.142 raeburn 13664: return $from_ip if ($noproxy);
13665: # Who controls proxy settings for server
13666: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13667: my $proxyinfo = &get_proxy_settings($dom_in_use);
13668: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13669: if ($proxyinfo->{'vpnint'}) {
13670: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13671: return $from_ip;
13672: }
13673: }
13674: if ($proxyinfo->{'trusted'}) {
13675: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13676: my $ipheader = $proxyinfo->{'ipheader'};
13677: my ($ip,$xfor);
13678: if (ref($r)) {
13679: if ($ipheader) {
13680: $ip = $r->headers_in->{$ipheader};
13681: }
13682: $xfor = $r->headers_in->{'X-Forwarded-For'};
13683: } else {
13684: if ($ipheader) {
13685: $ip = $ENV{'HTTP_'.uc($ipheader)};
13686: }
13687: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13688: }
13689: if (($ip eq '') && ($xfor ne '')) {
13690: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13691: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13692: $ip = $poss_ip;
13693: last;
13694: }
13695: }
13696: }
13697: if ($ip ne '') {
13698: return $ip;
13699: }
13700: }
13701: }
13702: }
1.1172.2.134 raeburn 13703: return $from_ip;
13704: }
13705:
1.1172.2.142 raeburn 13706: sub get_proxy_settings {
13707: my ($dom_in_use) = @_;
13708: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13709: my $proxyinfo = {
13710: ipheader => $domdefaults{'waf_ipheader'},
13711: trusted => $domdefaults{'waf_trusted'},
13712: vpnint => $domdefaults{'waf_vpnint'},
13713: vpnext => $domdefaults{'waf_vpnext'},
13714: sslopt => $domdefaults{'waf_sslopt'},
13715: };
13716: return $proxyinfo;
13717: }
13718:
13719: sub ip_match {
13720: my ($ip,$pattern_str) = @_;
13721: $ip=Net::CIDR::cidrvalidate($ip);
13722: if ($ip) {
13723: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13724: }
13725: return;
13726: }
13727:
13728: sub get_proxy_alias {
13729: my ($lonid) = @_;
13730: if ($lonid eq '') {
13731: $lonid = $perlvar{'lonHostID'};
13732: }
13733: if (!defined(&hostname($lonid))) {
13734: return;
13735: }
13736: if ($lonid ne '') {
13737: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13738: if ($cached) {
13739: return $alias;
13740: }
13741: my $dom = &Apache::lonnet::host_domain($lonid);
13742: if ($dom ne '') {
13743: my $cachetime = 60*60*24;
13744: my %domconfig =
13745: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13746: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13747: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13748: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13749: }
13750: }
13751: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13752: }
13753: }
13754: return;
13755: }
13756:
13757: sub use_proxy_alias {
13758: my ($r,$lonid) = @_;
13759: my $alias = &get_proxy_alias($lonid);
13760: if ($alias) {
13761: my $dom = &host_domain($lonid);
13762: if ($dom ne '') {
13763: my $proxyinfo = &get_proxy_settings($dom);
13764: my ($vpnint,$remote_ip);
13765: if (ref($proxyinfo) eq 'HASH') {
13766: $vpnint = $proxyinfo->{'vpnint'};
13767: if ($vpnint) {
13768: $remote_ip = &get_requestor_ip($r,1,1);
13769: }
13770: }
13771: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13772: return $alias;
13773: }
13774: }
13775: }
13776: return;
13777: }
13778:
13779: sub alias_sso {
13780: my ($lonid) = @_;
13781: if ($lonid eq '') {
13782: $lonid = $perlvar{'lonHostID'};
13783: }
13784: if (!defined(&hostname($lonid))) {
13785: return;
13786: }
13787: if ($lonid ne '') {
13788: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13789: if ($cached) {
13790: return $use_alias;
13791: }
13792: my $dom = &Apache::lonnet::host_domain($lonid);
13793: if ($dom ne '') {
13794: my $cachetime = 60*60*24;
13795: my %domconfig =
13796: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13797: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13798: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13799: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13800: }
13801: }
13802: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13803: }
13804: }
13805: return;
13806: }
13807:
13808: sub get_saml_landing {
13809: my ($lonid) = @_;
13810: if ($lonid eq '') {
13811: my $defdom = &default_login_domain();
13812: my @hosts = ¤t_machine_ids();
13813: if (@hosts > 1) {
13814: foreach my $hostid (@hosts) {
13815: if (&host_domain($hostid) eq $defdom) {
13816: $lonid = $hostid;
13817: last;
13818: }
13819: }
13820: } else {
13821: $lonid = $perlvar{'lonHostID'};
13822: }
13823: if ($lonid) {
13824: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13825: return;
13826: }
13827: } else {
13828: return;
13829: }
13830: } elsif (!defined(&hostname($lonid))) {
13831: return;
13832: }
13833: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13834: if ($cached) {
13835: return $landing;
13836: }
13837: my $dom = &Apache::lonnet::host_domain($lonid);
13838: if ($dom ne '') {
13839: my $cachetime = 60*60*24;
13840: my %domconfig =
13841: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13842: if (ref($domconfig{'login'}) eq 'HASH') {
13843: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13844: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13845: $landing = 1;
13846: }
13847: }
13848: }
13849: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13850: }
13851: return;
13852: }
13853:
1.31 www 13854: # ------------------------------------------------------------- Declutters URLs
13855:
13856: sub declutter {
13857: my $thisfn=shift;
1.569 albertel 13858: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13859: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13860: $thisfn=~s{^/home/httpd/html}{};
13861: }
1.31 www 13862: $thisfn=~s/^\///;
1.697 albertel 13863: $thisfn=~s|^adm/wrapper/||;
13864: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13865: $thisfn=~s/^res\///;
1.1172 bisitz 13866: $thisfn=~s/^priv\///;
1.1032 raeburn 13867: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13868: $thisfn=~s/\?.+$//;
13869: }
1.268 www 13870: return $thisfn;
13871: }
13872:
13873: # ------------------------------------------------------------- Clutter up URLs
13874:
13875: sub clutter {
13876: my $thisfn='/'.&declutter(shift);
1.887 albertel 13877: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13878: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13879: $thisfn='/res'.$thisfn;
13880: }
1.1031 raeburn 13881: if ($thisfn !~m|^/adm|) {
13882: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13883: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13884: } else {
13885: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13886: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13887: if ($embstyle eq 'ssi'
13888: || ($embstyle eq 'hdn')
13889: || ($embstyle eq 'rat')
13890: || ($embstyle eq 'prv')
13891: || ($embstyle eq 'ign')) {
13892: #do nothing with these
13893: } elsif (($embstyle eq 'img')
1.695 albertel 13894: || ($embstyle eq 'emb')
13895: || ($embstyle eq 'wrp')) {
13896: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13897: } elsif ($embstyle eq 'unk'
13898: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13899: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13900: } else {
1.718 www 13901: # &logthis("Got a blank emb style");
1.695 albertel 13902: }
1.694 albertel 13903: }
13904: }
1.31 www 13905: return $thisfn;
1.12 www 13906: }
13907:
1.787 albertel 13908: sub clutter_with_no_wrapper {
13909: my $uri = &clutter(shift);
13910: if ($uri =~ m-^/adm/-) {
13911: $uri =~ s-^/adm/wrapper/-/-;
13912: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13913: }
13914: return $uri;
13915: }
13916:
1.557 albertel 13917: sub freeze_escape {
13918: my ($value)=@_;
13919: if (ref($value)) {
13920: $value=&nfreeze($value);
13921: return '__FROZEN__'.&escape($value);
13922: }
13923: return &escape($value);
13924: }
13925:
1.11 www 13926:
1.557 albertel 13927: sub thaw_unescape {
13928: my ($value)=@_;
13929: if ($value =~ /^__FROZEN__/) {
13930: substr($value,0,10,undef);
13931: $value=&unescape($value);
13932: return &thaw($value);
13933: }
13934: return &unescape($value);
13935: }
13936:
1.436 albertel 13937: sub correct_line_ends {
13938: my ($result)=@_;
13939: $$result =~s/\r\n/\n/mg;
13940: $$result =~s/\r/\n/mg;
1.415 albertel 13941: }
1.1 albertel 13942: # ================================================================ Main Program
13943:
1.184 www 13944: sub goodbye {
1.204 albertel 13945: &logthis("Starting Shut down");
1.443 albertel 13946: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13947: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13948: #converted
1.599 albertel 13949: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13950: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13951: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13952: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13953: #1.1 only
1.870 albertel 13954: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13955: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13956: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13957: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13958: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13959: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13960: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13961: &flushcourselogs();
13962: &logthis("Shutting down");
13963: }
13964:
1.852 albertel 13965: sub get_dns {
1.1172.2.17 raeburn 13966: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13967: if (!$ignore_cache) {
13968: my ($content,$cached)=
13969: &Apache::lonnet::is_cached_new('dns',$url);
13970: if ($cached) {
1.1172.2.17 raeburn 13971: &$func($content,$hashref);
1.869 albertel 13972: return;
13973: }
13974: }
13975:
13976: my %alldns;
1.1172.2.96 raeburn 13977: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13978: foreach my $dns (<$config>) {
13979: next if ($dns !~ /^\^(\S*)/x);
13980: my $line = $1;
13981: my ($host,$protocol) = split(/:/,$line);
13982: if ($protocol ne 'https') {
13983: $protocol = 'http';
13984: }
13985: $alldns{$host} = $protocol;
1.979 raeburn 13986: }
1.1172.2.96 raeburn 13987: close($config);
1.869 albertel 13988: }
13989: while (%alldns) {
1.1172.2.52 raeburn 13990: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13991: my @content;
13992: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13993: my $command = (split('/',$url))[3];
13994: my ($dir,$file) = &parse_getdns_url($command,$url);
13995: delete($alldns{$dns});
13996: next if (($dir eq '') || ($file eq ''));
13997: if (open(my $config,'<',"$dir/$file")) {
13998: @content = <$config>;
13999: close($config);
14000: }
14001: } else {
14002: my $ua=new LWP::UserAgent;
14003: $ua->timeout(30);
14004: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14005: my $response=$ua->request($request);
14006: delete($alldns{$dns});
14007: next if ($response->is_error());
14008: @content = split("\n",$response->content);
14009: }
1.1172.2.17 raeburn 14010: unless ($nocache) {
1.1172.2.23 raeburn 14011: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 14012: }
14013: &$func(\@content,$hashref);
1.869 albertel 14014: return;
1.852 albertel 14015: }
1.871 albertel 14016: my $which = (split('/',$url))[3];
14017: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14018: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14019: my @content = <$config>;
14020: &$func(\@content,$hashref);
14021: }
1.1172.2.17 raeburn 14022: return;
14023: }
14024:
14025: # ------------------------------------------------------Get DNS checksums file
14026: sub parse_dns_checksums_tab {
14027: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14028: my $lonhost = $perlvar{'lonHostID'};
14029: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14030: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14031: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14032: my $webconfdir = '/etc/httpd/conf';
14033: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14034: $webconfdir = '/etc/apache2';
14035: } elsif ($distro =~ /^sles(\d+)$/) {
14036: if ($1 >= 10) {
14037: $webconfdir = '/etc/apache2';
14038: }
14039: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14040: if ($1 >= 10.0) {
14041: $webconfdir = '/etc/apache2';
14042: }
14043: }
1.1172.2.17 raeburn 14044: my ($release,$timestamp) = split(/\-/,$loncaparev);
14045: my (%chksum,%revnum);
14046: if (ref($lines) eq 'ARRAY') {
14047: chomp(@{$lines});
1.1172.2.34 raeburn 14048: my $version = shift(@{$lines});
14049: if ($version eq $release) {
1.1172.2.17 raeburn 14050: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14051: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14052: if ($file =~ m{^/etc/httpd/conf}) {
14053: if ($webconfdir eq '/etc/apache2') {
14054: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14055: }
14056: }
1.1172.2.34 raeburn 14057: $chksum{$file} = $shasum;
14058: $revnum{$file} = $version;
1.1172.2.17 raeburn 14059: }
14060: if (ref($hashref) eq 'HASH') {
14061: %{$hashref} = (
14062: sums => \%chksum,
14063: versions => \%revnum,
14064: );
14065: }
14066: }
14067: }
1.869 albertel 14068: return;
1.852 albertel 14069: }
1.1172.2.17 raeburn 14070:
14071: sub fetch_dns_checksums {
14072: my %checksums;
1.1172.2.34 raeburn 14073: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14074: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14075: my ($release,$timestamp) = split(/\-/,$loncaparev);
14076: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14077: \%checksums);
14078: return \%checksums;
14079: }
14080:
1.1172.2.142 raeburn 14081: sub parse_getdns_url {
14082: my ($command,$url) = @_;
14083: my $dir = $perlvar{'lonTabDir'};
14084: my $file;
14085: if ($command eq 'hosts') {
14086: $file = 'dns_hosts.tab';
14087: } elsif ($command eq 'domain') {
14088: $file = 'dns_domain.tab';
14089: } elsif ($command eq 'checksums') {
14090: my $version = (split('/',$url))[4];
14091: $file = "dns_checksums/$version.tab",
14092: }
14093: return ($dir,$file);
14094: }
14095:
1.327 albertel 14096: # ------------------------------------------------------------ Read domain file
14097: {
1.852 albertel 14098: my $loaded;
1.846 albertel 14099: my %domain;
14100:
1.852 albertel 14101: sub parse_domain_tab {
14102: my ($lines) = @_;
14103: foreach my $line (@$lines) {
14104: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14105:
1.846 albertel 14106: chomp($line);
1.852 albertel 14107: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14108: my %this_domain;
14109: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14110: 'lang_def', 'city', 'longi', 'lati',
14111: 'primary') {
14112: $this_domain{$field} = shift(@elements);
14113: }
14114: $domain{$name} = \%this_domain;
1.852 albertel 14115: }
14116: }
1.864 albertel 14117:
14118: sub reset_domain_info {
14119: undef($loaded);
14120: undef(%domain);
14121: }
14122:
1.852 albertel 14123: sub load_domain_tab {
1.1172.2.70 raeburn 14124: my ($ignore_cache,$nocache) = @_;
14125: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14126: my $fh;
1.1172.2.96 raeburn 14127: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14128: my @lines = <$fh>;
14129: &parse_domain_tab(\@lines);
1.448 albertel 14130: }
1.852 albertel 14131: close($fh);
14132: $loaded = 1;
1.327 albertel 14133: }
1.846 albertel 14134:
14135: sub domain {
1.852 albertel 14136: &load_domain_tab() if (!$loaded);
14137:
1.846 albertel 14138: my ($name,$what) = @_;
14139: return if ( !exists($domain{$name}) );
14140:
14141: if (!$what) {
14142: return $domain{$name}{'description'};
14143: }
14144: return $domain{$name}{$what};
14145: }
1.974 raeburn 14146:
14147: sub domain_info {
14148: &load_domain_tab() if (!$loaded);
14149: return %domain;
14150: }
14151:
1.327 albertel 14152: }
14153:
14154:
1.1 albertel 14155: # ------------------------------------------------------------- Read hosts file
14156: {
1.838 albertel 14157: my %hostname;
1.844 albertel 14158: my %hostdom;
1.845 albertel 14159: my %libserv;
1.852 albertel 14160: my $loaded;
1.888 albertel 14161: my %name_to_host;
1.1074 raeburn 14162: my %internetdom;
1.1107 raeburn 14163: my %LC_dns_serv;
1.852 albertel 14164:
14165: sub parse_hosts_tab {
14166: my ($file) = @_;
14167: foreach my $configline (@$file) {
14168: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14169: chomp($configline);
14170: if ($configline =~ /^\^/) {
14171: if ($configline =~ /^\^([\w.\-]+)/) {
14172: $LC_dns_serv{$1} = 1;
14173: }
14174: next;
14175: }
1.1074 raeburn 14176: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14177: $name=~s/\s//g;
14178: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14179: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14180: my $curr = $hostname{$id};
14181: my $skip;
14182: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14183: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14184: $skip = 1;
14185: } else {
14186: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14187: }
14188: }
14189: unless ($skip) {
14190: push(@{$name_to_host{$name}},$id);
14191: }
14192: } else {
14193: push(@{$name_to_host{$name}},$id);
14194: }
1.852 albertel 14195: $hostname{$id}=$name;
14196: $hostdom{$id}=$domain;
14197: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14198: if (defined($protocol)) {
14199: if ($protocol eq 'https') {
14200: $protocol{$id} = $protocol;
14201: } else {
14202: $protocol{$id} = 'http';
14203: }
1.968 raeburn 14204: } else {
1.969 raeburn 14205: $protocol{$id} = 'http';
1.968 raeburn 14206: }
1.1074 raeburn 14207: if (defined($intdom)) {
14208: $internetdom{$id} = $intdom;
14209: }
1.852 albertel 14210: }
14211: }
14212: }
1.864 albertel 14213:
14214: sub reset_hosts_info {
1.897 albertel 14215: &purge_remembered();
1.864 albertel 14216: &reset_domain_info();
14217: &reset_hosts_ip_info();
1.892 albertel 14218: undef(%name_to_host);
1.864 albertel 14219: undef(%hostname);
14220: undef(%hostdom);
14221: undef(%libserv);
14222: undef($loaded);
14223: }
1.1 albertel 14224:
1.852 albertel 14225: sub load_hosts_tab {
1.1172.2.70 raeburn 14226: my ($ignore_cache,$nocache) = @_;
14227: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14228: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14229: my @config = <$config>;
14230: &parse_hosts_tab(\@config);
14231: close($config);
14232: $loaded=1;
1.1 albertel 14233: }
1.852 albertel 14234:
1.838 albertel 14235: sub hostname {
1.852 albertel 14236: &load_hosts_tab() if (!$loaded);
14237:
1.838 albertel 14238: my ($lonid) = @_;
14239: return $hostname{$lonid};
14240: }
1.845 albertel 14241:
1.838 albertel 14242: sub all_hostnames {
1.852 albertel 14243: &load_hosts_tab() if (!$loaded);
14244:
1.838 albertel 14245: return %hostname;
14246: }
1.845 albertel 14247:
1.888 albertel 14248: sub all_names {
1.1172.2.70 raeburn 14249: my ($ignore_cache,$nocache) = @_;
14250: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14251:
14252: return %name_to_host;
14253: }
14254:
1.974 raeburn 14255: sub all_host_domain {
14256: &load_hosts_tab() if (!$loaded);
14257: return %hostdom;
14258: }
14259:
1.845 albertel 14260: sub is_library {
1.852 albertel 14261: &load_hosts_tab() if (!$loaded);
14262:
1.845 albertel 14263: return exists($libserv{$_[0]});
14264: }
14265:
14266: sub all_library {
1.852 albertel 14267: &load_hosts_tab() if (!$loaded);
14268:
1.845 albertel 14269: return %libserv;
14270: }
14271:
1.1062 droeschl 14272: sub unique_library {
14273: #2x reverse removes all hostnames that appear more than once
14274: my %unique = reverse &all_library();
14275: return reverse %unique;
14276: }
14277:
1.841 albertel 14278: sub get_servers {
1.852 albertel 14279: &load_hosts_tab() if (!$loaded);
14280:
1.841 albertel 14281: my ($domain,$type) = @_;
14282: my %possible_hosts = ($type eq 'library') ? %libserv
14283: : %hostname;
14284: my %result;
1.842 albertel 14285: if (ref($domain) eq 'ARRAY') {
14286: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14287: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14288: $result{$host} = $hostname;
14289: }
14290: }
14291: } else {
14292: while ( my ($host,$hostname) = each(%possible_hosts)) {
14293: if ($hostdom{$host} eq $domain) {
14294: $result{$host} = $hostname;
14295: }
1.841 albertel 14296: }
14297: }
14298: return %result;
14299: }
1.845 albertel 14300:
1.1062 droeschl 14301: sub get_unique_servers {
14302: my %unique = reverse &get_servers(@_);
14303: return reverse %unique;
14304: }
14305:
1.844 albertel 14306: sub host_domain {
1.852 albertel 14307: &load_hosts_tab() if (!$loaded);
14308:
1.844 albertel 14309: my ($lonid) = @_;
14310: return $hostdom{$lonid};
14311: }
14312:
1.841 albertel 14313: sub all_domains {
1.852 albertel 14314: &load_hosts_tab() if (!$loaded);
14315:
1.841 albertel 14316: my %seen;
14317: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14318: return @uniq;
14319: }
1.1074 raeburn 14320:
14321: sub internet_dom {
14322: &load_hosts_tab() if (!$loaded);
14323:
14324: my ($lonid) = @_;
14325: return $internetdom{$lonid};
14326: }
1.1107 raeburn 14327:
14328: sub is_LC_dns {
14329: &load_hosts_tab() if (!$loaded);
14330:
14331: my ($hostname) = @_;
14332: return exists($LC_dns_serv{$hostname});
14333: }
14334:
1.1 albertel 14335: }
14336:
1.847 albertel 14337: {
14338: my %iphost;
1.856 albertel 14339: my %name_to_ip;
14340: my %lonid_to_ip;
1.869 albertel 14341:
1.847 albertel 14342: sub get_hosts_from_ip {
14343: my ($ip) = @_;
14344: my %iphosts = &get_iphost();
14345: if (ref($iphosts{$ip})) {
14346: return @{$iphosts{$ip}};
14347: }
14348: return;
1.839 albertel 14349: }
1.864 albertel 14350:
14351: sub reset_hosts_ip_info {
14352: undef(%iphost);
14353: undef(%name_to_ip);
14354: undef(%lonid_to_ip);
14355: }
1.856 albertel 14356:
14357: sub get_host_ip {
14358: my ($lonid) = @_;
14359: if (exists($lonid_to_ip{$lonid})) {
14360: return $lonid_to_ip{$lonid};
14361: }
14362: my $name=&hostname($lonid);
14363: my $ip = gethostbyname($name);
14364: return if (!$ip || length($ip) ne 4);
14365: $ip=inet_ntoa($ip);
14366: $name_to_ip{$name} = $ip;
14367: $lonid_to_ip{$lonid} = $ip;
14368: return $ip;
14369: }
1.847 albertel 14370:
14371: sub get_iphost {
1.1172.2.70 raeburn 14372: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14373:
1.869 albertel 14374: if (!$ignore_cache) {
14375: if (%iphost) {
14376: return %iphost;
14377: }
14378: my ($ip_info,$cached)=
14379: &Apache::lonnet::is_cached_new('iphost','iphost');
14380: if ($cached) {
14381: %iphost = %{$ip_info->[0]};
14382: %name_to_ip = %{$ip_info->[1]};
14383: %lonid_to_ip = %{$ip_info->[2]};
14384: return %iphost;
14385: }
14386: }
1.894 albertel 14387:
14388: # get yesterday's info for fallback
14389: my %old_name_to_ip;
14390: my ($ip_info,$cached)=
14391: &Apache::lonnet::is_cached_new('iphost','iphost');
14392: if ($cached) {
14393: %old_name_to_ip = %{$ip_info->[1]};
14394: }
14395:
1.1172.2.70 raeburn 14396: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14397: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14398: my $ip;
14399: if (!exists($name_to_ip{$name})) {
14400: $ip = gethostbyname($name);
14401: if (!$ip || length($ip) ne 4) {
1.894 albertel 14402: if (defined($old_name_to_ip{$name})) {
14403: $ip = $old_name_to_ip{$name};
14404: &logthis("Can't find $name defaulting to old $ip");
14405: } else {
14406: &logthis("Name $name no IP found");
14407: next;
14408: }
14409: } else {
14410: $ip=inet_ntoa($ip);
1.847 albertel 14411: }
14412: $name_to_ip{$name} = $ip;
14413: } else {
14414: $ip = $name_to_ip{$name};
1.653 albertel 14415: }
1.888 albertel 14416: foreach my $id (@{ $name_to_host{$name} }) {
14417: $lonid_to_ip{$id} = $ip;
14418: }
14419: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14420: }
1.1172.2.70 raeburn 14421: unless ($nocache) {
14422: &do_cache_new('iphost','iphost',
14423: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14424: 48*60*60);
14425: }
1.869 albertel 14426:
1.847 albertel 14427: return %iphost;
1.598 albertel 14428: }
14429:
1.992 raeburn 14430: #
14431: # Given a DNS returns the loncapa host name for that DNS
14432: #
14433: sub host_from_dns {
14434: my ($dns) = @_;
14435: my @hosts;
14436: my $ip;
14437:
1.993 raeburn 14438: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14439: $ip = $name_to_ip{$dns};
14440: }
14441: if (!$ip) {
14442: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14443: if (length($ip) == 4) {
14444: $ip = &IO::Socket::inet_ntoa($ip);
14445: }
14446: }
14447: if ($ip) {
14448: @hosts = get_hosts_from_ip($ip);
14449: return $hosts[0];
14450: }
14451: return undef;
1.986 foxr 14452: }
1.992 raeburn 14453:
1.1074 raeburn 14454: sub get_internet_names {
14455: my ($lonid) = @_;
14456: return if ($lonid eq '');
14457: my ($idnref,$cached)=
14458: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14459: if ($cached) {
14460: return $idnref;
14461: }
14462: my $ip = &get_host_ip($lonid);
14463: my @hosts = &get_hosts_from_ip($ip);
14464: my %iphost = &get_iphost();
14465: my (@idns,%seen);
14466: foreach my $id (@hosts) {
14467: my $dom = &host_domain($id);
14468: my $prim_id = &domain($dom,'primary');
14469: my $prim_ip = &get_host_ip($prim_id);
14470: next if ($seen{$prim_ip});
14471: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14472: foreach my $id (@{$iphost{$prim_ip}}) {
14473: my $intdom = &internet_dom($id);
14474: unless (grep(/^\Q$intdom\E$/,@idns)) {
14475: push(@idns,$intdom);
14476: }
14477: }
14478: }
14479: $seen{$prim_ip} = 1;
14480: }
1.1172.2.23 raeburn 14481: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14482: }
14483:
1.986 foxr 14484: }
14485:
1.1079 raeburn 14486: sub all_loncaparevs {
1.1172.2.39 raeburn 14487: 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 14488: }
14489:
1.1172.2.27 raeburn 14490: # ------------------------------------------------------- Read loncaparev table
14491: {
14492: sub load_loncaparevs {
14493: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14494: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14495: while (my $configline=<$config>) {
14496: chomp($configline);
14497: my ($hostid,$loncaparev)=split(/:/,$configline);
14498: $loncaparevs{$hostid}=$loncaparev;
14499: }
14500: close($config);
14501: }
14502: }
14503: }
14504: }
14505:
14506: # ----------------------------------------------------- Read serverhostID table
14507: {
14508: sub load_serverhomeIDs {
14509: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14510: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14511: while (my $configline=<$config>) {
14512: chomp($configline);
14513: my ($name,$id)=split(/:/,$configline);
14514: $serverhomeIDs{$name}=$id;
14515: }
14516: close($config);
14517: }
14518: }
14519: }
14520: }
14521:
14522:
1.862 albertel 14523: BEGIN {
14524:
14525: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14526: unless ($readit) {
14527: {
14528: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14529: %perlvar = (%perlvar,%{$configvars});
14530: }
14531:
14532:
1.1 albertel 14533: # ------------------------------------------------------ Read spare server file
14534: {
1.1172.2.96 raeburn 14535: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14536:
14537: while (my $configline=<$config>) {
14538: chomp($configline);
1.284 matthew 14539: if ($configline) {
1.784 albertel 14540: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14541: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14542: push(@{ $spareid{$type} }, $host);
1.1 albertel 14543: }
14544: }
1.448 albertel 14545: close($config);
1.1 albertel 14546: }
1.11 www 14547: # ------------------------------------------------------------ Read permissions
14548: {
1.1172.2.96 raeburn 14549: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14550:
14551: while (my $configline=<$config>) {
1.448 albertel 14552: chomp($configline);
14553: if ($configline) {
14554: my ($role,$perm)=split(/ /,$configline);
14555: if ($perm ne '') { $pr{$role}=$perm; }
14556: }
1.11 www 14557: }
1.448 albertel 14558: close($config);
1.11 www 14559: }
14560:
14561: # -------------------------------------------- Read plain texts for permissions
14562: {
1.1172.2.96 raeburn 14563: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14564:
14565: while (my $configline=<$config>) {
1.448 albertel 14566: chomp($configline);
14567: if ($configline) {
1.742 raeburn 14568: my ($short,@plain)=split(/:/,$configline);
14569: %{$prp{$short}} = ();
14570: if (@plain > 0) {
14571: $prp{$short}{'std'} = $plain[0];
14572: for (my $i=1; $i<@plain; $i++) {
14573: $prp{$short}{'alt'.$i} = $plain[$i];
14574: }
14575: }
1.448 albertel 14576: }
1.135 www 14577: }
1.448 albertel 14578: close($config);
1.135 www 14579: }
14580:
14581: # ---------------------------------------------------------- Read package table
14582: {
1.1172.2.96 raeburn 14583: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14584:
14585: while (my $configline=<$config>) {
1.483 albertel 14586: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14587: chomp($configline);
14588: my ($short,$plain)=split(/:/,$configline);
14589: my ($pack,$name)=split(/\&/,$short);
14590: if ($plain ne '') {
14591: $packagetab{$pack.'&'.$name.'&name'}=$name;
14592: $packagetab{$short}=$plain;
14593: }
1.11 www 14594: }
1.448 albertel 14595: close($config);
1.329 matthew 14596: }
14597:
1.1172.2.27 raeburn 14598: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14599:
1.1172.2.27 raeburn 14600: &load_loncaparevs();
14601:
14602: # ------------------------------------------------------- Read serverhostID table
14603:
14604: &load_serverhomeIDs();
1.1074 raeburn 14605:
1.1172.2.27 raeburn 14606: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14607: {
14608: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14609: if (-e $file) {
14610: my $parser = HTML::LCParser->new($file);
14611: while (my $token = $parser->get_token()) {
14612: if ($token->[0] eq 'S') {
14613: my $item = $token->[1];
14614: my $name = $token->[2]{'name'};
14615: my $value = $token->[2]{'value'};
14616: if ($item ne '' && $name ne '' && $value ne '') {
14617: my $release = $parser->get_text();
14618: $release =~ s/(^\s*|\s*$ )//gx;
14619: $needsrelease{$item.':'.$name.':'.$value} = $release;
14620: }
14621: }
14622: }
14623: }
1.1073 raeburn 14624: }
14625:
1.1138 raeburn 14626: # ---------------------------------------------------------- Read managers table
14627: {
14628: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14629: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14630: while (my $configline=<$config>) {
14631: chomp($configline);
14632: next if ($configline =~ /^\#/);
14633: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14634: $managerstab{$configline} = 1;
14635: }
14636: }
14637: close($config);
14638: }
14639: }
14640: }
14641:
1.329 matthew 14642: # ------------- set up temporary directory
14643: {
1.1117 foxr 14644: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14645:
1.11 www 14646: }
14647:
1.1172.2.104 raeburn 14648: # ------------- set default texengine (domain default overrides this)
14649: {
14650: $deftex = LONCAPA::texengine();
14651: }
14652:
1.1172.2.114 raeburn 14653: # ------------- set default minimum length for passwords for internal auth users
14654: {
14655: $passwdmin = LONCAPA::passwd_min();
14656: }
14657:
1.794 albertel 14658: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14659: 'compress_threshold'=> 20_000,
14660: });
1.185 www 14661:
1.281 www 14662: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14663: $dumpcount=0;
1.958 www 14664: $locknum=0;
1.22 www 14665:
1.163 harris41 14666: &logtouch();
1.672 albertel 14667: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14668: $readit=1;
1.564 albertel 14669: {
14670: use integer;
14671: my $test=(2**32)+1;
1.568 albertel 14672: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14673: &logthis(" Detected 64bit platform ($_64bit)");
14674: }
1.195 www 14675: }
1.1 albertel 14676: }
1.179 www 14677:
1.1 albertel 14678: 1;
1.191 harris41 14679: __END__
14680:
1.243 albertel 14681: =pod
14682:
1.191 harris41 14683: =head1 NAME
14684:
1.243 albertel 14685: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14686:
14687: =head1 SYNOPSIS
14688:
1.243 albertel 14689: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14690:
14691: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14692:
1.243 albertel 14693: Common parameters:
14694:
14695: =over 4
14696:
14697: =item *
14698:
14699: $uname : an internal username (if $cname expecting a course Id specifically)
14700:
14701: =item *
14702:
14703: $udom : a domain (if $cdom expecting a course's domain specifically)
14704:
14705: =item *
14706:
14707: $symb : a resource instance identifier
14708:
14709: =item *
14710:
14711: $namespace : the name of a .db file that contains the data needed or
14712: being set.
14713:
14714: =back
14715:
1.394 bowersj2 14716: =head1 OVERVIEW
1.191 harris41 14717:
1.394 bowersj2 14718: lonnet provides subroutines which interact with the
14719: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14720: about classes, users, and resources.
1.243 albertel 14721:
14722: For many of these objects you can also use this to store data about
14723: them or modify them in various ways.
1.191 harris41 14724:
1.394 bowersj2 14725: =head2 Symbs
1.191 harris41 14726:
1.394 bowersj2 14727: To identify a specific instance of a resource, LON-CAPA uses symbols
14728: or "symbs"X<symb>. These identifiers are built from the URL of the
14729: map, the resource number of the resource in the map, and the URL of
14730: the resource itself. The latter is somewhat redundant, but might help
14731: if maps change.
14732:
14733: An example is
14734:
14735: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14736:
14737: The respective map entry is
14738:
14739: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14740: title="Problem 2">
14741: </resource>
14742:
14743: Symbs are used by the random number generator, as well as to store and
14744: restore data specific to a certain instance of for example a problem.
14745:
14746: =head2 Storing And Retrieving Data
14747:
14748: X<store()>X<cstore()>X<restore()>Three of the most important functions
14749: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14750: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14751: is is the non-critical message twin of cstore. These functions are for
14752: handlers to store a perl hash to a user's permanent data space in an
14753: easy manner, and to retrieve it again on another call. It is expected
14754: that a handler would use this once at the beginning to retrieve data,
14755: and then again once at the end to send only the new data back.
14756:
14757: The data is stored in the user's data directory on the user's
14758: homeserver under the ID of the course.
14759:
14760: The hash that is returned by restore will have all of the previous
14761: value for all of the elements of the hash.
14762:
14763: Example:
14764:
14765: #creating a hash
14766: my %hash;
14767: $hash{'foo'}='bar';
14768:
14769: #storing it
14770: &Apache::lonnet::cstore(\%hash);
14771:
14772: #changing a value
14773: $hash{'foo'}='notbar';
14774:
14775: #adding a new value
14776: $hash{'bar'}='foo';
14777: &Apache::lonnet::cstore(\%hash);
14778:
14779: #retrieving the hash
14780: my %history=&Apache::lonnet::restore();
14781:
14782: #print the hash
14783: foreach my $key (sort(keys(%history))) {
14784: print("\%history{$key} = $history{$key}");
14785: }
14786:
14787: Will print out:
1.191 harris41 14788:
1.394 bowersj2 14789: %history{1:foo} = bar
14790: %history{1:keys} = foo:timestamp
14791: %history{1:timestamp} = 990455579
14792: %history{2:bar} = foo
14793: %history{2:foo} = notbar
14794: %history{2:keys} = foo:bar:timestamp
14795: %history{2:timestamp} = 990455580
14796: %history{bar} = foo
14797: %history{foo} = notbar
14798: %history{timestamp} = 990455580
14799: %history{version} = 2
14800:
14801: Note that the special hash entries C<keys>, C<version> and
14802: C<timestamp> were added to the hash. C<version> will be equal to the
14803: total number of versions of the data that have been stored. The
14804: C<timestamp> attribute will be the UNIX time the hash was
14805: stored. C<keys> is available in every historical section to list which
14806: keys were added or changed at a specific historical revision of a
14807: hash.
14808:
14809: B<Warning>: do not store the hash that restore returns directly. This
14810: will cause a mess since it will restore the historical keys as if the
14811: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14812:
1.394 bowersj2 14813: Calling convention:
1.191 harris41 14814:
1.1172.2.27 raeburn 14815: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14816: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14817:
1.394 bowersj2 14818: For more detailed information, see lonnet specific documentation.
1.191 harris41 14819:
1.394 bowersj2 14820: =head1 RETURN MESSAGES
1.191 harris41 14821:
1.394 bowersj2 14822: =over 4
1.191 harris41 14823:
1.394 bowersj2 14824: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14825:
1.394 bowersj2 14826: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14827: when the connection is brought back up
1.191 harris41 14828:
1.394 bowersj2 14829: =item * B<con_failed>: unable to contact remote host and unable to save message
14830: for later delivery
1.191 harris41 14831:
1.967 bisitz 14832: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14833:
1.394 bowersj2 14834: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14835: that was requested
1.191 harris41 14836:
1.243 albertel 14837: =back
1.191 harris41 14838:
1.243 albertel 14839: =head1 PUBLIC SUBROUTINES
1.191 harris41 14840:
1.243 albertel 14841: =head2 Session Environment Functions
1.191 harris41 14842:
1.243 albertel 14843: =over 4
1.191 harris41 14844:
1.394 bowersj2 14845: =item *
14846: X<appenv()>
1.949 raeburn 14847: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14848: the user envirnoment file, and will be restored for each access this
1.620 albertel 14849: user makes during this session, also modifies the %env for the current
1.949 raeburn 14850: process. Optional rolesarrayref - if defined contains a reference to an array
14851: of roles which are exempt from the restriction on modifying user.role entries
14852: in the user's environment.db and in %env.
1.191 harris41 14853:
14854: =item *
1.394 bowersj2 14855: X<delenv()>
1.987 raeburn 14856: B<delenv($delthis,$regexp)>: removes all items from the session
14857: environment file that begin with $delthis. If the
14858: optional second arg - $regexp - is true, $delthis is treated as a
14859: regular expression, otherwise \Q$delthis\E is used.
14860: The values are also deleted from the current processes %env.
1.191 harris41 14861:
1.795 albertel 14862: =item * get_env_multiple($name)
14863:
14864: gets $name from the %env hash, it seemlessly handles the cases where multiple
14865: values may be defined and end up as an array ref.
14866:
14867: returns an array of values
14868:
1.243 albertel 14869: =back
14870:
14871: =head2 User Information
1.191 harris41 14872:
1.243 albertel 14873: =over 4
1.191 harris41 14874:
14875: =item *
1.394 bowersj2 14876: X<queryauthenticate()>
14877: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14878: authentication scheme
14879:
14880: =item *
1.394 bowersj2 14881: X<authenticate()>
1.1073 raeburn 14882: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14883: authenticate user from domain's lib servers (first use the current
14884: one). C<$upass> should be the users password.
1.1073 raeburn 14885: $checkdefauth is optional (value is 1 if a check should be made to
14886: authenticate user using default authentication method, and allow
14887: account creation if username does not have account in the domain).
14888: $clientcancheckhost is optional (value is 1 if checking whether the
14889: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14890:
14891: =item *
1.394 bowersj2 14892: X<homeserver()>
14893: B<homeserver($uname,$udom)>: find the server which has
14894: the user's directory and files (there must be only one), this caches
14895: the answer, and also caches if there is a borken connection.
1.191 harris41 14896:
14897: =item *
1.394 bowersj2 14898: X<idget()>
14899: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14900: (IDs are a unique resource in a domain, there must be only 1 ID per
14901: username, and only 1 username per ID in a specific domain) (returns
14902: hash: id=>name,id=>name)
1.191 harris41 14903:
14904: =item *
1.394 bowersj2 14905: X<idrget()>
14906: B<idrget($udom,@unames)>: find the IDs behind a list of
14907: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14908:
14909: =item *
1.394 bowersj2 14910: X<idput()>
14911: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14912:
14913: =item *
1.394 bowersj2 14914: X<rolesinit()>
1.1169 droeschl 14915: B<rolesinit($udom,$username)>: get user privileges.
14916: returns user role, first access and timer interval hashes
1.243 albertel 14917:
14918: =item *
1.1171 droeschl 14919: X<privileged()>
14920: B<privileged($username,$domain)>: returns a true if user has a
14921: privileged and active role (i.e. su or dc), false otherwise.
14922:
14923: =item *
1.551 albertel 14924: X<getsection()>
14925: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14926: course $cname, return section name/number or '' for "not in course"
14927: and '-1' for "no section"
14928:
14929: =item *
1.394 bowersj2 14930: X<userenvironment()>
14931: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14932: passed in @what from the requested user's environment, returns a hash
14933:
1.858 raeburn 14934: =item *
14935: X<userlog_query()>
1.859 albertel 14936: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14937: activity.log file. %filters defines filters applied when parsing the
14938: log file. These can be start or end timestamps, or the type of action
14939: - log to look for Login or Logout events, check for Checkin or
14940: Checkout, role for role selection. The response is in the form
14941: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14942: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14943:
1.243 albertel 14944: =back
14945:
14946: =head2 User Roles
14947:
14948: =over 4
14949:
14950: =item *
14951:
1.1172.2.65 raeburn 14952: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14953: returns codes for allowed actions.
14954:
14955: The first argument is required, all others are optional.
14956:
14957: $priv is the privilege being checked.
14958: $uri contains additional information about what is being checked for access (e.g.,
14959: URL, course ID etc.).
14960: $symb is the unique resource instance identifier in a course; if needed,
14961: but not provided, it will be retrieved via a call to &symbread().
14962: $role is the role for which a priv is being checked (only used if priv is evb).
14963: $clientip is the user's IP address (only used when checking for access to portfolio
14964: files).
14965: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14966: prevents recursive calls to &allowed.
14967:
1.243 albertel 14968: F: full access
14969: U,I,K: authentication modes (cxx only)
14970: '': forbidden
14971: 1: user needs to choose course
14972: 2: browse allowed
1.766 albertel 14973: A: passphrase authentication needed
1.1172.2.65 raeburn 14974: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14975:
14976: =item *
14977:
1.1172.2.13 raeburn 14978: constructaccess($url,$setpriv) : check for access to construction space URL
14979:
14980: See if the owner domain and name in the URL match those in the
14981: expected environment. If so, return three element list
14982: ($ownername,$ownerdomain,$ownerhome).
14983:
14984: Otherwise return the null string.
14985:
14986: If second argument 'setpriv' is true, it assigns the privileges,
14987: and returns the same three element list, unless the owner has
14988: blocked "ad hoc" Domain Coordinator access to the Author Space,
14989: in which case the null string is returned.
14990:
14991: =item *
14992:
1.1172.2.84 raeburn 14993: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14994: define a custom role rolename set privileges in format of lonTabs/roles.tab
14995: for system, domain, and course level. $uname and $udom are optional (current
14996: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14997:
14998: =item *
14999:
1.988 raeburn 15000: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15001: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15002: $type is Course (default) or Community.
1.988 raeburn 15003: If $forcedefault evaluates to true, text returned will be default
15004: text for $type. Otherwise, if this is a course, the text returned
15005: will be a custom name for the role (if defined in the course's
15006: environment). If no custom name is defined the default is returned.
15007:
1.832 raeburn 15008: =item *
15009:
1.1172.2.23 raeburn 15010: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15011: All arguments are optional. Returns a hash of a roles, either for
15012: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15013: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15014: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15015: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15016: For each key, value is set to colon-separated start and end times for
15017: the role. If no username and domain are specified, will default to
1.934 raeburn 15018: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15019: of role statuses (active, future or previous), roles
15020: (e.g., cc,in, st etc.) and domains of the roles which can be used
15021: to restrict the list of roles reported. If no array ref is
15022: provided for types, will default to return only active roles.
1.834 albertel 15023:
1.1172.2.13 raeburn 15024: =item *
15025:
15026: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15027: user: $uname:$udom has a role in the course: $cdom_$cnum.
15028:
15029: Additional optional arguments are: $type (if role checking is to be restricted
15030: to certain user status types -- previous (expired roles), active (currently
15031: available roles) or future (roles available in the future), and
15032: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15033: have active Domain Coordinator role in course's domain or in additional
15034: domains (specified in 'Domains to check for privileged users' in course
15035: environment -- set via: Course Settings -> Classlists and staff listing).
15036:
15037: =item *
15038:
15039: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15040: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15041: $possdomains and $possroles are optional array refs -- to domains to check and
15042: roles to check. If $possdomains is not specified, a dump will be done of the
15043: users' roles.db to check for a dc or su role in any domain. This can be
15044: time consuming if &privileged is called repeatedly (e.g., when displaying a
15045: classlist), so in such cases, supplying a $possdomains array is preferred, as
15046: this then allows &privileged_by_domain() to be used, which caches the identity
15047: of privileged users, eliminating the need for repeated calls to &dump().
15048:
15049: =item *
15050:
15051: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15052: where the outer hash keys are domains specified in the $possdomains array ref,
15053: next inner hash keys are privileged roles specified in the $roles array ref,
15054: and the innermost hash contains key = value pairs for username:domain = end:start
15055: for active or future "privileged" users with that role in that domain. To avoid
15056: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15057: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15058:
1.243 albertel 15059: =back
15060:
15061: =head2 User Modification
15062:
15063: =over 4
15064:
15065: =item *
15066:
1.957 raeburn 15067: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15068: user for the level given by URL. Optional start and end dates (leave empty
15069: string or zero for "no date")
1.191 harris41 15070:
15071: =item *
15072:
1.243 albertel 15073: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15074: change a users, password, possible return values are: ok,
15075: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15076: refused
1.191 harris41 15077:
15078: =item *
15079:
1.243 albertel 15080: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15081:
15082: =item *
15083:
1.1058 raeburn 15084: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15085: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15086:
15087: will update user information (firstname,middlename,lastname,generation,
15088: permanentemail), and if forceid is true, student/employee ID also.
15089: A user's institutional affiliation(s) can also be updated.
15090: User information fields will not be overwritten with empty entries
15091: unless the field is included in the $candelete array reference.
15092: This array is included when a single user is modified via "Manage Users",
15093: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15094:
15095: =item *
15096:
1.286 matthew 15097: modifystudent
15098:
1.957 raeburn 15099: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15100: The course id is resolved based on the current user's environment.
15101: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15102: associated with a course.
15103:
1.297 matthew 15104: This call is essentially a wrapper for lonnet::modifyuser and
15105: lonnet::modify_student_enrollment
1.286 matthew 15106:
15107: Inputs:
15108:
15109: =over 4
15110:
1.957 raeburn 15111: =item B<$udom> Student's loncapa domain
1.286 matthew 15112:
1.957 raeburn 15113: =item B<$uname> Student's loncapa login name
1.286 matthew 15114:
1.964 bisitz 15115: =item B<$uid> Student/Employee ID
1.286 matthew 15116:
1.957 raeburn 15117: =item B<$umode> Student's authentication mode
1.286 matthew 15118:
1.957 raeburn 15119: =item B<$upass> Student's password
1.286 matthew 15120:
1.957 raeburn 15121: =item B<$first> Student's first name
1.286 matthew 15122:
1.957 raeburn 15123: =item B<$middle> Student's middle name
1.286 matthew 15124:
1.957 raeburn 15125: =item B<$last> Student's last name
1.286 matthew 15126:
1.957 raeburn 15127: =item B<$gene> Student's generation
1.286 matthew 15128:
1.957 raeburn 15129: =item B<$usec> Student's section in course
1.286 matthew 15130:
15131: =item B<$end> Unix time of the roles expiration
15132:
15133: =item B<$start> Unix time of the roles start date
15134:
15135: =item B<$forceid> If defined, allow $uid to be changed
15136:
15137: =item B<$desiredhome> server to use as home server for student
15138:
1.957 raeburn 15139: =item B<$email> Student's permanent e-mail address
15140:
15141: =item B<$type> Type of enrollment (auto or manual)
15142:
1.963 raeburn 15143: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15144:
15145: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15146:
1.963 raeburn 15147: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15148:
1.963 raeburn 15149: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15150:
1.1172.2.19 raeburn 15151: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15152:
15153: =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 15154:
1.286 matthew 15155: =back
1.297 matthew 15156:
15157: =item *
15158:
15159: modify_student_enrollment
15160:
1.1172.2.31 raeburn 15161: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15162: 'role.request.course' must be defined for this function to proceed.
15163:
15164: Inputs:
15165:
15166: =over 4
15167:
1.1172.2.31 raeburn 15168: =item $udom, student's domain
1.297 matthew 15169:
1.1172.2.31 raeburn 15170: =item $uname, student's name
1.297 matthew 15171:
1.1172.2.31 raeburn 15172: =item $uid, student's user id
1.297 matthew 15173:
1.1172.2.31 raeburn 15174: =item $first, student's first name
1.297 matthew 15175:
15176: =item $middle
15177:
15178: =item $last
15179:
15180: =item $gene
15181:
15182: =item $usec
15183:
15184: =item $end
15185:
15186: =item $start
15187:
1.957 raeburn 15188: =item $type
15189:
15190: =item $locktype
15191:
15192: =item $cid
15193:
15194: =item $selfenroll
15195:
15196: =item $context
15197:
1.1172.2.19 raeburn 15198: =item $credits, number of credits student will earn from this class
15199:
1.1172.2.76 raeburn 15200: =item $instsec, institutional course section code for student
15201:
1.297 matthew 15202: =back
15203:
1.191 harris41 15204:
15205: =item *
15206:
1.243 albertel 15207: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15208: custom role; give a custom role to a user for the level given by URL. Specify
15209: name and domain of role author, and role name
1.191 harris41 15210:
15211: =item *
15212:
1.243 albertel 15213: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15214:
15215: =item *
15216:
1.243 albertel 15217: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15218:
15219: =back
15220:
15221: =head2 Course Infomation
15222:
15223: =over 4
1.191 harris41 15224:
15225: =item *
15226:
1.1118 foxr 15227: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15228: specified course id, including all environment settings for the
15229: course, the description of the course will be in the hash under the
15230: key 'description'
1.191 harris41 15231:
1.1118 foxr 15232: $options is an optional parameter that if supplied is a hash reference that controls
15233: what how this function works. It has the following key/values:
15234:
15235: =over 4
15236:
15237: =item freshen_cache
15238:
15239: If defined, and the environment cache for the course is valid, it is
15240: returned in the returned hash.
15241:
15242: =item one_time
15243:
15244: If defined, the last cache time is set to _now_
15245:
15246: =item user
15247:
15248: If defined, the supplied username is used instead of the current user.
15249:
15250:
15251: =back
15252:
1.191 harris41 15253: =item *
15254:
1.624 albertel 15255: resdata($name,$domain,$type,@which) : request for current parameter
15256: setting for a specific $type, where $type is either 'course' or 'user',
15257: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15258: answers for 10 minutes.
1.243 albertel 15259:
1.877 foxr 15260: =item *
15261:
15262: get_courseresdata($courseid, $domain) : dump the entire course resource
15263: data base, returning a hash that is keyed by the resource name and has
15264: values that are the resource value. I believe that the timestamps and
15265: versions are also returned.
15266:
1.1172.2.31 raeburn 15267: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15268: supplemental content area. This routine caches the number of files for
15269: 10 minutes.
15270:
1.243 albertel 15271: =back
15272:
15273: =head2 Course Modification
15274:
15275: =over 4
1.191 harris41 15276:
15277: =item *
15278:
1.243 albertel 15279: writecoursepref($courseid,%prefs) : write preferences (environment
15280: database) for a course
1.191 harris41 15281:
15282: =item *
15283:
1.1011 raeburn 15284: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15285:
15286: =item *
15287:
1.1038 raeburn 15288: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15289:
1.1167 droeschl 15290: =item *
15291:
15292: is_course($courseid), is_course($cdom, $cnum)
15293:
15294: Accepts either a combined $courseid (in the form of domain_courseid) or the
15295: two component version $cdom, $cnum. It checks if the specified course exists.
15296:
15297: Returns:
15298: undef if the course doesn't exist, otherwise
15299: in scalar context the combined courseid.
15300: in list context the two components of the course identifier, domain and
15301: courseid.
15302:
1.243 albertel 15303: =back
15304:
1.1172.2.109 raeburn 15305: =head2 Bubblesheet Configuration
15306:
15307: =over 4
15308:
15309: =item *
15310:
15311: get_scantron_config($which)
15312:
15313: $which - the name of the configuration to parse from the file.
15314:
15315: Parses and returns the bubblesheet configuration line selected as a
15316: hash of configuration file fields.
15317:
15318:
15319: Returns:
15320: If the named configuration is not in the file, an empty
15321: hash is returned.
15322:
15323: a hash with the fields
15324: name - internal name for the this configuration setup
15325: description - text to display to operator that describes this config
15326: CODElocation - if 0 or the string 'none'
15327: - no CODE exists for this config
15328: if -1 || the string 'letter'
15329: - a CODE exists for this config and is
15330: a string of letters
15331: Unsupported value (but planned for future support)
15332: if a positive integer
15333: - The CODE exists as the first n items from
15334: the question section of the form
15335: if the string 'number'
15336: - The CODE exists for this config and is
15337: a string of numbers
15338: CODEstart - (only matter if a CODE exists) column in the line where
15339: the CODE starts
15340: CODElength - length of the CODE
15341: IDstart - column where the student/employee ID starts
15342: IDlength - length of the student/employee ID info
15343: Qstart - column where the information from the bubbled
15344: 'questions' start
15345: Qlength - number of columns comprising a single bubble line from
15346: the sheet. (usually either 1 or 10)
15347: Qon - either a single character representing the character used
15348: to signal a bubble was chosen in the positional setup, or
15349: the string 'letter' if the letter of the chosen bubble is
15350: in the final, or 'number' if a number representing the
15351: chosen bubble is in the file (1->A 0->J)
15352: Qoff - the character used to represent that a bubble was
15353: left blank
15354: PaperID - if the scanning process generates a unique number for each
15355: sheet scanned the column that this ID number starts in
15356: PaperIDlength - number of columns that comprise the unique ID number
15357: for the sheet of paper
15358: FirstName - column that the first name starts in
15359: FirstNameLength - number of columns that the first name spans
15360: LastName - column that the last name starts in
15361: LastNameLength - number of columns that the last name spans
15362: BubblesPerRow - number of bubbles available in each row used to
15363: bubble an answer. (If not specified, 10 assumed).
15364:
15365:
15366: =item *
15367:
15368: get_scantronformat_file($cdom)
15369:
15370: $cdom - the course's domain (optional); if not supplied, uses
15371: domain for current $env{'request.course.id'}.
15372:
15373: Returns an array containing lines from the scantron format file for
15374: the domain of the course.
15375:
15376: If a url for a custom.tab file is listed in domain's configuration.db,
15377: lines are from this file.
15378:
15379: Otherwise, if a default.tab has been published in RES space by the
15380: domainconfig user, lines are from this file.
15381:
15382: Otherwise, fall back to getting lines from the legacy file on the
15383: local server: /home/httpd/lonTabs/default_scantronformat.tab
15384:
15385: =back
15386:
1.243 albertel 15387: =head2 Resource Subroutines
15388:
15389: =over 4
1.191 harris41 15390:
15391: =item *
15392:
1.243 albertel 15393: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15394:
15395: =item *
15396:
1.243 albertel 15397: repcopy($filename) : subscribes to the requested file, and attempts to
15398: replicate from the owning library server, Might return
1.607 raeburn 15399: 'unavailable', 'not_found', 'forbidden', 'ok', or
15400: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15401: resource. Expects the local filesystem pathname
15402: (/home/httpd/html/res/....)
15403:
15404: =back
15405:
15406: =head2 Resource Information
15407:
15408: =over 4
1.191 harris41 15409:
15410: =item *
15411:
1.1172.2.28 raeburn 15412: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15413: and returns the value of a variety of different possible values,
15414: $varname should be a request string, and the other parameters can be
15415: used to specify who and what one is asking about. Ordinarily, $cid
15416: does not need to be specified, as it is retrived from
15417: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15418: within lonuserstate::loadmap() when initializing a course, before
15419: $env{'request.course.id'} has been set, so it needs to be provided
15420: in that one case.
1.243 albertel 15421:
15422: Possible values for $varname are environment.lastname (or other item
15423: from the envirnment hash), user.name (or someother aspect about the
15424: user), resource.0.maxtries (or some other part and parameter of a
15425: resource)
1.204 albertel 15426:
15427: =item *
15428:
1.243 albertel 15429: directcondval($number) : get current value of a condition; reads from a state
15430: string
1.204 albertel 15431:
15432: =item *
15433:
1.243 albertel 15434: condval($condidx) : value of condition index based on state
1.204 albertel 15435:
15436: =item *
15437:
1.243 albertel 15438: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15439: resource's metadata, $what should be either a specific key, or either
15440: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15441: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15442:
15443: this function automatically caches all requests
1.191 harris41 15444:
15445: =item *
15446:
1.243 albertel 15447: metadata_query($query,$custom,$customshow) : make a metadata query against the
15448: network of library servers; returns file handle of where SQL and regex results
15449: will be stored for query
1.191 harris41 15450:
15451: =item *
15452:
1.1172.2.66 raeburn 15453: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15454: return symbolic list entry (all arguments optional).
15455:
15456: Args: filename is the filename (including path) for the file for which a symb
15457: is required; donotrecurse, if true will prevent calls to allowed() being made
15458: to check access status if more than one resource was found in the bighash
15459: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15460: a randompick); ignorecachednull, if true will prevent a symb of '' being
15461: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15462: cause possible symbs to be checked to determine if they are subject to content
15463: blocking, if so they will not be included as possible symbs; possibles is a
15464: ref to a hash, which, as a side effect, will be populated with all possible
15465: symbs (content blocking not tested).
15466:
1.243 albertel 15467: returns the data handle
1.191 harris41 15468:
15469: =item *
15470:
1.1172.2.17 raeburn 15471: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15472: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15473: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15474: on failure, user must be in a course, as it assumes the existence of
15475: the course initial hash, and uses $env('request.course.id'}. The third
15476: arg is an optional reference to a scalar. If this arg is passed in the
15477: call to symbverify, it will be set to 1 if the symb has been set to be
15478: encrypted; otherwise it will be null.
1.243 albertel 15479:
1.191 harris41 15480: =item *
15481:
1.243 albertel 15482: symbclean($symb) : removes versions numbers from a symb, returns the
15483: cleaned symb
1.191 harris41 15484:
15485: =item *
15486:
1.243 albertel 15487: is_on_map($uri) : checks if the $uri is somewhere on the current
15488: course map, user must be in a course for it to work.
1.191 harris41 15489:
15490: =item *
15491:
1.243 albertel 15492: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15493:
15494: =item *
15495:
1.243 albertel 15496: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15497: a random seed, all arguments are optional, if they aren't sent it uses the
15498: environment to derive them. Note: if symb isn't sent and it can't get one
15499: from &symbread it will use the current time as its return value
1.191 harris41 15500:
15501: =item *
15502:
1.243 albertel 15503: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15504: unfakeable, receipt
1.191 harris41 15505:
15506: =item *
15507:
1.620 albertel 15508: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15509:
15510: =item *
15511:
1.243 albertel 15512: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15513:
15514: =item *
15515:
1.243 albertel 15516: 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 15517:
15518: =item *
15519:
1.243 albertel 15520: 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 15521:
15522: =item *
15523:
1.243 albertel 15524: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15525:
15526: =item *
15527:
1.243 albertel 15528: devalidate($symb) : devalidate temporary spreadsheet calculations,
15529: forcing spreadsheet to reevaluate the resource scores next time.
15530:
1.1172.2.13 raeburn 15531: =item *
15532:
15533: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15534: when viewing in course context.
15535:
15536: input: six args -- filename (decluttered), course number, course domain,
15537: url, symb (if registered) and group (if this is a
15538: group item -- e.g., bulletin board, group page etc.).
15539:
15540: output: array of five scalars --
15541: $cfile -- url for file editing if editable on current server
15542: $home -- homeserver of resource (i.e., for author if published,
15543: or course if uploaded.).
15544: $switchserver -- 1 if server switch will be needed.
15545: $forceedit -- 1 if icon/link should be to go to edit mode
15546: $forceview -- 1 if icon/link should be to go to view mode
15547:
15548: =item *
15549:
15550: is_course_upload($file,$cnum,$cdom)
15551:
15552: Used in course context to determine if current file was uploaded to
15553: the course (i.e., would be found in /userfiles/docs on the course's
15554: homeserver.
15555:
15556: input: 3 args -- filename (decluttered), course number and course domain.
15557: output: boolean -- 1 if file was uploaded.
15558:
1.243 albertel 15559: =back
15560:
15561: =head2 Storing/Retreiving Data
15562:
15563: =over 4
1.191 harris41 15564:
15565: =item *
15566:
1.1172.2.64 raeburn 15567: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15568: permanently for this url; hashref needs to be given and should be a \%hashname;
15569: the remaining args aren't required and if they aren't passed or are '' they will
15570: be derived from the env (with the exception of $laststore, which is an
15571: optional arg used when a user's submission is stored in grading).
15572: $laststore is $version=$timestamp, where $version is the most recent version
15573: number retrieved for the corresponding $symb in the $namespace db file, and
15574: $timestamp is the timestamp for that transaction (UNIX time).
15575: $laststore is currently only passed when cstore() is called by
15576: structuretags::finalize_storage().
1.191 harris41 15577:
15578: =item *
15579:
1.1172.2.64 raeburn 15580: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15581: but uses critical subroutine
1.191 harris41 15582:
15583: =item *
15584:
1.243 albertel 15585: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15586: all args are optional
1.191 harris41 15587:
15588: =item *
15589:
1.717 albertel 15590: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15591: dumps the complete (or key matching regexp) namespace into a hash
15592: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15593: normally &store()ed into
15594:
15595: $range should be either an integer '100' (give me the first 100
15596: matching records)
15597: or be two integers sperated by a - with no spaces
15598: '30-50' (give me the 30th through the 50th matching
15599: records)
15600:
15601:
15602: =item *
15603:
1.1172.2.59 raeburn 15604: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15605: replaces a &store() version of data with a replacement set of data
15606: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15607: reference. If $tolog is true, the transaction is logged in the courselog
15608: with an action=PUTSTORE.
1.717 albertel 15609:
15610: =item *
15611:
1.243 albertel 15612: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15613: works very similar to store/cstore, but all data is stored in a
15614: temporary location and can be reset using tmpreset, $storehash should
15615: be a hash reference, returns nothing on success
1.191 harris41 15616:
15617: =item *
15618:
1.243 albertel 15619: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15620: similar to restore, but all data is stored in a temporary location and
15621: can be reset using tmpreset. Returns a hash of values on success,
15622: error string otherwise.
1.191 harris41 15623:
15624: =item *
15625:
1.243 albertel 15626: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15627: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15628:
15629: =item *
15630:
1.243 albertel 15631: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15632: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15633:
15634: =item *
15635:
1.243 albertel 15636: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15637: namesp ($udom and $uname are optional)
1.191 harris41 15638:
15639: =item *
15640:
1.702 albertel 15641: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15642: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15643: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15644:
1.702 albertel 15645: $range should be either an integer '100' (give me the first 100
15646: matching records)
15647: or be two integers sperated by a - with no spaces
15648: '30-50' (give me the 30th through the 50th matching
15649: records)
1.449 matthew 15650: =item *
15651:
15652: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15653: $store can be a scalar, an array reference, or if the amount to be
15654: incremented is > 1, a hash reference.
15655:
15656: ($udom and $uname are optional)
1.191 harris41 15657:
15658: =item *
15659:
1.243 albertel 15660: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15661: ($udom and $uname are optional)
1.191 harris41 15662:
15663: =item *
15664:
1.243 albertel 15665: cput($namespace,$storehash,$udom,$uname) : critical put
15666: ($udom and $uname are optional)
1.191 harris41 15667:
15668: =item *
15669:
1.748 albertel 15670: newput($namespace,$storehash,$udom,$uname) :
15671:
15672: Attempts to store the items in the $storehash, but only if they don't
15673: currently exist, if this succeeds you can be certain that you have
15674: successfully created a new key value pair in the $namespace db.
15675:
15676:
15677: Args:
15678: $namespace: name of database to store values to
15679: $storehash: hashref to store to the db
15680: $udom: (optional) domain of user containing the db
15681: $uname: (optional) name of user caontaining the db
15682:
15683: Returns:
15684: 'ok' -> succeeded in storing all keys of $storehash
15685: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15686: least <key> already existed in the db (other
15687: requested keys may also already exist)
1.967 bisitz 15688: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15689: 'con_lost' -> unable to contact request server
15690: 'refused' -> action was not allowed by remote machine
15691:
15692:
15693: =item *
15694:
1.243 albertel 15695: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15696: reference filled in from namesp (encrypts the return communication)
15697: ($udom and $uname are optional)
1.191 harris41 15698:
15699: =item *
15700:
1.243 albertel 15701: log($udom,$name,$home,$message) : write to permanent log for user; use
15702: critical subroutine
15703:
1.806 raeburn 15704: =item *
15705:
1.860 raeburn 15706: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15707: array reference filled in from namespace found in domain level on either
15708: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15709:
15710: =item *
15711:
1.860 raeburn 15712: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15713: domain level either on specified domain server ($uhome) or primary domain
15714: server ($udom and $uhome are optional)
1.806 raeburn 15715:
1.943 raeburn 15716: =item *
15717:
1.1172.2.35 raeburn 15718: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15719: for: authentication, language, quotas, timezone, date locale, and portal URL in
15720: the target domain.
15721:
15722: May also include additional key => value pairs for the following groups:
15723:
15724: =over
15725:
15726: =item
15727: disk quotas (MB allocated by default to portfolios and authoring spaces).
15728:
15729: =over
15730:
15731: =item defaultquota, authorquota
15732:
15733: =back
15734:
15735: =item
15736: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15737: portfolio for users).
15738:
15739: =over
15740:
15741: =item
15742: aboutme, blog, webdav, portfolio
15743:
15744: =back
15745:
15746: =item
15747: requestcourses: ability to request courses, and how requests are processed.
15748:
15749: =over
15750:
15751: =item
1.1172.2.37 raeburn 15752: official, unofficial, community, textbook
1.1172.2.35 raeburn 15753:
15754: =back
15755:
15756: =item
15757: inststatus: types of institutional affiliation, and order in which they are displayed.
15758:
15759: =over
15760:
15761: =item
1.1172.2.44 raeburn 15762: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15763:
15764: =back
15765:
15766: =item
15767: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15768: for course's uploaded content.
15769:
15770: =over
15771:
15772: =item
1.1172.2.68 raeburn 15773: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15774: communityquota, textbookquota
1.1172.2.35 raeburn 15775:
15776: =back
15777:
15778: =item
15779: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15780: on your servers.
15781:
15782: =over
15783:
15784: =item
15785: remotesessions, hostedsessions
15786:
15787: =back
15788:
15789: =back
15790:
15791: In cases where a domain coordinator has never used the "Set Domain Configuration"
15792: utility to create a configuration.db file on a domain's primary library server
15793: only the following domain defaults: auth_def, auth_arg_def, lang_def
15794: -- corresponding values are authentication type (internal, krb4, krb5,
15795: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15796: will be available. Values are retrieved from cache (if current), unless the
15797: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15798: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15799:
15800: Typical usage:
1.943 raeburn 15801:
1.1172.2.35 raeburn 15802: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15803:
1.243 albertel 15804: =back
15805:
15806: =head2 Network Status Functions
15807:
15808: =over 4
1.191 harris41 15809:
15810: =item *
15811:
1.1137 raeburn 15812: dirlist() : return directory list based on URI (first arg).
15813:
15814: Inputs: 1 required, 5 optional.
15815:
15816: =over
15817:
15818: =item
15819: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15820:
15821: =item
15822: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15823:
15824: =item
15825: $username - username of user/course to be listed. Extracted from $uri if absent.
15826:
15827: =item
15828: $getpropath - boolean: 1 if prepend path using &propath().
15829:
15830: =item
15831: $getuserdir - boolean: 1 if prepend path for "userfiles".
15832:
15833: =item
15834: $alternateRoot - path to prepend in place of path from $uri.
15835:
15836: =back
15837:
15838: Returns: Array of up to two items.
15839:
15840: =over
15841:
15842: a reference to an array of files/subdirectories
15843:
15844: =over
15845:
15846: Each element in the array of files/subdirectories is a & separated list of
15847: item name and the result of running stat on the item. If dirlist was requested
15848: for a file instead of a directory, the item name will be ''. For a directory
15849: listing, if the item is a metadata file, the element will end &N&M
15850: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15851: default copyright set (1).
15852:
15853: =back
15854:
15855: a scalar containing error condition (if encountered).
15856:
15857: =over
15858:
15859: =item
15860: no_host (no homeserver identified for $username:$domain).
15861:
15862: =item
15863: no_such_host (server contacted for listing not identified as valid host).
15864:
15865: =item
15866: con_lost (connection to remote server failed).
15867:
15868: =item
15869: refused (invalid $username:$domain received on lond side).
15870:
15871: =item
15872: no_such_dir (directory at specified path on lond side does not exist).
15873:
15874: =item
15875: empty (directory at specified path on lond side is empty).
15876:
15877: =over
15878:
15879: This is currently not encountered because the &ls3, &ls2,
15880: &ls (_handler) routines on the lond side do not filter out
15881: . and .. from a directory listing.
15882:
15883: =back
15884:
15885: =back
15886:
15887: =back
1.191 harris41 15888:
15889: =item *
15890:
1.243 albertel 15891: spareserver() : find server with least workload from spare.tab
15892:
1.986 foxr 15893:
15894: =item *
15895:
15896: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15897: if there is no corresponding loncapa host.
15898:
1.243 albertel 15899: =back
15900:
1.986 foxr 15901:
1.243 albertel 15902: =head2 Apache Request
15903:
15904: =over 4
1.191 harris41 15905:
15906: =item *
15907:
1.243 albertel 15908: ssi($url,%hash) : server side include, does a complete request cycle on url to
15909: localhost, posts hash
15910:
15911: =back
15912:
15913: =head2 Data to String to Data
15914:
15915: =over 4
1.191 harris41 15916:
15917: =item *
15918:
1.243 albertel 15919: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15920: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15921:
15922: =item *
15923:
1.243 albertel 15924: hashref2str($hashref) : convert a hashref into a string complete with
15925: escaping and '=' and '&' separators, supports elements that are
15926: arrayrefs and hashrefs
1.191 harris41 15927:
15928: =item *
15929:
1.243 albertel 15930: arrayref2str($arrayref) : convert an arrayref into a string complete
15931: with escaping and '&' separators, supports elements that are arrayrefs
15932: and hashrefs
1.191 harris41 15933:
15934: =item *
15935:
1.243 albertel 15936: str2hash($string) : convert string to hash using unescaping and
15937: splitting on '=' and '&', supports elements that are arrayrefs and
15938: hashrefs
1.191 harris41 15939:
15940: =item *
15941:
1.243 albertel 15942: str2array($string) : convert string to hash using unescaping and
15943: splitting on '&', supports elements that are arrayrefs and hashrefs
15944:
15945: =back
15946:
15947: =head2 Logging Routines
15948:
15949:
15950: These routines allow one to make log messages in the lonnet.log and
15951: lonnet.perm logfiles.
1.191 harris41 15952:
1.1119 foxr 15953: =over 4
15954:
1.191 harris41 15955: =item *
15956:
1.243 albertel 15957: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15958:
15959: =item *
15960:
1.243 albertel 15961: logthis() : append message to the normal lonnet.log file, it gets
15962: preiodically rolled over and deleted.
1.191 harris41 15963:
15964: =item *
15965:
1.243 albertel 15966: logperm() : append a permanent message to lonnet.perm.log, this log
15967: file never gets deleted by any automated portion of the system, only
15968: messages of critical importance should go in here.
15969:
1.1119 foxr 15970:
1.243 albertel 15971: =back
15972:
15973: =head2 General File Helper Routines
15974:
15975: =over 4
1.191 harris41 15976:
15977: =item *
15978:
1.481 raeburn 15979: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15980: (a) files in /uploaded
15981: (i) If a local copy of the file exists -
15982: compares modification date of local copy with last-modified date for
15983: definitive version stored on home server for course. If local copy is
15984: stale, requests a new version from the home server and stores it.
15985: If the original has been removed from the home server, then local copy
15986: is unlinked.
15987: (ii) If local copy does not exist -
15988: requests the file from the home server and stores it.
15989:
15990: If $caller is 'uploadrep':
15991: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15992: for request for files originally uploaded via DOCS.
15993: - returns 'ok' if fresh local copy now available, -1 otherwise.
15994:
15995: Otherwise:
15996: This indicates a call from the content generation phase of the request.
15997: - returns the entire contents of the file or -1.
15998:
15999: (b) files in /res
16000: - returns the entire contents of a file or -1;
16001: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16002:
1.712 albertel 16003:
16004: =item *
16005:
16006: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16007: reference
16008:
16009: returns either a stat() list of data about the file or an empty list
16010: if the file doesn't exist or couldn't find out about it (connection
16011: problems or user unknown)
16012:
1.191 harris41 16013: =item *
16014:
1.243 albertel 16015: filelocation($dir,$file) : returns file system location of a file
16016: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16017: directory that relative $file lookups are to looked in ($dir of /a/dir
16018: and a file of ../bob will become /a/bob)
1.191 harris41 16019:
16020: =item *
16021:
16022: hreflocation($dir,$file) : returns file system location or a URL; same as
16023: filelocation except for hrefs
16024:
16025: =item *
16026:
1.1172.2.49 raeburn 16027: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16028: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16029:
1.243 albertel 16030: =back
16031:
1.608 albertel 16032: =head2 Usererfile file routines (/uploaded*)
16033:
16034: =over 4
16035:
16036: =item *
16037:
16038: userfileupload(): main rotine for putting a file in a user or course's
16039: filespace, arguments are,
16040:
1.620 albertel 16041: formname - required - this is the name of the element in $env where the
1.608 albertel 16042: filename, and the contents of the file to create/modifed exist
1.620 albertel 16043: the filename is in $env{'form.'.$formname.'.filename'} and the
16044: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16045: context - if coursedoc, store the file in the course of the active role
16046: of the current user;
16047: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16048: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16049: subdir - required - subdirectory to put the file in under ../userfiles/
16050: if undefined, it will be placed in "unknown"
16051:
16052: (This routine calls clean_filename() to remove any dangerous
16053: characters from the filename, and then calls finuserfileupload() to
16054: complete the transaction)
16055:
16056: returns either the url of the uploaded file (/uploaded/....) if successful
16057: and /adm/notfound.html if unsuccessful
16058:
16059: =item *
16060:
16061: clean_filename(): routine for cleaing a filename up for storage in
16062: userfile space, argument is:
16063:
16064: filename - proposed filename
16065:
16066: returns: the new clean filename
16067:
16068: =item *
16069:
1.1090 raeburn 16070: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16071: userspace, probably shouldn't be called directly
16072:
16073: docuname: username or courseid of destination for the file
16074: docudom: domain of user/course of destination for the file
16075: formname: same as for userfileupload()
1.1090 raeburn 16076: fname: filename (including subdirectories) for the file
16077: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16078: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16079: allfiles: reference to hash used to store objects found by parser
16080: codebase: reference to hash used for codebases of java objects found by parser
16081: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16082: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16083: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16084: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16085: context: if 'overwrite', will move the uploaded file from its temporary location to
16086: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16087: mimetype: reference to scalar to accommodate mime type determined
16088: from File::MMagic if $parser = parse.
1.608 albertel 16089:
16090: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16091: and /adm/notfound.html if unsuccessful (or an error message if context
16092: was 'overwrite').
16093:
1.608 albertel 16094:
16095: =item *
16096:
16097: renameuserfile(): renames an existing userfile to a new name
16098:
16099: Args:
16100: docuname: username or courseid of destination for the file
16101: docudom: domain of user/course of destination for the file
16102: old: current file name (including any subdirs under userfiles)
16103: new: desired file name (including any subdirs under userfiles)
16104:
16105: =item *
16106:
16107: mkdiruserfile(): creates a directory is a userfiles dir
16108:
16109: Args:
16110: docuname: username or courseid of destination for the file
16111: docudom: domain of user/course of destination for the file
16112: dir: dir to create (including any subdirs under userfiles)
16113:
16114: =item *
16115:
16116: removeuserfile(): removes a file that exists in userfiles
16117:
16118: Args:
16119: docuname: username or courseid of destination for the file
16120: docudom: domain of user/course of destination for the file
16121: fname: filname to delete (including any subdirs under userfiles)
16122:
16123: =item *
16124:
16125: removeuploadedurl(): convience function for removeuserfile()
16126:
16127: Args:
16128: url: a full /uploaded/... url to delete
16129:
1.747 albertel 16130: =item *
16131:
16132: get_portfile_permissions():
16133: Args:
16134: domain: domain of user or course contain the portfolio files
16135: user: name of user or num of course contain the portfolio files
16136: Returns:
16137: hashref of a dump of the proper file_permissions.db
16138:
16139:
16140: =item *
16141:
16142: get_access_controls():
16143:
16144: Args:
16145: current_permissions: the hash ref returned from get_portfile_permissions()
16146: group: (optional) the group you want the files associated with
16147: file: (optional) the file you want access info on
16148:
16149: Returns:
1.749 raeburn 16150: a hash (keys are file names) of hashes containing
16151: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16152: values are XML containing access control settings (see below)
1.747 albertel 16153:
16154: Internal notes:
16155:
1.749 raeburn 16156: access controls are stored in file_permissions.db as key=value pairs.
16157: key -> path to file/file_name\0uniqueID:scope_end_start
16158: where scope -> public,guest,course,group,domains or users.
16159: end -> UNIX time for end of access (0 -> no end date)
16160: start -> UNIX time for start of access
16161:
16162: value -> XML description of access control
16163: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16164: <start></start>
16165: <end></end>
16166:
16167: <password></password> for scope type = guest
16168:
16169: <domain></domain> for scope type = course or group
16170: <number></number>
16171: <roles id="">
16172: <role></role>
16173: <access></access>
16174: <section></section>
16175: <group></group>
16176: </roles>
16177:
16178: <dom></dom> for scope type = domains
16179:
16180: <users> for scope type = users
16181: <user>
16182: <uname></uname>
16183: <udom></udom>
16184: </user>
16185: </users>
16186: </scope>
16187:
16188: Access data is also aggregated for each file in an additional key=value pair:
16189: key -> path to file/file_name\0accesscontrol
16190: value -> reference to hash
16191: hash contains key = value pairs
16192: where key = uniqueID:scope_end_start
16193: value = UNIX time record was last updated
16194:
16195: Used to improve speed of look-ups of access controls for each file.
16196:
16197: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16198:
1.1172.2.13 raeburn 16199: =item *
16200:
1.749 raeburn 16201: modify_access_controls():
16202:
16203: Modifies access controls for a portfolio file
16204: Args
16205: 1. file name
16206: 2. reference to hash of required changes,
16207: 3. domain
16208: 4. username
16209: where domain,username are the domain of the portfolio owner
16210: (either a user or a course)
16211:
16212: Returns:
16213: 1. result of additions or updates ('ok' or 'error', with error message).
16214: 2. result of deletions ('ok' or 'error', with error message).
16215: 3. reference to hash of any new or updated access controls.
16216: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16217: key = integer (inbound ID)
1.1172.2.13 raeburn 16218: value = uniqueID
16219:
16220: =item *
16221:
16222: get_timebased_id():
16223:
16224: Attempts to get a unique timestamp-based suffix for use with items added to a
16225: course via the Course Editor (e.g., folders, composite pages,
16226: group bulletin boards).
16227:
16228: Args: (first three required; six others optional)
16229:
16230: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16231: docssequence, or name of group
16232:
16233: 2. keyid (alphanumeric): name of temporary locking key in hash,
16234: e.g., num, boardids
16235:
16236: 3. namespace: name of gdbm file used to store suffixes already assigned;
16237: file will be named nohist_namespace.db
16238:
16239: 4. cdom: domain of course; default is current course domain from %env
16240:
16241: 5. cnum: course number; default is current course number from %env
16242:
16243: 6. idtype: set to concat if an additional digit is to be appended to the
16244: unix timestamp to form the suffix, if the plain timestamp is already
16245: in use. Default is to not do this, but simply increment the unix
16246: timestamp by 1 until a unique key is obtained.
16247:
16248: 7. who: holder of locking key; defaults to user:domain for user.
16249:
16250: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16251: retrying); default is 3.
16252:
16253: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16254:
16255: Returns:
16256:
16257: 1. suffix obtained (numeric)
16258:
16259: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16260:
16261: 3. error: contains (localized) error message if an error occurred.
16262:
1.747 albertel 16263:
1.608 albertel 16264: =back
16265:
1.243 albertel 16266: =head2 HTTP Helper Routines
16267:
16268: =over 4
16269:
1.191 harris41 16270: =item *
16271:
16272: escape() : unpack non-word characters into CGI-compatible hex codes
16273:
16274: =item *
16275:
16276: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16277:
1.243 albertel 16278: =back
16279:
16280: =head1 PRIVATE SUBROUTINES
16281:
16282: =head2 Underlying communication routines (Shouldn't call)
16283:
16284: =over 4
16285:
16286: =item *
16287:
16288: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16289:
16290: =item *
16291:
16292: reply() : uses subreply to send a message to remote machine, logs all failures
16293:
16294: =item *
16295:
16296: critical() : passes a critical message to another server; if cannot
16297: get through then place message in connection buffer directory and
16298: returns con_delayed, if incapable of saving message, returns
16299: con_failed
16300:
16301: =item *
16302:
16303: reconlonc() : tries to reconnect lonc client processes.
16304:
16305: =back
16306:
16307: =head2 Resource Access Logging
16308:
16309: =over 4
16310:
16311: =item *
16312:
16313: flushcourselogs() : flush (save) buffer logs and access logs
16314:
16315: =item *
16316:
16317: courselog($what) : save message for course in hash
16318:
16319: =item *
16320:
16321: courseacclog($what) : save message for course using &courselog(). Perform
16322: special processing for specific resource types (problems, exams, quizzes, etc).
16323:
1.191 harris41 16324: =item *
16325:
16326: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16327: as a PerlChildExitHandler
1.243 albertel 16328:
16329: =back
16330:
16331: =head2 Other
16332:
16333: =over 4
16334:
16335: =item *
16336:
16337: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16338:
16339: =back
16340:
16341: =cut
1.877 foxr 16342:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>