Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.146.2.21
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.146. .21(raeb 4:-24): # $Id: lonnet.pm,v 1.1172.2.146.2.20 2024/03/29 17:58:49 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.146. .1(raebu 130:22): 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.1172.2.146. .13(raeb 368:-23): sub sign_lti {
369:-23): my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
370:-23): my $chome;
371:-23): if (&domain($cdom) ne '') {
372:-23): if ($crsdef) {
373:-23): $chome = &homeserver($cnum,$cdom);
374:-23): } else {
375:-23): $chome = &domain($cdom,'primary');
376:-23): }
377:-23): }
378:-23): if ($cdom && $chome && ($chome ne 'no_host')) {
379:-23): if ((ref($paramsref) eq 'HASH') &&
380:-23): (ref($inforef) eq 'HASH')) {
381:-23): my $rep;
382:-23): if (grep { $_ eq $chome } ¤t_machine_ids()) {
383:-23): # domain information is hosted on this machine
384:-23): $rep =
385:-23): &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
386:-23): $context,$url,$ltinum,$keynum,
387:-23): $perlvar{'lonVersion'},
388:-23): $paramsref,$inforef);
389:-23): if (ref($rep) eq 'HASH') {
390:-23): return ('ok',$rep);
391:-23): }
392:-23): } else {
393:-23): my ($escurl,$params,$info);
394:-23): $escurl = &escape($url);
395:-23): if (ref($paramsref) eq 'HASH') {
396:-23): $params = &freeze_escape($paramsref);
397:-23): }
398:-23): if (ref($inforef) eq 'HASH') {
399:-23): $info = &freeze_escape($inforef);
400:-23): }
401:-23): $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
402:-23): }
403:-23): if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
404:-23): return ();
405:-23): } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
406:-23): ($inforef->{'respfmt'} eq 'to_authorization_header')) {
407:-23): return ('ok',$rep);
408:-23): } else {
409:-23): my %returnhash;
410:-23): foreach my $item (split(/\&/,$rep)) {
411:-23): my ($name,$value)=split(/\=/,$item);
412:-23): $returnhash{&unescape($name)}=&thaw_unescape($value);
413:-23): }
414:-23): return('ok',\%returnhash);
415:-23): }
416:-23): } else {
417:-23): return ();
418:-23): }
419:-23): } else {
420:-23): return ();
421:-23): &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
422:-23): }
423:-23): }
424:-23):
1.1 albertel 425: # -------------------------------------------------- Non-critical communication
426: sub subreply {
427: my ($cmd,$server)=@_;
1.838 albertel 428: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 429: #
430: # With loncnew process trimming, there's a timing hole between lonc server
431: # process exit and the master server picking up the listen on the AF_UNIX
432: # socket. In that time interval, a lock file will exist:
433:
434: my $lockfile=$peerfile.".lock";
435: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 436: sleep(0.1);
1.549 foxr 437: }
438: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 439: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 440: #
1.550 foxr 441: # We'll give the connection a few tries before abandoning it. If
442: # connection is not possible, we'll con_lost back to the client.
443: #
444: my $client;
445: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
446: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
447: Type => SOCK_STREAM,
448: Timeout => 10);
1.869 albertel 449: if ($client) {
1.550 foxr 450: last; # Connected!
1.850 albertel 451: } else {
1.853 albertel 452: &create_connection(&hostname($server),$server);
1.550 foxr 453: }
1.1172.2.79 raeburn 454: sleep(0.1); # Try again later if failed connection.
1.550 foxr 455: }
456: my $answer;
457: if ($client) {
1.704 albertel 458: print $client "sethost:$server:$cmd\n";
1.550 foxr 459: $answer=<$client>;
460: if (!$answer) { $answer="con_lost"; }
461: chomp($answer);
462: } else {
463: $answer = 'con_lost'; # Failed connection.
464: }
1.1 albertel 465: return $answer;
466: }
467:
468: sub reply {
469: my ($cmd,$server)=@_;
1.838 albertel 470: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 471: my $answer=subreply($cmd,$server);
1.65 www 472: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 473: my $logged = $cmd;
474: if ($cmd =~ /^encrypt:([^:]+):/) {
475: my $subcmd = $1;
476: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
477: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146. .13(raeb 478:-23): ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
479:-23): ($subcmd eq 'put')) {
1.1172.2.111 raeburn 480: (undef,undef,my @rest) = split(/:/,$cmd);
481: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
482: splice(@rest,2,1,'Hidden');
483: } elsif ($subcmd eq 'passwd') {
484: splice(@rest,2,2,('Hidden','Hidden'));
485: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146. .13(raeb 486:-23): ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1172.2.111 raeburn 487: splice(@rest,3,1,'Hidden');
488: }
489: $logged = join(':',('encrypt:'.$subcmd,@rest));
490: }
491: }
492: &logthis("<font color=\"blue\">WARNING:".
493: " $logged to $server returned $answer</font>");
1.12 www 494: }
1.1 albertel 495: return $answer;
496: }
497:
498: # ----------------------------------------------------------- Send USR1 to lonc
499:
500: sub reconlonc {
1.891 albertel 501: my ($lonid) = @_;
502: if ($lonid) {
1.1172.2.72 raeburn 503: my $hostname = &hostname($lonid);
1.891 albertel 504: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
505: if ($hostname && -e $peerfile) {
506: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
507: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
508: Type => SOCK_STREAM,
509: Timeout => 10);
510: if ($client) {
511: print $client ("reset_retries\n");
512: my $answer=<$client>;
513: #reset just this one.
514: }
515: }
516: return;
517: }
518:
1.836 www 519: &logthis("Trying to reconnect lonc");
1.1 albertel 520: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 521: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 522: my $loncpid=<$fh>;
523: chomp($loncpid);
524: if (kill 0 => $loncpid) {
525: &logthis("lonc at pid $loncpid responding, sending USR1");
526: kill USR1 => $loncpid;
527: sleep 1;
1.836 www 528: } else {
1.12 www 529: &logthis(
1.672 albertel 530: "<font color=\"blue\">WARNING:".
1.12 www 531: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 532: }
533: } else {
1.836 www 534: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 535: }
536: }
537:
538: # ------------------------------------------------------ Critical communication
1.12 www 539:
1.1 albertel 540: sub critical {
541: my ($cmd,$server)=@_;
1.838 albertel 542: unless (&hostname($server)) {
1.672 albertel 543: &logthis("<font color=\"blue\">WARNING:".
1.89 www 544: " Critical message to unknown server ($server)</font>");
545: return 'no_such_host';
546: }
1.1 albertel 547: my $answer=reply($cmd,$server);
548: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 549: &reconlonc($server);
1.589 albertel 550: my $answer=reply($cmd,$server);
1.1 albertel 551: if ($answer eq 'con_lost') {
552: my $now=time;
553: my $middlename=$cmd;
1.5 www 554: $middlename=substr($middlename,0,16);
1.1 albertel 555: $middlename=~s/\W//g;
556: my $dfilename=
1.305 www 557: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
558: $dumpcount++;
1.1 albertel 559: {
1.448 albertel 560: my $dfh;
1.1172.2.96 raeburn 561: if (open($dfh,">",$dfilename)) {
1.448 albertel 562: print $dfh "$cmd\n";
563: close($dfh);
564: }
1.1 albertel 565: }
1.1172.2.79 raeburn 566: sleep 1;
1.1 albertel 567: my $wcmd='';
568: {
1.448 albertel 569: my $dfh;
1.1172.2.96 raeburn 570: if (open($dfh,"<",$dfilename)) {
1.448 albertel 571: $wcmd=<$dfh>;
572: close($dfh);
573: }
1.1 albertel 574: }
575: chomp($wcmd);
1.7 www 576: if ($wcmd eq $cmd) {
1.672 albertel 577: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 578: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 579: &logperm("D:$server:$cmd");
580: return 'con_delayed';
581: } else {
1.672 albertel 582: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 583: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 584: &logperm("F:$server:$cmd");
585: return 'con_failed';
586: }
587: }
588: }
589: return $answer;
1.405 albertel 590: }
591:
1.755 albertel 592: # ------------------------------------------- check if return value is an error
593:
594: sub error {
595: my ($result) = @_;
1.756 albertel 596: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 597: if ($2 == 2) { return undef; }
598: return $1;
599: }
600: return undef;
601: }
602:
1.783 albertel 603: sub convert_and_load_session_env {
604: my ($lonidsdir,$handle)=@_;
605: my @profile;
606: {
1.917 albertel 607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: if (!$opened) {
1.915 albertel 609: return 0;
610: }
1.783 albertel 611: flock($idf,LOCK_SH);
612: @profile=<$idf>;
613: close($idf);
614: }
615: my %temp_env;
616: foreach my $line (@profile) {
1.786 albertel 617: if ($line !~ m/=/) {
618: return 0;
619: }
1.783 albertel 620: chomp($line);
621: my ($envname,$envvalue)=split(/=/,$line,2);
622: $temp_env{&unescape($envname)} = &unescape($envvalue);
623: }
624: unlink("$lonidsdir/$handle.id");
625: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
626: 0640)) {
627: %disk_env = %temp_env;
628: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
629: untie(%disk_env);
630: }
1.786 albertel 631: return 1;
1.783 albertel 632: }
633:
1.374 www 634: # ------------------------------------------- Transfer profile into environment
1.780 albertel 635: my $env_loaded;
636: sub transfer_profile_to_env {
1.788 albertel 637: my ($lonidsdir,$handle,$force_transfer) = @_;
638: if (!$force_transfer && $env_loaded) { return; }
1.374 www 639:
1.720 albertel 640: if (!defined($lonidsdir)) {
641: $lonidsdir = $perlvar{'lonIDsDir'};
642: }
643: if (!defined($handle)) {
644: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
645: }
646:
1.786 albertel 647: my $convert;
648: {
1.917 albertel 649: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
650: if (!$opened) {
1.915 albertel 651: return;
652: }
1.786 albertel 653: flock($idf,LOCK_SH);
654: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
655: &GDBM_READER(),0640)) {
656: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
657: untie(%disk_env);
658: } else {
659: $convert = 1;
660: }
661: }
662: if ($convert) {
663: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
664: &logthis("Failed to load session, or convert session.");
665: }
1.374 www 666: }
1.783 albertel 667:
1.786 albertel 668: my %remove;
1.783 albertel 669: while ( my $envname = each(%env) ) {
1.433 matthew 670: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
671: if ($time < time-300) {
1.783 albertel 672: $remove{$key}++;
1.433 matthew 673: }
674: }
675: }
1.783 albertel 676:
1.619 albertel 677: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 678: $env_loaded=1;
1.783 albertel 679: foreach my $expired_key (keys(%remove)) {
1.433 matthew 680: &delenv($expired_key);
1.374 www 681: }
1.1 albertel 682: }
683:
1.916 albertel 684: # ---------------------------------------------------- Check for valid session
685: sub check_for_valid_session {
1.1172.2.96 raeburn 686: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 687: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 688: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 689: if ($name eq 'lonDAV') {
690: $lonidsdir=$r->dir_config('lonDAVsessDir');
691: } else {
692: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 693: if ($name eq '') {
694: $name = 'lonID';
695: }
696: }
697: if ($name eq 'lonID') {
698: $secure = 'lonSID';
699: $linkname = 'lonLinkID';
700: $pubname = 'lonPubID';
701: if (exists($cookies{$secure})) {
702: $lonid=$cookies{$secure};
703: } elsif (exists($cookies{$name})) {
704: $lonid=$cookies{$name};
705: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
706: $lonid=$cookies{$linkname};
707: } elsif (exists($cookies{$pubname})) {
708: $lonid=$cookies{$pubname};
709: }
710: } else {
711: $lonid=$cookies{$name};
712: }
713: return undef if (!$lonid);
714:
715: my $handle=&LONCAPA::clean_handle($lonid->value);
716: if (-l "$lonidsdir/$handle.id") {
717: my $link = readlink("$lonidsdir/$handle.id");
718: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
719: $handle = $1;
720: }
1.1155 raeburn 721: }
1.1172.2.96 raeburn 722: if (!-e "$lonidsdir/$handle.id") {
723: if ((ref($domref)) && ($name eq 'lonID') &&
724: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
725: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
726: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
727: $$domref = $possudom;
728: }
729: }
730: return undef;
731: }
1.916 albertel 732:
1.917 albertel 733: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
734: return undef if (!$opened);
1.916 albertel 735:
736: flock($idf,LOCK_SH);
737: my %disk_env;
738: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
739: &GDBM_READER(),0640)) {
740: return undef;
741: }
742:
743: if (!defined($disk_env{'user.name'})
744: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 745: untie(%disk_env);
1.916 albertel 746: return undef;
747: }
1.1172.2.18 raeburn 748:
1.1172.2.36 raeburn 749: if (ref($userhashref) eq 'HASH') {
750: $userhashref->{'name'} = $disk_env{'user.name'};
751: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142 raeburn 752: if ($disk_env{'request.role'}) {
753: $userhashref->{'role'} = $disk_env{'request.role'};
754: }
1.1172.2.146. .13(raeb 755:-23): $userhashref->{'lti'} = $disk_env{'request.lti.login'};
756:-23): if ($userhashref->{'lti'}) {
757:-23): $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
758:-23): $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
759:-23): }
1.1172.2.18 raeburn 760: }
1.1172.2.107 raeburn 761: untie(%disk_env);
1.1172.2.18 raeburn 762:
1.916 albertel 763: return $handle;
764: }
765:
1.830 albertel 766: sub timed_flock {
767: my ($file,$lock_type) = @_;
768: my $failed=0;
769: eval {
770: local $SIG{__DIE__}='DEFAULT';
771: local $SIG{ALRM}=sub {
772: $failed=1;
773: die("failed lock");
774: };
775: alarm(13);
776: flock($file,$lock_type);
777: alarm(0);
778: };
779: if ($failed) {
780: return undef;
781: } else {
782: return 1;
783: }
784: }
785:
1.1172.2.107 raeburn 786: sub get_sessionfile_vars {
787: my ($handle,$lonidsdir,$storearr) = @_;
788: my %returnhash;
789: unless (ref($storearr) eq 'ARRAY') {
790: return %returnhash;
791: }
792: if (-l "$lonidsdir/$handle.id") {
793: my $link = readlink("$lonidsdir/$handle.id");
794: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
795: $handle = $1;
796: }
797: }
798: if ((-e "$lonidsdir/$handle.id") &&
799: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
800: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
801: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
802: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
803: flock($idf,LOCK_SH);
804: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
805: &GDBM_READER(),0640)) {
806: foreach my $item (@{$storearr}) {
807: $returnhash{$item} = $disk_env{$item};
808: }
809: untie(%disk_env);
810: }
811: }
812: }
813: }
814: return %returnhash;
815: }
816:
1.5 www 817: # ---------------------------------------------------------- Append Environment
818:
819: sub appenv {
1.949 raeburn 820: my ($newenv,$roles) = @_;
821: if (ref($newenv) eq 'HASH') {
822: foreach my $key (keys(%{$newenv})) {
823: my $refused = 0;
824: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
825: $refused = 1;
826: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 827: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 828: if (grep(/^\Q$role\E$/,@{$roles})) {
829: $refused = 0;
830: }
831: }
832: }
833: if ($refused) {
834: &logthis("<font color=\"blue\">WARNING: ".
835: "Attempt to modify environment ".$key." to ".$newenv->{$key}
836: .'</font>');
837: delete($newenv->{$key});
838: } else {
839: $env{$key}=$newenv->{$key};
840: }
841: }
1.1172.2.96 raeburn 842: my $lonids = $perlvar{'lonIDsDir'};
843: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
844: my $opened = open(my $env_file,'+<',$env{'user.environment'});
845: if ($opened
846: && &timed_flock($env_file,LOCK_EX)
847: &&
848: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
849: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
850: while (my ($key,$value) = each(%{$newenv})) {
851: $disk_env{$key} = $value;
852: }
853: untie(%disk_env);
854: }
1.35 www 855: }
1.191 harris41 856: }
1.56 www 857: return 'ok';
858: }
859: # ----------------------------------------------------- Delete from Environment
860:
861: sub delenv {
1.1104 raeburn 862: my ($delthis,$regexp,$roles) = @_;
863: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
864: my $refused = 1;
865: if (ref($roles) eq 'ARRAY') {
866: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
867: if (grep(/^\Q$role\E$/,@{$roles})) {
868: $refused = 0;
869: }
870: }
871: if ($refused) {
872: &logthis("<font color=\"blue\">WARNING: ".
873: "Attempt to delete from environment ".$delthis);
874: return 'error';
875: }
1.56 www 876: }
1.917 albertel 877: my $opened = open(my $env_file,'+<',$env{'user.environment'});
878: if ($opened
1.915 albertel 879: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 880: &&
881: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
882: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 883: foreach my $key (keys(%disk_env)) {
1.987 raeburn 884: if ($regexp) {
885: if ($key=~/^$delthis/) {
886: delete($env{$key});
887: delete($disk_env{$key});
888: }
889: } else {
890: if ($key=~/^\Q$delthis\E/) {
891: delete($env{$key});
892: delete($disk_env{$key});
893: }
894: }
1.448 albertel 895: }
1.783 albertel 896: untie(%disk_env);
1.5 www 897: }
898: return 'ok';
1.369 albertel 899: }
900:
1.790 albertel 901: sub get_env_multiple {
902: my ($name) = @_;
903: my @values;
904: if (defined($env{$name})) {
905: # exists is it an array
906: if (ref($env{$name})) {
907: @values=@{ $env{$name} };
908: } else {
909: $values[0]=$env{$name};
910: }
911: }
912: return(@values);
913: }
914:
1.958 www 915: # ------------------------------------------------------------------- Locking
916:
917: sub set_lock {
918: my ($text)=@_;
919: $locknum++;
920: my $id=$$.'-'.$locknum;
921: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
922: 'session.lock.'.$id => $text});
923: return $id;
924: }
925:
926: sub get_locks {
927: my $num=0;
928: my %texts=();
929: foreach my $lock (split(/\,/,$env{'session.locks'})) {
930: if ($lock=~/\w/) {
931: $num++;
932: $texts{$lock}=$env{'session.lock.'.$lock};
933: }
934: }
935: return ($num,%texts);
936: }
937:
938: sub remove_lock {
939: my ($id)=@_;
940: my $newlocks='';
941: foreach my $lock (split(/\,/,$env{'session.locks'})) {
942: if (($lock=~/\w/) && ($lock ne $id)) {
943: $newlocks.=','.$lock;
944: }
945: }
946: &appenv({'session.locks' => $newlocks});
947: &delenv('session.lock.'.$id);
948: }
949:
950: sub remove_all_locks {
951: my $activelocks=$env{'session.locks'};
952: foreach my $lock (split(/\,/,$env{'session.locks'})) {
953: if ($lock=~/\w/) {
954: &remove_lock($lock);
955: }
956: }
957: }
958:
959:
1.369 albertel 960: # ------------------------------------------ Find out current server userload
961: sub userload {
962: my $numusers=0;
963: {
964: opendir(LONIDS,$perlvar{'lonIDsDir'});
965: my $filename;
966: my $curtime=time;
967: while ($filename=readdir(LONIDS)) {
1.925 albertel 968: next if ($filename eq '.' || $filename eq '..');
969: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 970: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 971: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 972: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 973: }
974: closedir(LONIDS);
975: }
976: my $userloadpercent=0;
977: my $maxuserload=$perlvar{'lonUserLoadLim'};
978: if ($maxuserload) {
1.371 albertel 979: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 980: }
1.372 albertel 981: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 982: return $userloadpercent;
1.283 www 983: }
984:
1.1 albertel 985: # ------------------------------ Find server with least workload from spare.tab
1.11 www 986:
1.1 albertel 987: sub spareserver {
1.1172.2.142 raeburn 988: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 989: my $spare_server;
1.370 albertel 990: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 991: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
992: : $userloadpercent;
1.1083 raeburn 993: my ($uint_dom,$remotesessions);
994: if (($udom ne '') && (&domain($udom) ne '')) {
995: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
996: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
997: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
998: $remotesessions = $udomdefaults{'remotesessions'};
999: }
1.1123 raeburn 1000: my $spareshash = &this_host_spares($udom);
1001: if (ref($spareshash) eq 'HASH') {
1002: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1003: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 1004: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
1005: $try_server));
1.1123 raeburn 1006: ($spare_server, $lowest_load) =
1007: &compare_server_load($try_server, $spare_server, $lowest_load);
1008: }
1.1083 raeburn 1009: }
1.784 albertel 1010:
1.1123 raeburn 1011: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1012:
1013: if (!$found_server) {
1014: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1015: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 1016: next unless (&spare_can_host($udom,$uint_dom,
1017: $remotesessions,$try_server));
1.1123 raeburn 1018: ($spare_server, $lowest_load) =
1019: &compare_server_load($try_server, $spare_server, $lowest_load);
1020: }
1021: }
1022: }
1.784 albertel 1023: }
1024:
1025: if (!$want_server_name) {
1.1001 raeburn 1026: if (defined($spare_server)) {
1027: my $hostname = &hostname($spare_server);
1.1083 raeburn 1028: if (defined($hostname)) {
1.1172.2.120 raeburn 1029: my $protocol = 'http';
1030: if ($protocol{$spare_server} eq 'https') {
1031: $protocol = $protocol{$spare_server};
1032: }
1.1172.2.142 raeburn 1033: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
1034: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1035: $spare_server = $protocol.'://'.$hostname;
1036: }
1037: }
1.784 albertel 1038: }
1039: return $spare_server;
1040: }
1041:
1042: sub compare_server_load {
1.1172.2.41 raeburn 1043: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1044:
1045: if ($required) {
1046: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1047: my $remoterev = &get_server_loncaparev(undef,$try_server);
1048: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1049: if (($major eq '' && $minor eq '') ||
1050: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1051: return ($spare_server,$lowest_load);
1052: }
1053: }
1.784 albertel 1054:
1055: my $loadans = &reply('load', $try_server);
1056: my $userloadans = &reply('userload',$try_server);
1057:
1058: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1059: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1060: }
1061:
1062: my $load;
1063: if ($loadans =~ /\d/) {
1064: if ($userloadans =~ /\d/) {
1065: #both are numbers, pick the bigger one
1066: $load = ($loadans > $userloadans) ? $loadans
1067: : $userloadans;
1.411 albertel 1068: } else {
1.784 albertel 1069: $load = $loadans;
1.411 albertel 1070: }
1.784 albertel 1071: } else {
1072: $load = $userloadans;
1073: }
1074:
1075: if (($load =~ /\d/) && ($load < $lowest_load)) {
1076: $spare_server = $try_server;
1077: $lowest_load = $load;
1.370 albertel 1078: }
1.784 albertel 1079: return ($spare_server,$lowest_load);
1.202 matthew 1080: }
1.914 albertel 1081:
1082: # --------------------------- ask offload servers if user already has a session
1083: sub find_existing_session {
1084: my ($udom,$uname) = @_;
1.1123 raeburn 1085: my $spareshash = &this_host_spares($udom);
1086: if (ref($spareshash) eq 'HASH') {
1087: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1088: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1089: return $try_server if (&has_user_session($try_server, $udom, $uname));
1090: }
1091: }
1092: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1093: foreach my $try_server (@{ $spareshash->{'default'} }) {
1094: return $try_server if (&has_user_session($try_server, $udom, $uname));
1095: }
1096: }
1.914 albertel 1097: }
1098: return;
1099: }
1100:
1.1172.2.146. .13(raeb 1101:-23): sub delusersession {
1102:-23): my ($lonid,$udom,$uname) = @_;
1103:-23): my $uprimary_id = &domain($udom,'primary');
1104:-23): my $uintdom = &internet_dom($uprimary_id);
1105:-23): my $intdom = &internet_dom($lonid);
1106:-23): my $serverhomedom = &host_domain($lonid);
1107:-23): if (($uintdom ne '') && ($uintdom eq $intdom)) {
1108:-23): return &reply(join(':','delusersession',
1109:-23): map {&escape($_)} ($udom,$uname)),$lonid);
1110:-23): }
1111:-23): return;
1112:-23): }
1113:-23):
1114:-23):
1.1172.2.107 raeburn 1115: # check if user's browser sent load balancer cookie and server still has session
1116: # and is not overloaded.
1117: sub check_for_balancer_cookie {
1118: my ($r,$update_mtime) = @_;
1119: my ($otherserver,$cookie);
1120: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1121: if (exists($cookies{'balanceID'})) {
1122: my $balid = $cookies{'balanceID'};
1123: $cookie=&LONCAPA::clean_handle($balid->value);
1124: my $balancedir=$r->dir_config('lonBalanceDir');
1125: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1126: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1127: my ($possudom,$possuname) = ($1,$2);
1128: my $has_session = 0;
1129: if ((&domain($possudom) ne '') &&
1130: (&homeserver($possuname,$possudom) ne 'no_host')) {
1131: my $try_server;
1132: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1133: if ($opened) {
1134: flock($idf,LOCK_SH);
1135: while (my $line = <$idf>) {
1136: chomp($line);
1137: if (&hostname($line) ne '') {
1138: $try_server = $line;
1139: last;
1140: }
1141: }
1142: close($idf);
1143: if (($try_server) &&
1144: (&has_user_session($try_server,$possudom,$possuname))) {
1145: my $lowest_load = 30000;
1146: ($otherserver,$lowest_load) =
1147: &compare_server_load($try_server,undef,$lowest_load);
1148: if ($otherserver ne '' && $lowest_load < 100) {
1149: $has_session = 1;
1150: } else {
1151: undef($otherserver);
1152: }
1153: }
1154: }
1155: }
1156: if ($has_session) {
1157: if ($update_mtime) {
1158: my $atime = my $mtime = time;
1159: utime($atime,$mtime,"$balancedir/$cookie.id");
1160: }
1161: } else {
1162: unlink("$balancedir/$cookie.id");
1163: }
1164: }
1165: }
1166: }
1167: return ($otherserver,$cookie);
1168: }
1169:
1.1172.2.130 raeburn 1170: sub updatebalcookie {
1171: my ($cookie,$balancer,$lastentry)=@_;
1172: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1173: my ($udom,$uname) = ($1,$2);
1174: my $uprimary_id = &domain($udom,'primary');
1175: my $uintdom = &internet_dom($uprimary_id);
1176: my $intdom = &internet_dom($balancer);
1177: my $serverhomedom = &host_domain($balancer);
1178: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1179: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1180: }
1181: }
1182: return;
1183: }
1184:
1.1172.2.107 raeburn 1185: sub delbalcookie {
1186: my ($cookie,$balancer) =@_;
1187: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1188: my ($udom,$uname) = ($1,$2);
1189: my $uprimary_id = &domain($udom,'primary');
1190: my $uintdom = &internet_dom($uprimary_id);
1191: my $intdom = &internet_dom($balancer);
1192: my $serverhomedom = &host_domain($balancer);
1193: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1194: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1195: }
1196: }
1197: }
1198:
1.914 albertel 1199: # -------------------------------- ask if server already has a session for user
1200: sub has_user_session {
1201: my ($lonid,$udom,$uname) = @_;
1202: my $result = &reply(join(':','userhassession',
1203: map {&escape($_)} ($udom,$uname)),$lonid);
1204: return 1 if ($result eq 'ok');
1205:
1206: return 0;
1207: }
1208:
1.1076 raeburn 1209: # --------- determine least loaded server in a user's domain which allows login
1210:
1211: sub choose_server {
1.1172.2.47 raeburn 1212: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1213: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1214: my %servers = &get_servers($udom);
1.1076 raeburn 1215: my $lowest_load = 30000;
1.1172.2.47 raeburn 1216: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1217: if ($skiploadbal) {
1218: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1219: unless (defined($cached)) {
1220: my $cachetime = 60*60*24;
1221: my %domconfig =
1222: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1223: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1224: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1225: $cachetime);
1226: }
1227: }
1228: }
1.1076 raeburn 1229: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1230: my $loginvia;
1.1172.2.47 raeburn 1231: if ($skiploadbal) {
1232: if (ref($balancers) eq 'HASH') {
1233: next if (exists($balancers->{$lonhost}));
1234: }
1235: }
1.1115 raeburn 1236: if ($checkloginvia) {
1237: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1238: if ($loginvia) {
1239: my ($server,$path) = split(/:/,$loginvia);
1240: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1241: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1242: if ($login_host eq $server) {
1243: $portal_path = $path;
1.1151 raeburn 1244: $isredirect = 1;
1.1116 raeburn 1245: }
1246: } else {
1247: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1249: if ($login_host eq $lonhost) {
1250: $portal_path = '';
1.1151 raeburn 1251: $isredirect = '';
1.1116 raeburn 1252: }
1253: }
1254: } else {
1.1076 raeburn 1255: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1256: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1257: }
1258: }
1259: if ($login_host ne '') {
1.1116 raeburn 1260: $hostname = &hostname($login_host);
1.1076 raeburn 1261: }
1.1172.2.88 raeburn 1262: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1263: }
1264:
1.1172.2.123 raeburn 1265: sub get_course_sessions {
1266: my ($cnum,$cdom,$lastactivity) = @_;
1267: my %servers = &internet_dom_servers($cdom);
1268: my %returnhash;
1269: foreach my $server (sort(keys(%servers))) {
1270: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1271: my @pairs=split(/\&/,$rep);
1272: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1273: foreach my $item (@pairs) {
1274: my ($key,$value)=split(/=/,$item,2);
1275: $key = &unescape($key);
1276: next if ($key =~ /^error: 2 /);
1277: if (exists($returnhash{$key})) {
1278: next if ($value < $returnhash{$key});
1279: }
1280: $returnhash{$key}=$value;
1281: }
1282: }
1283: }
1284: return %returnhash;
1285: }
1286:
1.202 matthew 1287: # --------------------------------------------- Try to change a user's password
1288:
1289: sub changepass {
1.799 raeburn 1290: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1291: $currentpass = &escape($currentpass);
1292: $newpass = &escape($newpass);
1.1030 raeburn 1293: my $lonhost = $perlvar{'lonHostID'};
1294: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1295: $server);
1296: if (! $answer) {
1297: &logthis("No reply on password change request to $server ".
1298: "by $uname in domain $udom.");
1299: } elsif ($answer =~ "^ok") {
1300: &logthis("$uname in $udom successfully changed their password ".
1301: "on $server.");
1302: } elsif ($answer =~ "^pwchange_failure") {
1303: &logthis("$uname in $udom was unable to change their password ".
1304: "on $server. The action was blocked by either lcpasswd ".
1305: "or pwchange");
1306: } elsif ($answer =~ "^non_authorized") {
1307: &logthis("$uname in $udom did not get their password correct when ".
1308: "attempting to change it on $server.");
1309: } elsif ($answer =~ "^auth_mode_error") {
1310: &logthis("$uname in $udom attempted to change their password despite ".
1311: "not being locally or internally authenticated on $server.");
1312: } elsif ($answer =~ "^unknown_user") {
1313: &logthis("$uname in $udom attempted to change their password ".
1314: "on $server but were unable to because $server is not ".
1315: "their home server.");
1316: } elsif ($answer =~ "^refused") {
1317: &logthis("$server refused to change $uname in $udom password because ".
1318: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1319: } elsif ($answer =~ "invalid_client") {
1320: &logthis("$server refused to change $uname in $udom password because ".
1321: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1322: } elsif ($answer =~ "^prioruse") {
1323: &logthis("$server refused to change $uname in $udom password because ".
1324: "the password had been used before");
1.202 matthew 1325: }
1326: return $answer;
1.1 albertel 1327: }
1328:
1.169 harris41 1329: # ----------------------- Try to determine user's current authentication scheme
1330:
1331: sub queryauthenticate {
1332: my ($uname,$udom)=@_;
1.456 albertel 1333: my $uhome=&homeserver($uname,$udom);
1.1172.2.146. .5(raebu 1334:22): if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1335: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1336: return 'no_host';
1337: }
1338: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1339: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1340: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1341: }
1.456 albertel 1342: return $answer;
1.169 harris41 1343: }
1344:
1.1 albertel 1345: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1346:
1.1 albertel 1347: sub authenticate {
1.1073 raeburn 1348: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1349: $upass=&escape($upass);
1350: $uname= &LONCAPA::clean_username($uname);
1.836 www 1351: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1352: my $newhome;
1.836 www 1353: if ((!$uhome) || ($uhome eq 'no_host')) {
1354: # Maybe the machine was offline and only re-appeared again recently?
1355: &reconlonc();
1356: # One more
1.952 raeburn 1357: $uhome=&homeserver($uname,$udom,1);
1358: if (($uhome eq 'no_host') && $checkdefauth) {
1359: if (defined(&domain($udom,'primary'))) {
1360: $newhome=&domain($udom,'primary');
1361: }
1362: if ($newhome ne '') {
1363: $uhome = $newhome;
1364: }
1365: }
1.836 www 1366: if ((!$uhome) || ($uhome eq 'no_host')) {
1367: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1368: return 'no_host';
1369: }
1.1 albertel 1370: }
1.1073 raeburn 1371: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1372: if ($answer eq 'authorized') {
1.952 raeburn 1373: if ($newhome) {
1374: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1375: return 'no_account_on_host';
1376: } else {
1377: &logthis("User $uname at $udom authorized by $uhome");
1378: return $uhome;
1379: }
1.471 albertel 1380: }
1381: if ($answer eq 'non_authorized') {
1382: &logthis("User $uname at $udom rejected by $uhome");
1.1172.2.146. .5(raebu 1383:22): return 'no_host';
1.9 www 1384: }
1.471 albertel 1385: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1386: return 'no_host';
1387: }
1388:
1.1172.2.146. .6(raebu 1389:22): sub can_switchserver {
1390:22): my ($udom,$home) = @_;
1391:22): my ($canswitch,@intdoms);
1392:22): my $internet_names = &get_internet_names($home);
1393:22): if (ref($internet_names) eq 'ARRAY') {
1394:22): @intdoms = @{$internet_names};
1395:22): }
1396:22): my $uint_dom = &internet_dom(&domain($udom,'primary'));
1397:22): if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1398:22): $canswitch = 1;
1399:22): } else {
1400:22): my $serverhomeID = &get_server_homeID(&hostname($home));
1401:22): my $serverhomedom = &host_domain($serverhomeID);
1402:22): my %defdomdefaults = &get_domain_defaults($serverhomedom);
1403:22): my %udomdefaults = &get_domain_defaults($udom);
1404:22): my $remoterev = &get_server_loncaparev('',$home);
1405:22): $canswitch = &can_host_session($udom,$home,$remoterev,
1406:22): $udomdefaults{'remotesessions'},
1407:22): $defdomdefaults{'hostedsessions'});
1408:22): }
1409:22): return $canswitch;
1410:22): }
1411:22):
1.1073 raeburn 1412: sub can_host_session {
1.1074 raeburn 1413: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1414: my $canhost = 1;
1.1074 raeburn 1415: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1416: if (ref($remotesessions) eq 'HASH') {
1417: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1418: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1419: $canhost = 0;
1420: } else {
1421: $canhost = 1;
1422: }
1423: }
1424: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1425: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1426: $canhost = 1;
1427: } else {
1428: $canhost = 0;
1429: }
1430: }
1431: if ($canhost) {
1432: if ($remotesessions->{'version'} ne '') {
1433: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1434: if ($reqmajor ne '' && $reqminor ne '') {
1435: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1436: my $major = $1;
1437: my $minor = $2;
1438: if (($major < $reqmajor ) ||
1439: (($major == $reqmajor) && ($minor < $reqminor))) {
1440: $canhost = 0;
1441: }
1442: } else {
1443: $canhost = 0;
1444: }
1445: }
1446: }
1447: }
1448: }
1449: if ($canhost) {
1450: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1451: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1452: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1453: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1454: if (($uint_dom ne '') &&
1455: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1456: $canhost = 0;
1457: } else {
1458: $canhost = 1;
1459: }
1460: }
1461: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1462: if (($uint_dom ne '') &&
1463: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1464: $canhost = 1;
1465: } else {
1466: $canhost = 0;
1467: }
1468: }
1469: }
1470: }
1471: return $canhost;
1472: }
1473:
1.1083 raeburn 1474: sub spare_can_host {
1475: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1476: my $canhost=1;
1.1172.2.62 raeburn 1477: my $try_server_hostname = &hostname($try_server);
1478: my $serverhomeID = &get_server_homeID($try_server_hostname);
1479: my $serverhomedom = &host_domain($serverhomeID);
1480: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1481: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1482: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1483: $canhost = 0;
1484: }
1485: }
1.1172.2.136 raeburn 1486: if ($canhost) {
1487: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1488: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1489: unless (&shared_institution($udom,$try_server)) {
1490: $canhost = 0;
1491: }
1492: }
1493: }
1494: }
1.1172.2.62 raeburn 1495: if (($canhost) && ($uint_dom)) {
1496: my @intdoms;
1497: my $internet_names = &get_internet_names($try_server);
1498: if (ref($internet_names) eq 'ARRAY') {
1499: @intdoms = @{$internet_names};
1500: }
1501: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1502: my $remoterev = &get_server_loncaparev(undef,$try_server);
1503: $canhost = &can_host_session($udom,$try_server,$remoterev,
1504: $remotesessions,
1505: $defdomdefaults{'hostedsessions'});
1506: }
1.1083 raeburn 1507: }
1508: return $canhost;
1509: }
1510:
1.1123 raeburn 1511: sub this_host_spares {
1512: my ($dom) = @_;
1.1126 raeburn 1513: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1514: my @hosts = ¤t_machine_ids();
1515: foreach my $lonhost (@hosts) {
1516: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1517: $dom_in_use = $dom;
1518: $lonhost_in_use = $lonhost;
1.1123 raeburn 1519: last;
1520: }
1521: }
1.1126 raeburn 1522: if ($dom_in_use ne '') {
1523: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1524: }
1525: if (ref($result) ne 'HASH') {
1526: $lonhost_in_use = $perlvar{'lonHostID'};
1527: $dom_in_use = &host_domain($lonhost_in_use);
1528: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1529: if (ref($result) ne 'HASH') {
1530: $result = \%spareid;
1531: }
1532: }
1533: return $result;
1534: }
1535:
1536: sub spares_for_offload {
1537: my ($dom_in_use,$lonhost_in_use) = @_;
1538: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1539: if (defined($cached)) {
1540: return $result;
1541: } else {
1.1126 raeburn 1542: my $cachetime = 60*60*24;
1543: my %domconfig =
1544: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1545: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1546: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1547: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1548: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1549: }
1550: }
1551: }
1552: }
1.1126 raeburn 1553: return;
1.1123 raeburn 1554: }
1555:
1.1129 raeburn 1556: sub get_lonbalancer_config {
1557: my ($servers) = @_;
1558: my ($currbalancer,$currtargets);
1559: if (ref($servers) eq 'HASH') {
1560: foreach my $server (keys(%{$servers})) {
1561: my %what = (
1562: spareid => 1,
1563: perlvar => 1,
1564: );
1565: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1566: if ($result eq 'ok') {
1567: if (ref($returnhash) eq 'HASH') {
1568: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1569: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1570: $currbalancer = $server;
1571: $currtargets = {};
1572: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1573: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1574: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1575: }
1576: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1577: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1578: }
1579: }
1580: last;
1581: }
1582: }
1583: }
1584: }
1585: }
1586: }
1587: return ($currbalancer,$currtargets);
1588: }
1589:
1590: sub check_loadbalancing {
1.1172.2.88 raeburn 1591: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1592: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1593: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1594: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1595: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1596: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1597: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1598: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1599: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1600: my $domneedscache;
1.1129 raeburn 1601: my $cachetime = 60*60*24;
1602:
1603: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1604: $dom_in_use = $udom;
1605: $homeintdom = 1;
1606: } else {
1607: $dom_in_use = $serverhomedom;
1608: }
1609: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1610: unless (defined($cached)) {
1611: my %domconfig =
1612: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1613: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1614: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1615: } else {
1616: $domneedscache = $dom_in_use;
1.1129 raeburn 1617: }
1618: }
1619: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1620: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1621: &check_balancer_result($result,@hosts);
1.1129 raeburn 1622: if ($is_balancer) {
1623: if (ref($currrules) eq 'HASH') {
1624: if ($homeintdom) {
1625: if ($uname ne '') {
1626: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1627: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1628: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1629: $rule_in_effect = $currrules->{'_LC_author'};
1630: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1631: $rule_in_effect = $currrules->{'_LC_adv'}
1632: }
1633: }
1634: if ($rule_in_effect eq '') {
1635: my %userenv = &userenvironment($udom,$uname,'inststatus');
1636: if ($userenv{'inststatus'} ne '') {
1637: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1638: my ($othertitle,$usertypes,$types) =
1639: &Apache::loncommon::sorted_inst_types($udom);
1640: if (ref($types) eq 'ARRAY') {
1641: foreach my $type (@{$types}) {
1642: if (grep(/^\Q$type\E$/,@statuses)) {
1643: if (exists($currrules->{$type})) {
1644: $rule_in_effect = $currrules->{$type};
1645: }
1646: }
1647: }
1648: }
1649: } else {
1650: if (exists($currrules->{'default'})) {
1651: $rule_in_effect = $currrules->{'default'};
1652: }
1653: }
1654: }
1655: } else {
1656: if (exists($currrules->{'default'})) {
1657: $rule_in_effect = $currrules->{'default'};
1658: }
1659: }
1660: } else {
1661: if ($currrules->{'_LC_external'} ne '') {
1662: $rule_in_effect = $currrules->{'_LC_external'};
1663: }
1664: }
1665: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1666: $uname,$udom);
1667: }
1668: }
1669: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1670: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1671: unless (defined($cached)) {
1672: my %domconfig =
1673: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1674: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1675: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1676: } else {
1677: $domneedscache = $serverhomedom;
1.1129 raeburn 1678: }
1679: }
1680: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1681: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1682: &check_balancer_result($result,@hosts);
1683: if ($is_balancer) {
1.1129 raeburn 1684: if (ref($currrules) eq 'HASH') {
1685: if ($currrules->{'_LC_internetdom'} ne '') {
1686: $rule_in_effect = $currrules->{'_LC_internetdom'};
1687: }
1688: }
1689: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1690: $uname,$udom);
1691: }
1692: } else {
1693: if ($perlvar{'lonBalancer'} eq 'yes') {
1694: $is_balancer = 1;
1695: $offloadto = &this_host_spares($dom_in_use);
1696: }
1.1172.2.75 raeburn 1697: unless (defined($cached)) {
1698: $domneedscache = $serverhomedom;
1699: }
1.1129 raeburn 1700: }
1701: } else {
1702: if ($perlvar{'lonBalancer'} eq 'yes') {
1703: $is_balancer = 1;
1704: $offloadto = &this_host_spares($dom_in_use);
1705: }
1.1172.2.75 raeburn 1706: unless (defined($cached)) {
1707: $domneedscache = $serverhomedom;
1708: }
1709: }
1710: if ($domneedscache) {
1711: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1712: }
1.1172.2.130 raeburn 1713: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1714: my $lowest_load = 30000;
1715: if (ref($offloadto) eq 'HASH') {
1716: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1717: foreach my $try_server (@{$offloadto->{'primary'}}) {
1718: ($otherserver,$lowest_load) =
1719: &compare_server_load($try_server,$otherserver,$lowest_load);
1720: }
1.1129 raeburn 1721: }
1.1172.2.5 raeburn 1722: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1723:
1.1172.2.5 raeburn 1724: if (!$found_server) {
1725: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1726: foreach my $try_server (@{$offloadto->{'default'}}) {
1727: ($otherserver,$lowest_load) =
1728: &compare_server_load($try_server,$otherserver,$lowest_load);
1729: }
1730: }
1731: }
1732: } elsif (ref($offloadto) eq 'ARRAY') {
1733: if (@{$offloadto} == 1) {
1734: $otherserver = $offloadto->[0];
1735: } elsif (@{$offloadto} > 1) {
1736: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1737: ($otherserver,$lowest_load) =
1738: &compare_server_load($try_server,$otherserver,$lowest_load);
1739: }
1740: }
1741: }
1.1172.2.88 raeburn 1742: unless ($caller eq 'login') {
1743: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1744: $is_balancer = 0;
1745: if ($uname ne '' && $udom ne '') {
1746: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1747: &appenv({'user.loadbalexempt' => $lonhost,
1748: 'user.loadbalcheck.time' => time});
1749: }
1.1172.2.5 raeburn 1750: }
1.1129 raeburn 1751: }
1752: }
1.1172.2.130 raeburn 1753: }
1754: if (($is_balancer) && (!$homeintdom)) {
1755: undef($setcookie);
1.1129 raeburn 1756: }
1.1172.2.107 raeburn 1757: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1758: }
1759:
1.1172.2.12 raeburn 1760: sub check_balancer_result {
1761: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1762: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1763: if (ref($result) eq 'HASH') {
1764: if ($result->{'lonhost'} ne '') {
1765: my $currbalancer = $result->{'lonhost'};
1766: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1767: $is_balancer = 1;
1768: $currtargets = $result->{'targets'};
1769: $currrules = $result->{'rules'};
1770: }
1771: } else {
1772: foreach my $key (keys(%{$result})) {
1773: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1774: (ref($result->{$key}) eq 'HASH')) {
1775: $is_balancer = 1;
1776: $currrules = $result->{$key}{'rules'};
1777: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1778: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1779: last;
1780: }
1781: }
1782: }
1783: }
1.1172.2.107 raeburn 1784: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1785: }
1786:
1.1129 raeburn 1787: sub get_loadbalancer_targets {
1788: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1789: my $offloadto;
1.1172.2.4 raeburn 1790: if ($rule_in_effect eq 'none') {
1791: return [$perlvar{'lonHostID'}];
1792: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1793: $offloadto = $currtargets;
1794: } else {
1795: if ($rule_in_effect eq 'homeserver') {
1796: my $homeserver = &homeserver($uname,$udom);
1797: if ($homeserver ne 'no_host') {
1798: $offloadto = [$homeserver];
1799: }
1800: } elsif ($rule_in_effect eq 'externalbalancer') {
1801: my %domconfig =
1802: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1803: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1804: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1805: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1806: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1807: }
1808: }
1809: } else {
1.1172.2.7 raeburn 1810: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1811: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1812: if (&hostname($remotebalancer) ne '') {
1813: $offloadto = [$remotebalancer];
1814: }
1815: }
1816: } elsif (&hostname($rule_in_effect) ne '') {
1817: $offloadto = [$rule_in_effect];
1818: }
1819: }
1820: return $offloadto;
1821: }
1822:
1.1127 raeburn 1823: sub internet_dom_servers {
1824: my ($dom) = @_;
1825: my (%uniqservers,%servers);
1826: my $primaryserver = &hostname(&domain($dom,'primary'));
1827: my @machinedoms = &machine_domains($primaryserver);
1828: foreach my $mdom (@machinedoms) {
1829: my %currservers = %servers;
1830: my %server = &get_servers($mdom);
1831: %servers = (%currservers,%server);
1832: }
1833: my %by_hostname;
1834: foreach my $id (keys(%servers)) {
1835: push(@{$by_hostname{$servers{$id}}},$id);
1836: }
1837: foreach my $hostname (sort(keys(%by_hostname))) {
1838: if (@{$by_hostname{$hostname}} > 1) {
1839: my $match = 0;
1840: foreach my $id (@{$by_hostname{$hostname}}) {
1841: if (&host_domain($id) eq $dom) {
1842: $uniqservers{$id} = $hostname;
1843: $match = 1;
1844: }
1845: }
1846: unless ($match) {
1847: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1848: }
1849: } else {
1850: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1851: }
1852: }
1853: return %uniqservers;
1854: }
1855:
1.1 albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1857:
1.599 albertel 1858: my %homecache;
1.1 albertel 1859: sub homeserver {
1.230 stredwic 1860: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1861: my $index="$uname:$udom";
1.426 albertel 1862:
1.599 albertel 1863: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1864:
1865: my %servers = &get_servers($udom,'library');
1866: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1867: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1868: exists($badServerCache{$tryserver}));
1.841 albertel 1869:
1870: my $answer=reply("home:$udom:$uname",$tryserver);
1871: if ($answer eq 'found') {
1872: delete($badServerCache{$tryserver});
1873: return $homecache{$index}=$tryserver;
1874: } elsif ($answer eq 'no_host') {
1875: $badServerCache{$tryserver}=1;
1876: }
1.1 albertel 1877: }
1878: return 'no_host';
1.70 www 1879: }
1880:
1881: # ------------------------------------- Find the usernames behind a list of IDs
1882:
1883: sub idget {
1884: my ($udom,@ids)=@_;
1885: my %returnhash=();
1886:
1.841 albertel 1887: my %servers = &get_servers($udom,'library');
1888: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1889: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1890: $idlist=~tr/A-Z/a-z/;
1891: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1892: my @answer=();
1893: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1894: @answer=split(/\&/,$reply);
1895: } ;
1896: my $i;
1897: for ($i=0;$i<=$#ids;$i++) {
1898: if ($answer[$i]) {
1.1172.2.73 raeburn 1899: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1900: }
1901: }
1902: }
1.70 www 1903: return %returnhash;
1904: }
1905:
1906: # ------------------------------------- Find the IDs behind a list of usernames
1907:
1908: sub idrget {
1909: my ($udom,@unames)=@_;
1910: my %returnhash=();
1.800 albertel 1911: foreach my $uname (@unames) {
1912: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1913: }
1.70 www 1914: return %returnhash;
1915: }
1916:
1917: # ------------------------------- Store away a list of names and associated IDs
1918:
1919: sub idput {
1920: my ($udom,%ids)=@_;
1921: my %servers=();
1.800 albertel 1922: foreach my $uname (keys(%ids)) {
1923: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1924: my $uhom=&homeserver($uname,$udom);
1.70 www 1925: if ($uhom ne 'no_host') {
1.800 albertel 1926: my $id=&escape($ids{$uname});
1.70 www 1927: $id=~tr/A-Z/a-z/;
1.800 albertel 1928: my $esc_unam=&escape($uname);
1.70 www 1929: if ($servers{$uhom}) {
1.800 albertel 1930: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1931: } else {
1.800 albertel 1932: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1933: }
1934: }
1.191 harris41 1935: }
1.800 albertel 1936: foreach my $server (keys(%servers)) {
1937: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1938: }
1.344 www 1939: }
1940:
1.1172.2.30 raeburn 1941: # ---------------------------------------- Delete unwanted IDs from ids.db file
1942:
1943: sub iddel {
1944: my ($udom,$idshashref,$uhome)=@_;
1945: my %result=();
1946: unless (ref($idshashref) eq 'HASH') {
1947: return %result;
1948: }
1949: my %servers=();
1950: while (my ($id,$uname) = each(%{$idshashref})) {
1951: my $uhom;
1952: if ($uhome) {
1953: $uhom = $uhome;
1954: } else {
1955: $uhom=&homeserver($uname,$udom);
1956: }
1957: if ($uhom ne 'no_host') {
1958: if ($servers{$uhom}) {
1959: $servers{$uhom}.='&'.&escape($id);
1960: } else {
1961: $servers{$uhom}=&escape($id);
1962: }
1963: }
1964: }
1965: foreach my $server (keys(%servers)) {
1966: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1967: }
1968: return %result;
1969: }
1970:
1.1023 raeburn 1971: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1972: sub dump_dom {
1.1165 droeschl 1973: my ($namespace, $udom, $regexp) = @_;
1974:
1975: $udom ||= $env{'user.domain'};
1976:
1977: return () unless $udom;
1978:
1979: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1980: }
1981:
1.1023 raeburn 1982: # ------------------------------------------ get items from domain db files
1.806 raeburn 1983:
1984: sub get_dom {
1.1172.2.146. .1(raebu 1985:22): my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57 raeburn 1986: return if ($udom eq 'public');
1.806 raeburn 1987: my $items='';
1988: foreach my $item (@$storearr) {
1989: $items.=&escape($item).'&';
1990: }
1991: $items=~s/\&$//;
1.860 raeburn 1992: if (!$udom) {
1993: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1994: return if ($udom eq 'public');
1.860 raeburn 1995: if (defined(&domain($udom,'primary'))) {
1996: $uhome=&domain($udom,'primary');
1997: } else {
1.874 albertel 1998: undef($uhome);
1.860 raeburn 1999: }
2000: } else {
2001: if (!$uhome) {
2002: if (defined(&domain($udom,'primary'))) {
2003: $uhome=&domain($udom,'primary');
2004: }
2005: }
2006: }
2007: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139 raeburn 2008: my $rep;
2009: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2010: # domain information is hosted on this machine
2011: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146. .1(raebu 2012:22): } else {
2013:22): if ($encrypt) {
2014:22): $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2015:22): } else {
2016:22): $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2017:22): }
1.1172.2.139 raeburn 2018: }
1.866 raeburn 2019: my %returnhash;
1.875 albertel 2020: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2021: return %returnhash;
2022: }
1.806 raeburn 2023: my @pairs=split(/\&/,$rep);
2024: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2025: return @pairs;
2026: }
2027: my $i=0;
2028: foreach my $item (@$storearr) {
2029: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2030: $i++;
2031: }
2032: return %returnhash;
2033: } else {
1.880 banghart 2034: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2035: }
2036: }
2037:
2038: # -------------------------------------------- put items in domain db files
2039:
2040: sub put_dom {
1.1172.2.146. .1(raebu 2041:22): my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2042: if (!$udom) {
2043: $udom=$env{'user.domain'};
2044: if (defined(&domain($udom,'primary'))) {
2045: $uhome=&domain($udom,'primary');
2046: } else {
1.874 albertel 2047: undef($uhome);
1.860 raeburn 2048: }
2049: } else {
2050: if (!$uhome) {
2051: if (defined(&domain($udom,'primary'))) {
2052: $uhome=&domain($udom,'primary');
2053: }
2054: }
2055: }
2056: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2057: my $items='';
2058: foreach my $item (keys(%$storehash)) {
2059: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2060: }
2061: $items=~s/\&$//;
1.1172.2.146. .1(raebu 2062:22): if ($encrypt) {
2063:22): return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2064:22): } else {
2065:22): return &reply("putdom:$udom:$namespace:$items",$uhome);
2066:22): }
1.806 raeburn 2067: } else {
1.860 raeburn 2068: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2069: }
2070: }
2071:
1.1023 raeburn 2072: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2073: sub newput_dom {
1.1023 raeburn 2074: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2075: my $result;
2076: if (!$udom) {
2077: $udom=$env{'user.domain'};
2078: }
1.1023 raeburn 2079: if ($udom) {
2080: my $uname = &get_domainconfiguser($udom);
2081: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2082: }
2083: return $result;
2084: }
2085:
1.1023 raeburn 2086: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2087: sub del_dom {
1.1023 raeburn 2088: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2089: if (ref($storearr) eq 'ARRAY') {
2090: if (!$udom) {
2091: $udom=$env{'user.domain'};
2092: }
1.1023 raeburn 2093: if ($udom) {
2094: my $uname = &get_domainconfiguser($udom);
2095: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2096: }
2097: }
2098: }
2099:
1.1172.2.146. .4(raebu 2100:22): sub store_dom {
2101:22): my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
2102:22): $$storehash{'ip'}=&get_requestor_ip();
2103:22): $$storehash{'host'}=$perlvar{'lonHostID'};
2104:22): my $namevalue='';
2105:22): foreach my $key (keys(%{$storehash})) {
2106:22): $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2107:22): }
2108:22): $namevalue=~s/\&$//;
2109:22): if (grep { $_ eq $home } current_machine_ids()) {
2110:22): return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2111:22): } else {
2112:22): if ($namespace eq 'private') {
2113:22): return 'refused';
2114:22): } elsif ($encrypt) {
2115:22): return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
2116:22): } else {
2117:22): return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
2118:22): }
2119:22): }
2120:22): }
2121:22):
2122:22): sub restore_dom {
2123:22): my ($id,$namespace,$dom,$home,$encrypt) = @_;
2124:22): my $answer;
2125:22): if (grep { $_ eq $home } current_machine_ids()) {
2126:22): $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2127:22): } elsif ($namespace ne 'private') {
2128:22): if ($encrypt) {
2129:22): $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2130:22): } else {
2131:22): $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2132:22): }
2133:22): }
2134:22): my %returnhash=();
2135:22): unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2136:22): ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2137:22): foreach my $line (split(/\&/,$answer)) {
2138:22): my ($name,$value)=split(/\=/,$line);
2139:22): $returnhash{&unescape($name)}=&thaw_unescape($value);
2140:22): }
2141:22): my $version;
2142:22): for ($version=1;$version<=$returnhash{'version'};$version++) {
2143:22): foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2144:22): $returnhash{$item}=$returnhash{$version.':'.$item};
2145:22): }
2146:22): }
2147:22): }
2148:22): return %returnhash;
2149:22): }
2150:22):
1.1023 raeburn 2151: # ----------------------------------construct domainconfig user for a domain
2152: sub get_domainconfiguser {
2153: my ($udom) = @_;
2154: return $udom.'-domainconfig';
2155: }
2156:
1.837 raeburn 2157: sub retrieve_inst_usertypes {
2158: my ($udom) = @_;
2159: my (%returnhash,@order);
1.989 raeburn 2160: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2161: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2162: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 2163: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2164: } else {
2165: if (defined(&domain($udom,'primary'))) {
2166: my $uhome=&domain($udom,'primary');
2167: my $rep=&reply("inst_usertypes:$udom",$uhome);
2168: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2169: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2170: return (\%returnhash,\@order);
2171: }
2172: my ($hashitems,$orderitems) = split(/:/,$rep);
2173: my @pairs=split(/\&/,$hashitems);
2174: foreach my $item (@pairs) {
2175: my ($key,$value)=split(/=/,$item,2);
2176: $key = &unescape($key);
2177: next if ($key =~ /^error: 2 /);
2178: $returnhash{$key}=&thaw_unescape($value);
2179: }
2180: my @esc_order = split(/\&/,$orderitems);
2181: foreach my $item (@esc_order) {
2182: push(@order,&unescape($item));
2183: }
2184: } else {
1.1172.2.44 raeburn 2185: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2186: }
1.1172.2.44 raeburn 2187: return (\%returnhash,\@order);
1.837 raeburn 2188: }
2189: }
2190:
1.868 raeburn 2191: sub is_domainimage {
2192: my ($url) = @_;
1.1172.2.142 raeburn 2193: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2194: if (&domain($1) ne '') {
2195: return '1';
2196: }
2197: }
2198: return;
2199: }
2200:
1.899 raeburn 2201: sub inst_directory_query {
2202: my ($srch) = @_;
2203: my $udom = $srch->{'srchdomain'};
2204: my %results;
2205: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2206: my $outcome;
1.899 raeburn 2207: if ($homeserver ne '') {
1.1172.2.116 raeburn 2208: unless ($homeserver eq $perlvar{'lonHostID'}) {
2209: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2210: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2211: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2212: if (($major eq '' && $minor eq '') || ($major < 2) ||
2213: (($major == 2) && ($minor < 11)) ||
2214: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2215: return;
2216: }
2217: }
2218: }
1.904 albertel 2219: my $queryid=&reply("querysend:instdirsearch:".
2220: &escape($srch->{'srchby'}).':'.
2221: &escape($srch->{'srchterm'}).':'.
2222: &escape($srch->{'srchtype'}),$homeserver);
2223: my $host=&hostname($homeserver);
2224: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2225: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2226: return;
2227: }
2228: my $response = &get_query_reply($queryid);
2229: my $maxtries = 5;
2230: my $tries = 1;
2231: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2232: $response = &get_query_reply($queryid);
2233: $tries ++;
2234: }
2235:
2236: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2237: if ($response eq 'unavailable') {
2238: $outcome = $response;
2239: } else {
2240: $outcome = 'ok';
2241: my @matches = split(/\n/,$response);
2242: foreach my $match (@matches) {
2243: my ($key,$value) = split(/=/,$match);
2244: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2245: }
1.899 raeburn 2246: }
2247: }
2248: }
1.909 raeburn 2249: return ($outcome,%results);
1.899 raeburn 2250: }
2251:
2252: sub usersearch {
2253: my ($srch) = @_;
2254: my $dom = $srch->{'srchdomain'};
2255: my %results;
2256: my %libserv = &all_library();
2257: my $query = 'usersearch';
2258: foreach my $tryserver (keys(%libserv)) {
2259: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2260: unless ($tryserver eq $perlvar{'lonHostID'}) {
2261: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2262: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2263: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2264: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2265: (($major == 2) && ($minor < 11)) ||
2266: (($major == 2) && ($minor == 11) && ($subver < 3)));
2267: }
2268: }
1.899 raeburn 2269: my $host=&hostname($tryserver);
2270: my $queryid=
1.911 raeburn 2271: &reply("querysend:".&escape($query).':'.
2272: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2273: &escape($srch->{'srchtype'}).':'.
2274: &escape($srch->{'srchterm'}),$tryserver);
2275: if ($queryid !~/^\Q$host\E\_/) {
2276: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2277: next;
1.899 raeburn 2278: }
2279: my $reply = &get_query_reply($queryid);
2280: my $maxtries = 1;
2281: my $tries = 1;
2282: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2283: $reply = &get_query_reply($queryid);
2284: $tries ++;
2285: }
2286: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2287: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2288: } else {
1.911 raeburn 2289: my @matches;
2290: if ($reply =~ /\n/) {
2291: @matches = split(/\n/,$reply);
2292: } else {
2293: @matches = split(/\&/,$reply);
2294: }
1.899 raeburn 2295: foreach my $match (@matches) {
2296: my ($uname,$udom,%userhash);
1.911 raeburn 2297: foreach my $entry (split(/:/,$match)) {
2298: my ($key,$value) =
2299: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2300: $userhash{$key} = $value;
2301: if ($key eq 'username') {
2302: $uname = $value;
2303: } elsif ($key eq 'domain') {
2304: $udom = $value;
1.911 raeburn 2305: }
1.899 raeburn 2306: }
2307: $results{$uname.':'.$udom} = \%userhash;
2308: }
2309: }
2310: }
2311: }
2312: return %results;
2313: }
2314:
1.912 raeburn 2315: sub get_instuser {
2316: my ($udom,$uname,$id) = @_;
2317: my $homeserver = &domain($udom,'primary');
2318: my ($outcome,%results);
2319: if ($homeserver ne '') {
2320: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2321: &escape($id).':'.&escape($udom),$homeserver);
2322: my $host=&hostname($homeserver);
2323: if ($queryid !~/^\Q$host\E\_/) {
2324: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2325: return;
2326: }
2327: my $response = &get_query_reply($queryid);
2328: my $maxtries = 5;
2329: my $tries = 1;
2330: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2331: $response = &get_query_reply($queryid);
2332: $tries ++;
2333: }
2334: if (!&error($response) && $response ne 'refused') {
2335: if ($response eq 'unavailable') {
2336: $outcome = $response;
2337: } else {
2338: $outcome = 'ok';
2339: my @matches = split(/\n/,$response);
2340: foreach my $match (@matches) {
2341: my ($key,$value) = split(/=/,$match);
2342: $results{&unescape($key)} = &thaw_unescape($value);
2343: }
2344: }
2345: }
2346: }
2347: my %userinfo;
2348: if (ref($results{$uname}) eq 'HASH') {
2349: %userinfo = %{$results{$uname}};
2350: }
2351: return ($outcome,%userinfo);
2352: }
2353:
1.1172.2.69 raeburn 2354: sub get_multiple_instusers {
2355: my ($udom,$users,$caller) = @_;
2356: my ($outcome,$results);
2357: if (ref($users) eq 'HASH') {
2358: my $count = keys(%{$users});
2359: my $requested = &freeze_escape($users);
2360: my $homeserver = &domain($udom,'primary');
2361: if ($homeserver ne '') {
2362: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2363: my $host=&hostname($homeserver);
2364: if ($queryid !~/^\Q$host\E\_/) {
2365: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2366: ' for host: '.$homeserver.'in domain '.$udom);
2367: return ($outcome,$results);
2368: }
2369: my $response = &get_query_reply($queryid);
2370: my $maxtries = 5;
2371: if ($count > 100) {
2372: $maxtries = 1+int($count/20);
2373: }
2374: my $tries = 1;
2375: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2376: $response = &get_query_reply($queryid);
2377: $tries ++;
2378: }
2379: if ($response eq '') {
2380: $results = {};
2381: foreach my $key (keys(%{$users})) {
2382: my ($uname,$id);
2383: if ($caller eq 'id') {
2384: $id = $key;
2385: } else {
2386: $uname = $key;
2387: }
2388: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2389: $outcome = $resp;
2390: if ($resp eq 'ok') {
2391: %{$results} = (%{$results}, %info);
2392: } else {
2393: last;
2394: }
2395: }
2396: } elsif(!&error($response) && ($response ne 'refused')) {
2397: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2398: $outcome = $response;
2399: } else {
2400: ($outcome,my $userdata) = split(/=/,$response,2);
2401: if ($outcome eq 'ok') {
2402: $results = &thaw_unescape($userdata);
2403: }
2404: }
2405: }
2406: }
2407: }
2408: return ($outcome,$results);
2409: }
2410:
1.912 raeburn 2411: sub inst_rulecheck {
1.923 raeburn 2412: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2413: my %returnhash;
2414: if ($udom ne '') {
2415: if (ref($rules) eq 'ARRAY') {
2416: @{$rules} = map {&escape($_);} (@{$rules});
2417: my $rulestr = join(':',@{$rules});
2418: my $homeserver=&domain($udom,'primary');
2419: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2420: my $response;
2421: if ($item eq 'username') {
2422: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2423: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2424: $homeserver));
1.923 raeburn 2425: } elsif ($item eq 'id') {
2426: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2427: ':'.&escape($id).':'.$rulestr,
2428: $homeserver));
1.1172.2.146. .5(raebu 2429:22): } elsif ($item eq 'unamemap') {
2430:22): $response=&unescape(&reply('instunamemapcheck:'.
2431:22): &escape($udom).':'.&escape($uname).
2432:22): ':'.$rulestr,$homeserver));
1.945 raeburn 2433: } elsif ($item eq 'selfcreate') {
2434: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2435: &escape($udom).':'.&escape($uname).
2436: ':'.$rulestr,$homeserver));
1.923 raeburn 2437: }
1.912 raeburn 2438: if ($response ne 'refused') {
2439: my @pairs=split(/\&/,$response);
2440: foreach my $item (@pairs) {
2441: my ($key,$value)=split(/=/,$item,2);
2442: $key = &unescape($key);
2443: next if ($key =~ /^error: 2 /);
2444: $returnhash{$key}=&thaw_unescape($value);
2445: }
2446: }
2447: }
2448: }
2449: }
2450: return %returnhash;
2451: }
2452:
2453: sub inst_userrules {
1.923 raeburn 2454: my ($udom,$check) = @_;
1.912 raeburn 2455: my (%ruleshash,@ruleorder);
2456: if ($udom ne '') {
2457: my $homeserver=&domain($udom,'primary');
2458: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2459: my $response;
2460: if ($check eq 'id') {
2461: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2462: $homeserver);
1.943 raeburn 2463: } elsif ($check eq 'email') {
2464: $response=&reply('instemailrules:'.&escape($udom),
2465: $homeserver);
1.1172.2.146. .5(raebu 2466:22): } elsif ($check eq 'unamemap') {
2467:22): $response=&reply('unamemaprules:'.&escape($udom),
2468:22): $homeserver);
1.923 raeburn 2469: } else {
2470: $response=&reply('instuserrules:'.&escape($udom),
2471: $homeserver);
2472: }
1.912 raeburn 2473: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2474: ($response ne 'unknown_cmd') &&
1.912 raeburn 2475: ($response ne 'no_such_host')) {
2476: my ($hashitems,$orderitems) = split(/:/,$response);
2477: my @pairs=split(/\&/,$hashitems);
2478: foreach my $item (@pairs) {
2479: my ($key,$value)=split(/=/,$item,2);
2480: $key = &unescape($key);
2481: next if ($key =~ /^error: 2 /);
2482: $ruleshash{$key}=&thaw_unescape($value);
2483: }
2484: my @esc_order = split(/\&/,$orderitems);
2485: foreach my $item (@esc_order) {
2486: push(@ruleorder,&unescape($item));
2487: }
2488: }
2489: }
2490: }
2491: return (\%ruleshash,\@ruleorder);
2492: }
2493:
1.976 raeburn 2494: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2495:
2496: sub get_domain_defaults {
1.1172.2.35 raeburn 2497: my ($domain,$ignore_cache) = @_;
2498: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2499: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2500: unless ($ignore_cache) {
2501: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2502: if (defined($cached)) {
2503: if (ref($result) eq 'HASH') {
2504: return %{$result};
2505: }
1.943 raeburn 2506: }
2507: }
2508: my %domdefaults;
2509: my %domconfig =
1.989 raeburn 2510: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2511: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2512: 'coursedefaults','usersessions',
1.1172.2.146. .18(raeb 2513:-24): 'requestauthor','authordefaults',
2514:-24): 'selfenrollment','coursecategories',
2515:-24): 'autoenroll','helpsettings',
2516:-24): 'wafproxy','ltisec','toolsec',
2517:-24): 'domexttool','exttool'],$domain);
1.1172.2.41 raeburn 2518: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2519: if (ref($domconfig{'defaults'}) eq 'HASH') {
2520: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2521: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2522: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2523: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2524: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2525: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146. .12(raeb 2526:-23): $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2527:-23): $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91 raeburn 2528: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2529: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2530: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146. .5(raebu 2531:22): $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2532: } else {
2533: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2534: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2535: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2536: }
1.976 raeburn 2537: if (ref($domconfig{'quotas'}) eq 'HASH') {
2538: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2539: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2540: } else {
2541: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2542: }
1.1172.2.6 raeburn 2543: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2544: foreach my $item (@usertools) {
2545: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2546: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2547: }
2548: }
1.1172.2.29 raeburn 2549: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2550: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2551: }
1.976 raeburn 2552: }
1.985 raeburn 2553: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2554: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2555: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2556: }
2557: }
1.1172.2.146. .18(raeb 2558:-24): if (ref($domconfig{'authordefaults'}) eq 'HASH') {
2559:-24): foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
2560:-24): if ($item eq 'editors') {
2561:-24): if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
2562:-24): $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
2563:-24): }
2564:-24): } else {
2565:-24): $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
2566:-24): }
2567:-24): }
2568:-24): }
1.1172.2.9 raeburn 2569: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2570: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2571: }
1.989 raeburn 2572: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2573: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2574: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2575: }
2576: }
1.1047 raeburn 2577: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2578: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144 raeburn 2579: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60 raeburn 2580: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2581: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2582: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2583: }
1.1172.2.41 raeburn 2584: foreach my $type (@coursetypes) {
2585: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2586: unless ($type eq 'community') {
2587: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2588: }
2589: }
2590: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2591: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2592: }
1.1172.2.146. .14(raeb 2593:-23): if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
2594:-23): $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
2595:-23): }
1.1172.2.60 raeburn 2596: if ($domdefaults{'postsubmit'} eq 'on') {
2597: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2598: $domdefaults{$type.'postsubtimeout'} =
2599: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2600: }
2601: }
1.1172.2.146. .13(raeb 2602:-23): if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
2603:-23): $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
2604:-23): } else {
2605:-23): $domdefaults{$type.'domexttool'} = 1;
2606:-23): }
2607:-23): if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
2608:-23): $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
2609:-23): } else {
2610:-23): $domdefaults{$type.'exttool'} = 0;
2611:-23): }
1.1172.2.30 raeburn 2612: }
1.1172.2.67 raeburn 2613: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2614: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2615: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2616: if (@clonecodes) {
2617: $domdefaults{'canclone'} = join('+',@clonecodes);
2618: }
2619: }
2620: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2621: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2622: }
1.1172.2.103 raeburn 2623: if ($domconfig{'coursedefaults'}{'texengine'}) {
2624: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2625: }
1.1172.2.146. .3(raebu 2626:22): if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2627:22): $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2628:22): }
1.1047 raeburn 2629: }
1.1073 raeburn 2630: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2631: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2632: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2633: }
2634: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2635: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2636: }
1.1172.2.62 raeburn 2637: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2638: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2639: }
1.1172.2.137 raeburn 2640: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2641: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2642: }
1.1073 raeburn 2643: }
1.1172.2.41 raeburn 2644: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2645: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2646: my @settings = ('types','registered','enroll_dates','access_dates','section',
2647: 'approval','limit');
2648: foreach my $type (@coursetypes) {
2649: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2650: my @mgrdc = ();
2651: foreach my $item (@settings) {
2652: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2653: push(@mgrdc,$item);
2654: }
2655: }
2656: if (@mgrdc) {
2657: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2658: }
2659: }
2660: }
2661: }
2662: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2663: foreach my $type (@coursetypes) {
2664: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2665: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2666: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2667: }
2668: }
2669: }
2670: }
2671: }
1.1172.2.46 raeburn 2672: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2673: $domdefaults{'catauth'} = 'std';
2674: $domdefaults{'catunauth'} = 'std';
2675: if ($domconfig{'coursecategories'}{'auth'}) {
2676: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2677: }
2678: if ($domconfig{'coursecategories'}{'unauth'}) {
2679: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2680: }
2681: }
1.1172.2.76 raeburn 2682: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2683: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146 raeburn 2684: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76 raeburn 2685: }
1.1172.2.89 raeburn 2686: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2687: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2688: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2689: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2690: }
2691: }
1.1172.2.142 raeburn 2692: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2693: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2694: if ($domconfig{'wafproxy'}{$item}) {
2695: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2696: }
2697: }
2698: }
1.1172.2.146. .4(raebu 2699:22): if (ref($domconfig{'ltisec'}) eq 'HASH') {
2700:22): if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2701:22): $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2702:22): $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2703:22): $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2704:22): }
2705:22): if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2706:22): if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
.13(raeb 2707:-23): $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2708:-23): }
2709:-23): }
.17(raeb 2710:-24): if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
2711:-24): my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
2712:-24): foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
2713:-24): unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
2714:-24): delete($suggestions{$item});
2715:-24): }
2716:-24): }
2717:-24): if (keys(%suggestions)) {
2718:-24): $domdefaults{'linkprotsuggested'} = \%suggestions;
2719:-24): }
2720:-24): }
.13(raeb 2721:-23): }
2722:-23): if (ref($domconfig{'toolsec'}) eq 'HASH') {
2723:-23): if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
2724:-23): $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
2725:-23): $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
2726:-23): }
2727:-23): if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
2728:-23): if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
2729:-23): $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
.4(raebu 2730:22): }
2731:22): }
2732:22): }
1.1172.2.23 raeburn 2733: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2734: return %domdefaults;
2735: }
2736:
1.1172.2.106 raeburn 2737: sub get_dom_cats {
2738: my ($dom) = @_;
2739: return unless (&domain($dom));
2740: my ($cats,$cached)=&is_cached_new('cats',$dom);
2741: unless (defined($cached)) {
2742: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2743: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2744: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2745: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2746: } else {
2747: $cats = {};
2748: }
2749: } else {
2750: $cats = {};
2751: }
2752: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2753: }
2754: return $cats;
2755: }
2756:
2757: sub get_dom_instcats {
2758: my ($dom) = @_;
2759: return unless (&domain($dom));
2760: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2761: unless (defined($cached)) {
2762: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2763: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2764: if ($totcodes > 0) {
2765: my $caller = 'global';
2766: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2767: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2768: $instcats = {
1.1172.2.146. .10(raeb 2769:-23): totcodes => $totcodes,
1.1172.2.106 raeburn 2770: codes => \%codes,
2771: codetitles => \@codetitles,
2772: cat_titles => \%cat_titles,
2773: cat_order => \%cat_order,
2774: };
2775: &do_cache_new('instcats',$dom,$instcats,3600);
2776: }
2777: }
2778: }
2779: return $instcats;
2780: }
2781:
2782: sub retrieve_instcodes {
2783: my ($coursecodes,$dom) = @_;
2784: my $totcodes;
2785: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2786: foreach my $course (keys(%courses)) {
2787: if (ref($courses{$course}) eq 'HASH') {
2788: if ($courses{$course}{'inst_code'} ne '') {
2789: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2790: $totcodes ++;
2791: }
2792: }
2793: }
2794: return $totcodes;
2795: }
2796:
1.1172.2.113 raeburn 2797: # --------------------------------------------- Get domain config for passwords
2798:
2799: sub get_passwdconf {
2800: my ($dom) = @_;
2801: my (%passwdconf,$gotconf,$lookup);
2802: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2803: if (defined($cached)) {
2804: if (ref($result) eq 'HASH') {
2805: %passwdconf = %{$result};
2806: $gotconf = 1;
2807: }
2808: }
2809: unless ($gotconf) {
2810: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2811: if (ref($domconfig{'passwords'}) eq 'HASH') {
2812: %passwdconf = %{$domconfig{'passwords'}};
2813: }
2814: my $cachetime = 24*60*60;
2815: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2816: }
2817: return %passwdconf;
2818: }
2819:
1.1172.2.146. .1(raebu 2820:22): sub course_portal_url {
2821:22): my ($cnum,$cdom,$r) = @_;
2822:22): my $chome = &homeserver($cnum,$cdom);
2823:22): my $hostname = &hostname($chome);
2824:22): my $protocol = $protocol{$chome};
2825:22): $protocol = 'http' if ($protocol ne 'https');
2826:22): my %domdefaults = &get_domain_defaults($cdom);
2827:22): my $firsturl;
2828:22): if ($domdefaults{'portal_def'}) {
2829:22): $firsturl = $domdefaults{'portal_def'};
2830:22): } else {
2831:22): my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2832:22): $hostname = $alias if ($alias ne '');
2833:22): $firsturl = $protocol.'://'.$hostname;
2834:22): }
2835:22): return $firsturl;
2836:22): }
2837:22):
.12(raeb 2838:-23): sub url_prefix {
2839:-23): my ($r,$dom,$home,$context) = @_;
2840:-23): my $prefix;
2841:-23): my %domdefs = &get_domain_defaults($dom);
2842:-23): if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
2843:-23): if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
2844:-23): $prefix = $1;
2845:-23): }
2846:-23): }
2847:-23): if ($prefix eq '') {
2848:-23): my $hostname = &hostname($home);
2849:-23): my $protocol = $protocol{$home};
2850:-23): $protocol = 'http' if ($protocol{$home} ne 'https');
2851:-23): my $alias = &use_proxy_alias($r,$home);
2852:-23): $hostname = $alias if ($alias ne '');
2853:-23): $prefix = $protocol.'://'.$hostname;
2854:-23): }
2855:-23): return $prefix;
2856:-23): }
2857:-23):
1.344 www 2858: # --------------------------------------------------- Assign a key to a student
2859:
2860: sub assign_access_key {
1.364 www 2861: #
2862: # a valid key looks like uname:udom#comments
2863: # comments are being appended
2864: #
1.498 www 2865: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2866: $kdom=
1.620 albertel 2867: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2868: $knum=
1.620 albertel 2869: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2870: $cdom=
1.620 albertel 2871: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2872: $cnum=
1.620 albertel 2873: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2874: $udom=$env{'user.name'} unless (defined($udom));
2875: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2876: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2877: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2878: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2879: # assigned to this person
2880: # - this should not happen,
1.345 www 2881: # unless something went wrong
2882: # the first time around
2883: # ready to assign
1.364 www 2884: $logentry=$1.'; '.$logentry;
1.496 www 2885: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2886: $kdom,$knum) eq 'ok') {
1.345 www 2887: # key now belongs to user
1.346 www 2888: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2889: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2890: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2891: return 'ok';
2892: } else {
2893: return
2894: 'error: Count not permanently assign key, will need to be re-entered later.';
2895: }
2896: } else {
2897: return 'error: Could not assign key, try again later.';
2898: }
1.364 www 2899: } elsif (!$existing{$ckey}) {
1.345 www 2900: # the key does not exist
2901: return 'error: The key does not exist';
2902: } else {
2903: # the key is somebody else's
2904: return 'error: The key is already in use';
2905: }
1.344 www 2906: }
2907:
1.364 www 2908: # ------------------------------------------ put an additional comment on a key
2909:
2910: sub comment_access_key {
2911: #
2912: # a valid key looks like uname:udom#comments
2913: # comments are being appended
2914: #
2915: my ($ckey,$cdom,$cnum,$logentry)=@_;
2916: $cdom=
1.620 albertel 2917: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2918: $cnum=
1.620 albertel 2919: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2920: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2921: if ($existing{$ckey}) {
2922: $existing{$ckey}.='; '.$logentry;
2923: # ready to assign
1.367 www 2924: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2925: $cdom,$cnum) eq 'ok') {
2926: return 'ok';
2927: } else {
2928: return 'error: Count not store comment.';
2929: }
2930: } else {
2931: # the key does not exist
2932: return 'error: The key does not exist';
2933: }
2934: }
2935:
1.344 www 2936: # ------------------------------------------------------ Generate a set of keys
2937:
2938: sub generate_access_keys {
1.364 www 2939: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2940: $cdom=
1.620 albertel 2941: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2942: $cnum=
1.620 albertel 2943: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2944: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2945: unless (($cdom) && ($cnum)) { return 0; }
2946: if ($number>10000) { return 0; }
2947: sleep(2); # make sure don't get same seed twice
2948: srand(time()^($$+($$<<15))); # from "Programming Perl"
2949: my $total=0;
2950: for (my $i=1;$i<=$number;$i++) {
2951: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2952: sprintf("%lx",int(100000*rand)).'-'.
2953: sprintf("%lx",int(100000*rand));
2954: $newkey=~s/1/g/g; # folks mix up 1 and l
2955: $newkey=~s/0/h/g; # and also 0 and O
2956: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2957: if ($existing{$newkey}) {
2958: $i--;
2959: } else {
1.364 www 2960: if (&put('accesskeys',
2961: { $newkey => '# generated '.localtime().
1.620 albertel 2962: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2963: '; '.$logentry },
2964: $cdom,$cnum) eq 'ok') {
1.344 www 2965: $total++;
2966: }
2967: }
2968: }
1.620 albertel 2969: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2970: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2971: return $total;
2972: }
2973:
2974: # ------------------------------------------------------- Validate an accesskey
2975:
2976: sub validate_access_key {
2977: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2978: $cdom=
1.620 albertel 2979: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2980: $cnum=
1.620 albertel 2981: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2982: $udom=$env{'user.domain'} unless (defined($udom));
2983: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2984: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2985: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2986: }
2987:
2988: # ------------------------------------- Find the section of student in a course
1.652 albertel 2989: sub devalidate_getsection_cache {
2990: my ($udom,$unam,$courseid)=@_;
2991: my $hashid="$udom:$unam:$courseid";
2992: &devalidate_cache_new('getsection',$hashid);
2993: }
1.298 matthew 2994:
1.815 albertel 2995: sub courseid_to_courseurl {
2996: my ($courseid) = @_;
2997: #already url style courseid
2998: return $courseid if ($courseid =~ m{^/});
2999:
3000: if (exists($env{'course.'.$courseid.'.num'})) {
3001: my $cnum = $env{'course.'.$courseid.'.num'};
3002: my $cdom = $env{'course.'.$courseid.'.domain'};
3003: return "/$cdom/$cnum";
3004: }
3005:
3006: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3007: if (exists($courseinfo{'num'})) {
3008: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3009: }
3010:
3011: return undef;
3012: }
3013:
1.298 matthew 3014: sub getsection {
3015: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3016: my $cachetime=1800;
1.551 albertel 3017:
3018: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3019: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3020: if (defined($cached)) { return $result; }
3021:
1.298 matthew 3022: my %Pending;
3023: my %Expired;
3024: #
3025: # Each role can either have not started yet (pending), be active,
3026: # or have expired.
3027: #
3028: # If there is an active role, we are done.
3029: #
3030: # If there is more than one role which has not started yet,
3031: # choose the one which will start sooner
3032: # If there is one role which has not started yet, return it.
3033: #
3034: # If there is more than one expired role, choose the one which ended last.
3035: # If there is a role which has expired, return it.
3036: #
1.815 albertel 3037: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3038: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3039: foreach my $key (keys(%roleshash)) {
1.479 albertel 3040: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3041: my $section=$1;
3042: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3043: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3044: my $now=time;
1.548 albertel 3045: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3046: $Expired{$end}=$section;
3047: next;
3048: }
1.548 albertel 3049: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3050: $Pending{$start}=$section;
3051: next;
3052: }
1.599 albertel 3053: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3054: }
3055: #
3056: # Presumedly there will be few matching roles from the above
3057: # loop and the sorting time will be negligible.
3058: if (scalar(keys(%Pending))) {
3059: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3060: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3061: }
3062: if (scalar(keys(%Expired))) {
3063: my @sorted = sort {$a <=> $b} keys(%Expired);
3064: my $time = pop(@sorted);
1.599 albertel 3065: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3066: }
1.599 albertel 3067: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3068: }
1.70 www 3069:
1.599 albertel 3070: sub save_cache {
3071: &purge_remembered();
1.722 albertel 3072: #&Apache::loncommon::validate_page();
1.620 albertel 3073: undef(%env);
1.780 albertel 3074: undef($env_loaded);
1.599 albertel 3075: }
1.452 albertel 3076:
1.599 albertel 3077: my $to_remember=-1;
3078: my %remembered;
3079: my %accessed;
3080: my $kicks=0;
3081: my $hits=0;
1.849 albertel 3082: sub make_key {
3083: my ($name,$id) = @_;
1.872 albertel 3084: if (length($id) > 65
3085: && length(&escape($id)) > 200) {
3086: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3087: }
1.849 albertel 3088: return &escape($name.':'.$id);
3089: }
3090:
1.599 albertel 3091: sub devalidate_cache_new {
3092: my ($name,$id,$debug) = @_;
3093: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 3094: my $remembered_id=$name.':'.$id;
1.849 albertel 3095: $id=&make_key($name,$id);
1.599 albertel 3096: $memcache->delete($id);
1.1172.2.81 raeburn 3097: delete($remembered{$remembered_id});
3098: delete($accessed{$remembered_id});
1.599 albertel 3099: }
3100:
3101: sub is_cached_new {
3102: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 3103: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
3104: # keys in %remembered hash, which persists for
3105: # duration of request (no restriction on key length).
3106: if (exists($remembered{$remembered_id})) {
3107: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3108: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3109: $hits++;
1.1172.2.81 raeburn 3110: return ($remembered{$remembered_id},1);
1.599 albertel 3111: }
1.1172.2.81 raeburn 3112: $id=&make_key($name,$id);
1.599 albertel 3113: my $value = $memcache->get($id);
3114: if (!(defined($value))) {
3115: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3116: return (undef,undef);
1.416 albertel 3117: }
1.599 albertel 3118: if ($value eq '__undef__') {
3119: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3120: $value=undef;
3121: }
1.1172.2.81 raeburn 3122: &make_room($remembered_id,$value,$debug);
1.599 albertel 3123: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3124: return ($value,1);
3125: }
3126:
3127: sub do_cache_new {
3128: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 3129: my $remembered_id=$name.':'.$id;
1.849 albertel 3130: $id=&make_key($name,$id);
1.599 albertel 3131: my $setvalue=$value;
3132: if (!defined($setvalue)) {
3133: $setvalue='__undef__';
3134: }
1.623 albertel 3135: if (!defined($time) ) {
3136: $time=600;
3137: }
1.599 albertel 3138: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3139: my $result = $memcache->set($id,$setvalue,$time);
3140: if (! $result) {
1.872 albertel 3141: &logthis("caching of id -> $id failed");
1.910 albertel 3142: $memcache->disconnect_all();
1.872 albertel 3143: }
1.600 albertel 3144: # need to make a copy of $value
1.1172.2.81 raeburn 3145: &make_room($remembered_id,$value,$debug);
1.599 albertel 3146: return $value;
3147: }
3148:
3149: sub make_room {
1.1172.2.81 raeburn 3150: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3151:
1.1172.2.81 raeburn 3152: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3153: : $value;
1.599 albertel 3154: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 3155: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3156: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3157: my $to_kick;
3158: my $max_time=0;
3159: foreach my $other (keys(%accessed)) {
3160: if (&tv_interval($accessed{$other}) > $max_time) {
3161: $to_kick=$other;
3162: $max_time=&tv_interval($accessed{$other});
3163: }
3164: }
3165: delete($remembered{$to_kick});
3166: delete($accessed{$to_kick});
3167: $kicks++;
3168: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3169: return;
3170: }
3171:
1.599 albertel 3172: sub purge_remembered {
1.604 albertel 3173: #&logthis("Tossing ".scalar(keys(%remembered)));
3174: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3175: undef(%remembered);
3176: undef(%accessed);
1.428 albertel 3177: }
1.70 www 3178: # ------------------------------------- Read an entry from a user's environment
3179:
3180: sub userenvironment {
3181: my ($udom,$unam,@what)=@_;
1.976 raeburn 3182: my $items;
3183: foreach my $item (@what) {
3184: $items.=&escape($item).'&';
3185: }
3186: $items=~s/\&$//;
1.70 www 3187: my %returnhash=();
1.1009 raeburn 3188: my $uhome = &homeserver($unam,$udom);
3189: unless ($uhome eq 'no_host') {
3190: my @answer=split(/\&/,
3191: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3192: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3193: return %returnhash;
3194: }
1.1009 raeburn 3195: my $i;
3196: for ($i=0;$i<=$#what;$i++) {
3197: $returnhash{$what[$i]}=&unescape($answer[$i]);
3198: }
1.70 www 3199: }
3200: return %returnhash;
1.1 albertel 3201: }
3202:
1.617 albertel 3203: # ---------------------------------------------------------- Get a studentphoto
3204: sub studentphoto {
3205: my ($udom,$unam,$ext) = @_;
3206: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3207: if (defined($env{'request.course.id'})) {
1.708 raeburn 3208: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3209: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3210: return(&retrievestudentphoto($udom,$unam,$ext));
3211: } else {
3212: my ($result,$perm_reqd)=
1.707 albertel 3213: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3214: if ($result eq 'ok') {
3215: if (!($perm_reqd eq 'yes')) {
3216: return(&retrievestudentphoto($udom,$unam,$ext));
3217: }
3218: }
3219: }
3220: }
3221: } else {
3222: my ($result,$perm_reqd) =
1.707 albertel 3223: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3224: if ($result eq 'ok') {
3225: if (!($perm_reqd eq 'yes')) {
3226: return(&retrievestudentphoto($udom,$unam,$ext));
3227: }
3228: }
3229: }
3230: return '/adm/lonKaputt/lonlogo_broken.gif';
3231: }
3232:
3233: sub retrievestudentphoto {
3234: my ($udom,$unam,$ext,$type) = @_;
3235: my $home=&Apache::lonnet::homeserver($unam,$udom);
3236: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3237: if ($ret eq 'ok') {
3238: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3239: if ($type eq 'thumbnail') {
3240: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3241: }
3242: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3243: return $tokenurl;
3244: } else {
3245: if ($type eq 'thumbnail') {
3246: return '/adm/lonKaputt/genericstudent_tn.gif';
3247: } else {
3248: return '/adm/lonKaputt/lonlogo_broken.gif';
3249: }
1.617 albertel 3250: }
3251: }
3252:
1.263 www 3253: # -------------------------------------------------------------------- New chat
3254:
3255: sub chatsend {
1.724 raeburn 3256: my ($newentry,$anon,$group)=@_;
1.620 albertel 3257: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3258: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3259: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3260: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3261: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3262: &escape($newentry)).':'.$group,$chome);
1.292 www 3263: }
3264:
3265: # ------------------------------------------ Find current version of a resource
3266:
3267: sub getversion {
3268: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3269: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3270: return ¤tversion(&filelocation('',$fname));
3271: }
3272:
3273: sub currentversion {
3274: my $fname=shift;
3275: my $author=$fname;
3276: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3277: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3278: my $home=&homeserver($uname,$udom);
1.292 www 3279: if ($home eq 'no_host') {
3280: return -1;
3281: }
1.1112 www 3282: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3283: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3284: return -1;
3285: }
1.1112 www 3286: return $answer;
1.263 www 3287: }
3288:
1.1111 www 3289: #
3290: # Return special version number of resource if set by override, empty otherwise
3291: #
3292: sub usedversion {
3293: my $fname=shift;
3294: unless ($fname) { $fname=$env{'request.uri'}; }
3295: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3296: if ($urlversion) { return $urlversion; }
3297: return '';
3298: }
3299:
1.1 albertel 3300: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3301:
1.1 albertel 3302: sub subscribe {
3303: my $fname=shift;
1.761 raeburn 3304: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3305: $fname=~s/[\n\r]//g;
1.1 albertel 3306: my $author=$fname;
3307: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3308: my ($udom,$uname)=split(/\//,$author);
3309: my $home=homeserver($uname,$udom);
1.335 albertel 3310: if ($home eq 'no_host') {
3311: return 'not_found';
1.1 albertel 3312: }
3313: my $answer=reply("sub:$fname",$home);
1.64 www 3314: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3315: $answer.=' by '.$home;
3316: }
1.1 albertel 3317: return $answer;
3318: }
3319:
1.8 www 3320: # -------------------------------------------------------------- Replicate file
3321:
3322: sub repcopy {
3323: my $filename=shift;
1.23 www 3324: $filename=~s/\/+/\//g;
1.1142 raeburn 3325: my $londocroot = $perlvar{'lonDocRoot'};
3326: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3327: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3328: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3329: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3330: return &repcopy_userfile($filename);
3331: }
1.532 albertel 3332: $filename=~s/[\n\r]//g;
1.8 www 3333: my $transname="$filename.in.transfer";
1.828 www 3334: # FIXME: this should flock
1.607 raeburn 3335: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3336: my $remoteurl=subscribe($filename);
1.64 www 3337: if ($remoteurl =~ /^con_lost by/) {
3338: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3339: return 'unavailable';
1.8 www 3340: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3341: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3342: return 'not_found';
1.64 www 3343: } elsif ($remoteurl =~ /^rejected by/) {
3344: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3345: return 'forbidden';
1.20 www 3346: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3347: return 'ok';
1.8 www 3348: } else {
1.290 www 3349: my $author=$filename;
3350: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3351: my ($udom,$uname)=split(/\//,$author);
3352: my $home=homeserver($uname,$udom);
3353: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3354: my @parts=split(/\//,$filename);
3355: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3356: if ($path ne "$londocroot/res") {
1.8 www 3357: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3358: return 'bad_request';
1.8 www 3359: }
3360: my $count;
3361: for ($count=5;$count<$#parts;$count++) {
3362: $path.="/$parts[$count]";
3363: if ((-e $path)!=1) {
3364: mkdir($path,0777);
3365: }
3366: }
3367: my $ua=new LWP::UserAgent;
3368: my $request=new HTTP::Request('GET',"$remoteurl");
3369: my $response=$ua->request($request,$transname);
3370: if ($response->is_error()) {
3371: unlink($transname);
3372: my $message=$response->status_line;
1.672 albertel 3373: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3374: ." LWP get: $message: $filename</font>");
1.607 raeburn 3375: return 'unavailable';
1.8 www 3376: } else {
1.16 www 3377: if ($remoteurl!~/\.meta$/) {
3378: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3379: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3380: if ($mresponse->is_error()) {
3381: unlink($filename.'.meta');
3382: &logthis(
1.672 albertel 3383: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3384: }
3385: }
1.8 www 3386: rename($transname,$filename);
1.607 raeburn 3387: return 'ok';
1.8 www 3388: }
1.290 www 3389: }
1.8 www 3390: }
1.330 www 3391: }
3392:
1.1172.2.124 raeburn 3393: # ------------------------------------------------- Unsubscribe from a resource
3394:
3395: sub unsubscribe {
3396: my ($fname) = @_;
3397: my $answer;
3398: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3399: $fname=~s/[\n\r]//g;
3400: my $author=$fname;
3401: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3402: my ($udom,$uname)=split(/\//,$author);
3403: my $home=homeserver($uname,$udom);
3404: if ($home eq 'no_host') {
3405: $answer = 'no_host';
3406: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3407: $answer = 'home';
3408: } else {
1.1172.2.125 raeburn 3409: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3410: }
3411: return $answer;
3412: }
3413:
1.330 www 3414: # ------------------------------------------------ Get server side include body
3415: sub ssi_body {
1.381 albertel 3416: my ($filelink,%form)=@_;
1.606 matthew 3417: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3418: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3419: }
1.953 www 3420: my $output='';
3421: my $response;
1.980 raeburn 3422: if ($filelink=~/^https?\:/) {
1.954 raeburn 3423: ($output,$response)=&externalssi($filelink);
1.953 www 3424: } else {
1.1004 droeschl 3425: $filelink .= $filelink=~/\?/ ? '&' : '?';
3426: $filelink .= 'inhibitmenu=yes';
1.953 www 3427: ($output,$response)=&ssi($filelink,%form);
3428: }
1.778 albertel 3429: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3430: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3431: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3432: if (wantarray) {
3433: return ($output, $response);
3434: } else {
3435: return $output;
3436: }
1.8 www 3437: }
3438:
1.15 www 3439: # --------------------------------------------------------- Server Side Include
3440:
1.782 albertel 3441: sub absolute_url {
1.1172.2.145 raeburn 3442: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3443: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3444: if ($host_name eq '') {
3445: $host_name = $ENV{'SERVER_NAME'};
3446: }
1.1172.2.145 raeburn 3447: if ($unalias) {
3448: my $alias = &get_proxy_alias();
3449: if ($alias eq $host_name) {
3450: my $lonhost = $perlvar{'lonHostID'};
3451: my $hostname = &hostname($lonhost);
3452: my $lcproto;
3453: if (($keep_proto) || ($hostname eq '')) {
3454: $lcproto = $protocol;
3455: } else {
3456: $lcproto = $protocol{$lonhost};
3457: $lcproto = 'http' if ($lcproto ne 'https');
3458: $lcproto .= '://';
3459: }
3460: unless ($hostname eq '') {
3461: return $lcproto.$hostname;
3462: }
3463: }
3464: }
1.782 albertel 3465: return $protocol.$host_name;
3466: }
3467:
1.942 foxr 3468: #
3469: # Server side include.
3470: # Parameters:
3471: # fn Possibly encrypted resource name/id.
3472: # form Hash that describes how the rendering should be done
3473: # and other things.
1.944 foxr 3474: # Returns:
1.950 raeburn 3475: # Scalar context: The content of the response.
3476: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3477: #
1.15 www 3478: sub ssi {
3479:
1.944 foxr 3480: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3481: my ($host,$request,$response);
3482: $host = &absolute_url('',1);
1.711 albertel 3483:
3484: $form{'no_update_last_known'}=1;
1.895 albertel 3485: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3486: if (%form) {
1.1172.2.145 raeburn 3487: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3488: $request->content(join('&',map {
3489: my $name = escape($_);
3490: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3491: ? join("&$name=", map {escape($_) } @{$form{$_}})
3492: : &escape($form{$_}) );
3493: } keys(%form)));
1.23 www 3494: } else {
1.1172.2.145 raeburn 3495: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3496: }
3497:
1.15 www 3498: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3499:
1.1172.2.101 raeburn 3500: if (($env{'request.course.id'}) &&
3501: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3502: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3503: ($form{'grade_symb'} ne '') &&
3504: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3505: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3506: if (LWP::UserAgent->VERSION >= 5.834) {
3507: my $ua=new LWP::UserAgent;
3508: $ua->local_address('127.0.0.1');
3509: $response = $ua->request($request);
3510: } else {
3511: {
3512: require LWP::Protocol::http;
3513: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3514: my $ua=new LWP::UserAgent;
3515: $response = $ua->request($request);
3516: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3517: }
3518: }
3519: } else {
3520: my $ua=new LWP::UserAgent;
3521: $response = $ua->request($request);
3522: }
1.944 foxr 3523: if (wantarray) {
1.1172.2.3 raeburn 3524: return ($response->content, $response);
1.944 foxr 3525: } else {
1.1172.2.3 raeburn 3526: return $response->content;
1.942 foxr 3527: }
1.324 www 3528: }
3529:
3530: sub externalssi {
3531: my ($url)=@_;
3532: my $ua=new LWP::UserAgent;
3533: my $request=new HTTP::Request('GET',$url);
3534: my $response=$ua->request($request);
1.954 raeburn 3535: if (wantarray) {
3536: return ($response->content, $response);
3537: } else {
3538: return $response->content;
3539: }
1.15 www 3540: }
1.254 www 3541:
1.1172.2.98 raeburn 3542: # If the local copy of a replicated resource is outdated, trigger a
3543: # connection from the homeserver to flush the delayed queue. If no update
3544: # happens, remove local copies of outdated resource (and corresponding
3545: # metadata file).
3546:
3547: sub remove_stale_resfile {
3548: my ($url) = @_;
3549: my $removed;
3550: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3551: my $audom = $1;
3552: my $auname = $2;
3553: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3554: my $homeserver = &homeserver($auname,$audom);
3555: unless (($homeserver eq 'no_host') ||
3556: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3557: my $fname = &filelocation('',$url);
3558: if (-e $fname) {
3559: my $hostname = &hostname($homeserver);
3560: if ($hostname) {
1.1172.2.120 raeburn 3561: my $protocol = $protocol{$homeserver};
3562: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3563: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3564: my $ua=new LWP::UserAgent;
3565: $ua->timeout(5);
1.1172.2.98 raeburn 3566: my $request=new HTTP::Request('HEAD',$uri);
3567: my $response=$ua->request($request);
3568: if ($response->is_success()) {
3569: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3570: my $locmodtime = (stat($fname))[9];
3571: if ($locmodtime < $remmodtime) {
3572: my $stale;
3573: my $answer = &reply('pong',$homeserver);
3574: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3575: sleep(0.2);
3576: $locmodtime = (stat($fname))[9];
3577: if ($locmodtime < $remmodtime) {
3578: my $posstransfer = $fname.'.in.transfer';
3579: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3580: $removed = 1;
3581: } else {
3582: $stale = 1;
3583: }
3584: } else {
3585: $removed = 1;
3586: }
3587: } else {
3588: $stale = 1;
3589: }
3590: if ($stale) {
1.1172.2.124 raeburn 3591: if (unlink($fname)) {
3592: if ($uri!~/\.meta$/) {
3593: if (-e $fname.'.meta') {
3594: unlink($fname.'.meta');
3595: }
3596: }
3597: my $unsubresult = &unsubscribe($fname);
3598: unless ($unsubresult eq 'ok') {
3599: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3600: }
3601: $removed = 1;
1.1172.2.98 raeburn 3602: }
3603: }
3604: }
3605: }
3606: }
3607: }
3608: }
3609: }
3610: }
3611: return $removed;
3612: }
3613:
1.492 albertel 3614: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3615:
3616: sub allowuploaded {
3617: my ($srcurl,$url)=@_;
3618: $url=&clutter(&declutter($url));
3619: my $dir=$url;
3620: $dir=~s/\/[^\/]+$//;
3621: my %httpref=();
3622: my $httpurl=&hreflocation('',$url);
3623: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3624: &Apache::lonnet::appenv(\%httpref);
1.254 www 3625: }
1.477 raeburn 3626:
1.1172.2.13 raeburn 3627: #
3628: # Determine if the current user should be able to edit a particular resource,
3629: # when viewing in course context.
3630: # (a) When viewing resource used to determine if "Edit" item is included in
3631: # Functions.
3632: # (b) When displaying folder contents in course editor, used to determine if
3633: # "Edit" link will be displayed alongside resource.
3634: #
3635: # input: six args -- filename (decluttered), course number, course domain,
3636: # url, symb (if registered) and group (if this is a group
3637: # item -- e.g., bulletin board, group page etc.).
3638: # output: array of five scalars --
3639: # $cfile -- url for file editing if editable on current server
3640: # $home -- homeserver of resource (i.e., for author if published,
3641: # or course if uploaded.).
3642: # $switchserver -- 1 if server switch will be needed.
3643: # $forceedit -- 1 if icon/link should be to go to edit mode
3644: # $forceview -- 1 if icon/link should be to go to view mode
3645: #
3646:
3647: sub can_edit_resource {
3648: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3649: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3650: #
3651: # For aboutme pages user can only edit his/her own.
3652: #
3653: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3654: my ($sdom,$sname) = ($1,$2);
3655: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3656: $home = $env{'user.home'};
3657: $cfile = $resurl;
3658: if ($env{'form.forceedit'}) {
3659: $forceview = 1;
3660: } else {
3661: $forceedit = 1;
3662: }
3663: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3664: } else {
3665: return;
3666: }
3667: }
3668:
3669: if ($env{'request.course.id'}) {
3670: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3671: if ($group ne '') {
3672: # if this is a group homepage or group bulletin board, check group privs
3673: my $allowed = 0;
3674: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3675: if ((&allowed('mdg',$env{'request.course.id'}.
3676: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3677: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3678: $allowed = 1;
3679: }
3680: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3681: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3682: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3683: $allowed = 1;
3684: }
3685: }
3686: if ($allowed) {
3687: $home=&homeserver($cnum,$cdom);
3688: if ($env{'form.forceedit'}) {
3689: $forceview = 1;
3690: } else {
3691: $forceedit = 1;
3692: }
3693: $cfile = $resurl;
3694: } else {
3695: return;
3696: }
3697: } else {
1.1172.2.15 raeburn 3698: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3699: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3700: return;
3701: }
3702: } elsif (!$crsedit) {
1.1172.2.146. .21(raeb 3703:-24): if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1172.2.13 raeburn 3704: #
3705: # No edit allowed where CC has switched to student role.
3706: #
1.1172.2.146. .21(raeb 3707:-24): return;
3708:-24): } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
3709:-24): ($resurl =~ m{^/res/lib/templates/})) {
3710:-24): return;
3711:-24): }
1.1172.2.13 raeburn 3712: }
3713: }
3714: }
3715:
3716: if ($file ne '') {
3717: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3718: if (&is_course_upload($file,$cnum,$cdom)) {
3719: $uploaded = 1;
3720: $incourse = 1;
3721: if ($file =~/\.(htm|html|css|js|txt)$/) {
3722: $cfile = &hreflocation('',$file);
3723: if ($env{'form.forceedit'}) {
3724: $forceview = 1;
3725: } else {
3726: $forceedit = 1;
3727: }
3728: }
3729: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3730: $incourse = 1;
3731: if ($env{'form.forceedit'}) {
3732: $forceview = 1;
3733: } else {
3734: $forceedit = 1;
3735: }
3736: $cfile = $resurl;
3737: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3738: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3739: $incourse = 1;
3740: if ($env{'form.forceedit'}) {
3741: $forceview = 1;
3742: } else {
3743: $forceedit = 1;
3744: }
3745: $cfile = $resurl;
3746: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3747: $incourse = 1;
3748: $cfile = $resurl.'/smpedit';
3749: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3750: $incourse = 1;
3751: if ($env{'form.forceedit'}) {
3752: $forceview = 1;
3753: } else {
3754: $forceedit = 1;
3755: }
3756: $cfile = $resurl;
1.1172.2.122 raeburn 3757: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3758: my ($map,$id,$res) = &decode_symb($symb);
3759: if ($map =~ /\.page$/) {
3760: $incourse = 1;
3761: if ($env{'form.forceedit'}) {
3762: $forceview = 1;
3763: $cfile = $map;
3764: } else {
3765: $forceedit = 1;
3766: $cfile = '/adm/wrapper'.$resurl;
3767: }
3768: }
1.1172.2.146. .1(raebu 3769:22): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3770:22): $incourse = 1;
3771:22): if ($env{'form.forceedit'}) {
3772:22): $forceview = 1;
3773:22): } else {
3774:22): $forceedit = 1;
3775:22): }
3776:22): $cfile = $resurl;
1.1172.2.15 raeburn 3777: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3778: $incourse = 1;
3779: if ($env{'form.forceedit'}) {
3780: $forceview = 1;
3781: } else {
3782: $forceedit = 1;
3783: }
3784: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3785: }
3786: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3787: my $template = '/res/lib/templates/simpleproblem.problem';
3788: if (&is_on_map($template)) {
3789: $incourse = 1;
3790: $forceview = 1;
3791: $cfile = $template;
3792: }
3793: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3794: $incourse = 1;
3795: if ($env{'form.forceedit'}) {
3796: $forceview = 1;
3797: } else {
3798: $forceedit = 1;
3799: }
3800: $cfile = $resurl;
1.1172.2.146. .1(raebu 3801:22): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3802:22): $incourse = 1;
3803:22): if ($env{'form.forceedit'}) {
3804:22): $forceview = 1;
3805:22): } else {
3806:22): $forceedit = 1;
3807:22): }
3808:22): $cfile = $resurl;
1.1172.2.13 raeburn 3809: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3810: $incourse = 1;
3811: $forceview = 1;
3812: if ($symb) {
3813: my ($map,$id,$res)=&decode_symb($symb);
3814: $env{'request.symb'} = $symb;
3815: $cfile = &clutter($res);
3816: } else {
3817: $cfile = $env{'form.suppurl'};
1.1172.2.146. .1(raebu 3818:22): my $escfile = &unescape($cfile);
3819:22): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3820:22): $cfile = '/adm/wrapper'.$escfile;
3821:22): } else {
3822:22): $escfile =~ s{^http://}{};
3823:22): $cfile = &escape("/adm/wrapper/ext/$escfile");
3824:22): }
1.1172.2.13 raeburn 3825: }
1.1172.2.31 raeburn 3826: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3827: if ($env{'form.forceedit'}) {
3828: $forceview = 1;
3829: } else {
3830: $forceedit = 1;
3831: }
3832: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3833: }
3834: }
3835: if ($uploaded || $incourse) {
3836: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3837: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3838: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3839: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3840: # Check that the user has permission to edit this resource
3841: my $setpriv = 1;
3842: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3843: if (defined($cfudom)) {
3844: $home=&homeserver($cfuname,$cfudom);
3845: $cfile=$file;
3846: }
3847: }
3848: if (($cfile ne '') && (!$incourse || $uploaded) &&
3849: (($home ne '') && ($home ne 'no_host'))) {
3850: my @ids=¤t_machine_ids();
3851: unless (grep(/^\Q$home\E$/,@ids)) {
3852: $switchserver=1;
3853: }
3854: }
3855: }
3856: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3857: }
3858:
3859: sub is_course_upload {
3860: my ($file,$cnum,$cdom) = @_;
3861: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3862: $uploadpath =~ s{^\/}{};
3863: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3864: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3865: return 1;
3866: }
3867: return;
3868: }
3869:
3870: sub in_course {
3871: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3872: if ($hideprivileged) {
3873: my $skipuser;
1.1172.2.23 raeburn 3874: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3875: my @possdoms = ($cdom);
3876: if ($coursehash{'checkforpriv'}) {
3877: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3878: }
3879: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3880: $skipuser = 1;
3881: if ($coursehash{'nothideprivileged'}) {
3882: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3883: my $user;
3884: if ($item =~ /:/) {
3885: $user = $item;
3886: } else {
3887: $user = join(':',split(/[\@]/,$item));
3888: }
3889: if ($user eq $uname.':'.$udom) {
3890: undef($skipuser);
3891: last;
3892: }
3893: }
3894: }
3895: if ($skipuser) {
3896: return 0;
3897: }
3898: }
3899: }
3900: $type ||= 'any';
3901: if (!defined($cdom) || !defined($cnum)) {
3902: my $cid = $env{'request.course.id'};
3903: $cdom = $env{'course.'.$cid.'.domain'};
3904: $cnum = $env{'course.'.$cid.'.num'};
3905: }
3906: my $typesref;
3907: if (($type eq 'any') || ($type eq 'all')) {
3908: $typesref = ['active','previous','future'];
3909: } elsif ($type eq 'previous' || $type eq 'future') {
3910: $typesref = [$type];
3911: }
3912: my %roles = &get_my_roles($uname,$udom,'userroles',
3913: $typesref,undef,[$cdom]);
3914: my ($tmp) = keys(%roles);
3915: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3916: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3917: if (@course_roles > 0) {
3918: return 1;
3919: }
3920: return 0;
3921: }
3922:
1.478 albertel 3923: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3924: # input: action, courseID, current domain, intended
1.637 raeburn 3925: # path to file, source of file, instruction to parse file for objects,
3926: # ref to hash for embedded objects,
3927: # ref to hash for codebase of java objects.
1.1095 raeburn 3928: # reference to scalar to accommodate mime type determined
3929: # from File::MMagic if $parser = parse.
1.637 raeburn 3930: #
1.485 raeburn 3931: # output: url to file (if action was uploaddoc),
3932: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3933: #
1.478 albertel 3934: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3935: # course.
1.477 raeburn 3936: #
1.478 albertel 3937: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3938: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3939: # course's home server.
1.477 raeburn 3940: #
1.478 albertel 3941: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3942: # be copied from $source (current location) to
3943: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3944: # and will then be copied to
3945: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3946: # course's home server.
1.485 raeburn 3947: #
1.481 raeburn 3948: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3949: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3950: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3951: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3952: # in course's home server.
1.637 raeburn 3953: #
1.477 raeburn 3954:
3955: sub process_coursefile {
1.1095 raeburn 3956: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3957: $mimetype)=@_;
1.477 raeburn 3958: my $fetchresult;
1.638 albertel 3959: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3960: if ($action eq 'propagate') {
1.638 albertel 3961: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3962: $home);
1.481 raeburn 3963: } else {
1.477 raeburn 3964: my $fpath = '';
3965: my $fname = $file;
1.478 albertel 3966: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3967: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3968: my $filepath = &build_filepath($fpath);
1.481 raeburn 3969: if ($action eq 'copy') {
3970: if ($source eq '') {
3971: $fetchresult = 'no source file';
3972: return $fetchresult;
3973: } else {
3974: my $destination = $filepath.'/'.$fname;
3975: rename($source,$destination);
3976: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3977: $home);
1.481 raeburn 3978: }
3979: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3980: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3981: print $fh $env{'form.'.$source};
1.481 raeburn 3982: close($fh);
1.637 raeburn 3983: if ($parser eq 'parse') {
1.1024 raeburn 3984: my $mm = new File::MMagic;
1.1095 raeburn 3985: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3986: if ($type eq 'text/html') {
1.1024 raeburn 3987: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3988: unless ($parse_result eq 'ok') {
3989: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3990: }
1.637 raeburn 3991: }
1.1095 raeburn 3992: if (ref($mimetype)) {
3993: $$mimetype = $type;
3994: }
1.637 raeburn 3995: }
1.477 raeburn 3996: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3997: $home);
1.481 raeburn 3998: if ($fetchresult eq 'ok') {
3999: return '/uploaded/'.$fpath.'/'.$fname;
4000: } else {
4001: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4002: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4003: return '/adm/notfound.html';
4004: }
1.477 raeburn 4005: }
4006: }
1.485 raeburn 4007: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4008: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4009: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4010: }
4011: return $fetchresult;
4012: }
4013:
1.637 raeburn 4014: sub build_filepath {
4015: my ($fpath) = @_;
4016: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4017: unless ($fpath eq '') {
4018: my @parts=split('/',$fpath);
4019: foreach my $part (@parts) {
4020: $filepath.= '/'.$part;
4021: if ((-e $filepath)!=1) {
4022: mkdir($filepath,0777);
4023: }
4024: }
4025: }
4026: return $filepath;
4027: }
4028:
4029: sub store_edited_file {
1.638 albertel 4030: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4031: my $file = $primary_url;
4032: $file =~ s#^/uploaded/$docudom/$docuname/##;
4033: my $fpath = '';
4034: my $fname = $file;
4035: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4036: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4037: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 4038: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4039: print $fh $content;
4040: close($fh);
1.638 albertel 4041: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4042: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4043: $home);
1.637 raeburn 4044: if ($$fetchresult eq 'ok') {
4045: return '/uploaded/'.$fpath.'/'.$fname;
4046: } else {
1.638 albertel 4047: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4048: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4049: return '/adm/notfound.html';
4050: }
4051: }
4052:
1.531 albertel 4053: sub clean_filename {
1.831 albertel 4054: my ($fname,$args)=@_;
1.315 www 4055: # Replace Windows backslashes by forward slashes
1.257 www 4056: $fname=~s/\\/\//g;
1.831 albertel 4057: if (!$args->{'keep_path'}) {
4058: # Get rid of everything but the actual filename
4059: $fname=~s/^.*\/([^\/]+)$/$1/;
4060: }
1.315 www 4061: # Replace spaces by underscores
4062: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 4063: # Transliterate non-ascii text to ascii
4064: my $lang = &Apache::lonlocal::current_language();
4065: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4066: # Replace all other weird characters by nothing
1.831 albertel 4067: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4068: # Replace all .\d. sequences with _\d. so they no longer look like version
4069: # numbers
4070: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 4071: # Replace three or more adjacent underscores with one for consistency
4072: # with loncfile::filename_check() so complete url can be extracted by
4073: # lonnet::decode_symb()
4074: $fname=~s/_{3,}/_/g;
1.531 albertel 4075: return $fname;
4076: }
1.1172.2.110 raeburn 4077:
1.1051 raeburn 4078: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4079: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4080: # image with the same aspect ratio as the original, but with dimensions which do
4081: # not exceed $resizewidth and $resizeheight.
4082:
1.984 neumanie 4083: sub resizeImage {
1.1051 raeburn 4084: my ($img_path,$resizewidth,$resizeheight) = @_;
4085: my $ima = Image::Magick->new;
4086: my $resized;
4087: if (-e $img_path) {
4088: $ima->Read($img_path);
4089: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4090: my $width = $ima->Get('width');
4091: my $height = $ima->Get('height');
4092: if ($width > $resizewidth) {
4093: my $factor = $width/$resizewidth;
4094: my $newheight = $height/$factor;
4095: $ima->Scale(width=>$resizewidth,height=>$newheight);
4096: $resized = 1;
4097: }
4098: }
4099: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4100: my $width = $ima->Get('width');
4101: my $height = $ima->Get('height');
4102: if ($height > $resizeheight) {
4103: my $factor = $height/$resizeheight;
4104: my $newwidth = $width/$factor;
4105: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4106: $resized = 1;
4107: }
4108: }
4109: if ($resized) {
4110: $ima->Write($img_path);
4111: }
4112: }
4113: return;
1.977 amueller 4114: }
4115:
1.608 albertel 4116: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4117: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4118: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4119: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.146. .13(raeb 4120:-23): # canceloverwrite, scantron, toollogo or ''.
1.1090 raeburn 4121: # if 'coursedoc': upload to the current course
4122: # if 'existingfile': write file to tmp/overwrites directory
4123: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4124: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4125: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 4126: # $parser - instruction to parse file for objects ($parser = parse) or
4127: # if context is 'scantron', $parser is hashref of csv column mapping
4128: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4129: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4130: # $allfiles - reference to hash for embedded objects
4131: # $codebase - reference to hash for codebase of java objects
1.1172.2.146. .13(raeb 4132:-23): # $destuname - username for permanent storage of uploaded file
4133:-23): # $destudom - domain for permanaent storage of uploaded file
1.860 raeburn 4134: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4135: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4136: # $resizewidth - width (pixels) to which to resize uploaded image
4137: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4138: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4139: # from File::MMagic.
1.858 raeburn 4140: #
1.686 albertel 4141: # output: url of file in userspace, or error: <message>
4142: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4143:
1.531 albertel 4144: sub userfileupload {
1.1090 raeburn 4145: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4146: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4147: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4148: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4149: $fname=&clean_filename($fname);
1.1090 raeburn 4150: # See if there is anything left
1.257 www 4151: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 4152: # If filename now begins with a . prepend unix timestamp _ milliseconds
4153: if ($fname =~ /^\./) {
4154: my ($s,$usec) = &gettimeofday();
4155: while (length($usec) < 6) {
4156: $usec = '0'.$usec;
4157: }
4158: $fname = $s.'_'.substr($usec,0,3).$fname;
4159: }
1.1090 raeburn 4160: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4161: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4162: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4163: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4164: my $now = time;
1.1090 raeburn 4165: my $filepath;
1.1095 raeburn 4166: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4167: $filepath = 'tmp/helprequests/'.$now;
4168: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4169: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4170: '_'.$env{'user.domain'}.'/pending';
4171: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4172: my ($docuname,$docudom);
1.1172.2.96 raeburn 4173: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4174: $docudom = $destudom;
4175: } else {
4176: $docudom = $env{'user.domain'};
4177: }
1.1172.2.96 raeburn 4178: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4179: $docuname = $destuname;
4180: } else {
4181: $docuname = $env{'user.name'};
4182: }
4183: if (exists($env{'form.group'})) {
4184: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4185: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4186: }
4187: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4188: if ($context eq 'canceloverwrite') {
4189: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4190: if (-e $tempfile) {
4191: my @info = stat($tempfile);
4192: if ($info[9] eq $env{'form.timestamp'}) {
4193: unlink($tempfile);
4194: }
4195: }
4196: return;
1.523 raeburn 4197: }
4198: }
1.1090 raeburn 4199: # Create the directory if not present
1.741 raeburn 4200: my @parts=split(/\//,$filepath);
4201: my $fullpath = $perlvar{'lonDaemons'};
4202: for (my $i=0;$i<@parts;$i++) {
4203: $fullpath .= '/'.$parts[$i];
4204: if ((-e $fullpath)!=1) {
4205: mkdir($fullpath,0777);
4206: }
4207: }
1.1172.2.96 raeburn 4208: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4209: print $fh $env{'form.'.$formname};
4210: close($fh);
1.1090 raeburn 4211: if ($context eq 'existingfile') {
4212: my @info = stat($fullpath.'/'.$fname);
4213: return ($fullpath.'/'.$fname,$info[9]);
4214: } else {
4215: return $fullpath.'/'.$fname;
4216: }
1.523 raeburn 4217: }
1.995 raeburn 4218: if ($subdir eq 'scantron') {
4219: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4220: } else {
1.995 raeburn 4221: $fname="$subdir/$fname";
4222: }
1.1090 raeburn 4223: if ($context eq 'coursedoc') {
1.638 albertel 4224: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4225: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4226: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4227: return &finishuserfileupload($docuname,$docudom,
4228: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4229: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4230: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4231: } else {
1.1172.2.21 raeburn 4232: if ($env{'form.folder'}) {
4233: $fname=$env{'form.folder'}.'/'.$fname;
4234: }
1.638 albertel 4235: return &process_coursefile('uploaddoc',$docuname,$docudom,
4236: $fname,$formname,$parser,
1.1095 raeburn 4237: $allfiles,$codebase,$mimetype);
1.481 raeburn 4238: }
1.719 banghart 4239: } elsif (defined($destuname)) {
4240: my $docuname=$destuname;
4241: my $docudom=$destudom;
1.860 raeburn 4242: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4243: $parser,$allfiles,$codebase,
1.1051 raeburn 4244: $thumbwidth,$thumbheight,
1.1095 raeburn 4245: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4246: } else {
1.638 albertel 4247: my $docuname=$env{'user.name'};
4248: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 4249: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4250: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4251: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4252: }
1.860 raeburn 4253: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4254: $parser,$allfiles,$codebase,
1.1051 raeburn 4255: $thumbwidth,$thumbheight,
1.1095 raeburn 4256: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4257: }
1.271 www 4258: }
4259:
4260: sub finishuserfileupload {
1.860 raeburn 4261: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4262: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4263: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4264: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4265:
1.860 raeburn 4266: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4267: $file=$fname;
4268: if ($fname=~m|/|) {
4269: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4270: $path.=$fnamepath.'/';
4271: }
1.259 www 4272: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4273: my $count;
4274: for ($count=4;$count<=$#parts;$count++) {
4275: $filepath.="/$parts[$count]";
4276: if ((-e $filepath)!=1) {
4277: mkdir($filepath,0777);
4278: }
4279: }
1.984 neumanie 4280:
1.258 www 4281: # Save the file
4282: {
1.1172.2.96 raeburn 4283: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4284: &logthis('Failed to create '.$filepath.'/'.$file);
4285: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4286: return '/adm/notfound.html';
4287: }
1.1090 raeburn 4288: if ($context eq 'overwrite') {
1.1117 foxr 4289: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4290: my $target = $filepath.'/'.$file;
4291: if (-e $source) {
4292: my @info = stat($source);
4293: if ($info[9] eq $env{'form.timestamp'}) {
4294: unless (&File::Copy::move($source,$target)) {
4295: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4296: return "Moving from $source failed";
4297: }
4298: } else {
4299: return "Temporary file: $source had unexpected date/time for last modification";
4300: }
4301: } else {
4302: return "Temporary file: $source missing";
4303: }
4304: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4305: &logthis('Failed to write to '.$filepath.'/'.$file);
4306: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4307: return '/adm/notfound.html';
4308: }
1.570 albertel 4309: close(FH);
1.1051 raeburn 4310: if ($resizewidth && $resizeheight) {
4311: my $mm = new File::MMagic;
4312: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4313: if ($mime_type =~ m{^image/}) {
4314: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4315: }
1.977 amueller 4316: }
1.258 www 4317: }
1.1152 raeburn 4318: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4319: if (ref($mimetype)) {
4320: if ($$mimetype eq '') {
4321: my $mm = new File::MMagic;
4322: my $type = $mm->checktype_filename($filepath.'/'.$file);
4323: $$mimetype = $type;
4324: }
4325: }
4326: }
1.1172.2.109 raeburn 4327: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4328: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4329: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4330: $allfiles,$codebase);
4331: unless ($parse_result eq 'ok') {
4332: &logthis('Failed to parse '.$filepath.$file.
4333: ' for embedded media: '.$parse_result);
4334: }
1.637 raeburn 4335: }
1.1172.2.109 raeburn 4336: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4337: my $format = $env{'form.scantron_format'};
4338: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4339: }
1.860 raeburn 4340: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4341: my $input = $filepath.'/'.$file;
4342: my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146. .13(raeb 4343:-23): my $makethumb;
1.860 raeburn 4344: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146. .13(raeb 4345:-23): if ($context eq 'toollogo') {
4346:-23): my ($fullwidth,$fullheight) = &check_dimensions($input);
4347:-23): if ($fullwidth ne '' && $fullheight ne '') {
4348:-23): if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
4349:-23): $makethumb = 1;
4350:-23): }
4351:-23): }
4352:-23): } else {
4353:-23): $makethumb = 1;
4354:-23): }
4355:-23): if ($makethumb) {
4356:-23): my @args = ('convert','-sample',$thumbsize,$input,$output);
4357:-23): system({$args[0]} @args);
4358:-23): if (-e $filepath.'/'.'tn-'.$file) {
4359:-23): $fetchthumb = 1;
4360:-23): }
1.860 raeburn 4361: }
4362: }
1.858 raeburn 4363:
1.259 www 4364: # Notify homeserver to grep it
4365: #
1.984 neumanie 4366: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4367: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4368: if ($fetchresult eq 'ok') {
1.860 raeburn 4369: if ($fetchthumb) {
4370: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4371: if ($thumbresult ne 'ok') {
4372: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4373: $docuhome.': '.$thumbresult);
4374: }
4375: }
1.259 www 4376: #
1.258 www 4377: # Return the URL to it
1.494 albertel 4378: return '/uploaded/'.$path.$file;
1.263 www 4379: } else {
1.494 albertel 4380: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4381: ': '.$fetchresult);
1.263 www 4382: return '/adm/notfound.html';
1.858 raeburn 4383: }
1.493 albertel 4384: }
4385:
1.637 raeburn 4386: sub extract_embedded_items {
1.961 raeburn 4387: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4388: my @state = ();
1.1164 raeburn 4389: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4390: my %javafiles = (
4391: codebase => '',
4392: code => '',
4393: archive => ''
4394: );
4395: my %mediafiles = (
4396: src => '',
4397: movie => '',
4398: );
1.648 raeburn 4399: my $p;
4400: if ($content) {
4401: $p = HTML::LCParser->new($content);
4402: } else {
1.961 raeburn 4403: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4404: }
1.641 albertel 4405: while (my $t=$p->get_token()) {
1.640 albertel 4406: if ($t->[0] eq 'S') {
4407: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4408: push(@state, $tagname);
1.648 raeburn 4409: if (lc($tagname) eq 'allow') {
4410: &add_filetype($allfiles,$attr->{'src'},'src');
4411: }
1.640 albertel 4412: if (lc($tagname) eq 'img') {
4413: &add_filetype($allfiles,$attr->{'src'},'src');
4414: }
1.886 albertel 4415: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4416: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4417: &add_filetype($allfiles,$attr->{'href'},'href');
4418: }
1.886 albertel 4419: }
1.645 raeburn 4420: if (lc($tagname) eq 'script') {
1.1164 raeburn 4421: my $src;
1.645 raeburn 4422: if ($attr->{'archive'} =~ /\.jar$/i) {
4423: &add_filetype($allfiles,$attr->{'archive'},'archive');
4424: } else {
1.1164 raeburn 4425: if ($attr->{'src'} ne '') {
4426: $src = $attr->{'src'};
4427: &add_filetype($allfiles,$src,'src');
4428: }
4429: }
4430: my $text = $p->get_trimmed_text();
4431: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4432: my @swfargs = split(/,/,$1);
4433: foreach my $item (@swfargs) {
4434: $item =~ s/["']//g;
4435: $item =~ s/^\s+//;
4436: $item =~ s/\s+$//;
4437: }
4438: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4439: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4440: push(@{$related{$swfargs[0]}},$swfargs[2]);
4441: } else {
4442: $related{$swfargs[0]} = [$swfargs[2]];
4443: }
4444: }
1.645 raeburn 4445: }
4446: }
4447: if (lc($tagname) eq 'link') {
4448: if (lc($attr->{'rel'}) eq 'stylesheet') {
4449: &add_filetype($allfiles,$attr->{'href'},'href');
4450: }
4451: }
1.640 albertel 4452: if (lc($tagname) eq 'object' ||
4453: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4454: foreach my $item (keys(%javafiles)) {
4455: $javafiles{$item} = '';
4456: }
1.1164 raeburn 4457: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4458: $lastids{lc($tagname)} = $attr->{'id'};
4459: }
1.640 albertel 4460: }
4461: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4462: my $name = lc($attr->{'name'});
4463: foreach my $item (keys(%javafiles)) {
4464: if ($name eq $item) {
4465: $javafiles{$item} = $attr->{'value'};
4466: last;
4467: }
4468: }
1.1164 raeburn 4469: my $pathfrom;
1.640 albertel 4470: foreach my $item (keys(%mediafiles)) {
4471: if ($name eq $item) {
1.1164 raeburn 4472: $pathfrom = $attr->{'value'};
4473: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4474: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4475: last;
4476: }
4477: }
1.1164 raeburn 4478: if ($name eq 'flashvars') {
4479: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4480: }
4481: if ($pathfrom ne '') {
4482: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4483: $pathfrom);
4484: }
1.640 albertel 4485: }
4486: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4487: foreach my $item (keys(%javafiles)) {
4488: if ($attr->{$item}) {
4489: $javafiles{$item} = $attr->{$item};
4490: last;
4491: }
4492: }
4493: foreach my $item (keys(%mediafiles)) {
4494: if ($attr->{$item}) {
4495: &add_filetype($allfiles,$attr->{$item},$item);
4496: last;
4497: }
4498: }
1.1164 raeburn 4499: if (lc($tagname) eq 'embed') {
4500: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4501: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4502: $attr->{'src'});
4503: }
4504: }
1.640 albertel 4505: }
1.1172.2.35 raeburn 4506: if (lc($tagname) eq 'iframe') {
4507: my $src = $attr->{'src'} ;
4508: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4509: &add_filetype($allfiles,$src,'src');
4510: } elsif ($src =~ m{^/}) {
4511: if ($env{'request.course.id'}) {
4512: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4513: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4514: my $url = &hreflocation('',$fullpath);
4515: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4516: my $relpath = $1;
4517: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4518: &add_filetype($allfiles,$1,'src');
4519: }
4520: }
4521: }
4522: }
4523: }
1.1164 raeburn 4524: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4525: pop(@state);
1.1164 raeburn 4526: }
1.640 albertel 4527: } elsif ($t->[0] eq 'E') {
4528: my ($tagname) = ($t->[1]);
4529: if ($javafiles{'codebase'} ne '') {
4530: $javafiles{'codebase'} .= '/';
4531: }
4532: if (lc($tagname) eq 'applet' ||
4533: lc($tagname) eq 'object' ||
4534: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4535: ) {
4536: foreach my $item (keys(%javafiles)) {
4537: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4538: my $file=$javafiles{'codebase'}.$javafiles{$item};
4539: &add_filetype($allfiles,$file,$item);
4540: }
4541: }
4542: }
4543: pop @state;
4544: }
4545: }
1.1164 raeburn 4546: foreach my $id (sort(keys(%flashvars))) {
4547: if ($shockwave{$id} ne '') {
4548: my @pairs = split(/\&/,$flashvars{$id});
4549: foreach my $pair (@pairs) {
4550: my ($key,$value) = split(/\=/,$pair);
4551: if ($key eq 'thumb') {
4552: &add_filetype($allfiles,$value,$key);
4553: } elsif ($key eq 'content') {
4554: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4555: my ($ext) = ($value =~ /\.([^.]+)$/);
4556: if ($ext ne '') {
4557: &add_filetype($allfiles,$path.$value,$ext);
4558: }
4559: }
4560: }
4561: }
4562: }
1.637 raeburn 4563: return 'ok';
4564: }
4565:
1.639 albertel 4566: sub add_filetype {
4567: my ($allfiles,$file,$type)=@_;
4568: if (exists($allfiles->{$file})) {
4569: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4570: push(@{$allfiles->{$file}}, &escape($type));
4571: }
4572: } else {
4573: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4574: }
4575: }
4576:
1.1164 raeburn 4577: sub embedded_dependency {
4578: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4579: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4580: if (($identifier ne '') &&
4581: (ref($related->{$identifier}) eq 'ARRAY') &&
4582: ($pathfrom ne '')) {
4583: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4584: foreach my $dep (@{$related->{$identifier}}) {
4585: &add_filetype($allfiles,$path.$dep,'object');
4586: }
4587: }
4588: }
4589: return;
4590: }
4591:
1.1172.2.146. .13(raeb 4592:-23): sub check_dimensions {
4593:-23): my ($inputfile) = @_;
4594:-23): my ($fullwidth,$fullheight);
4595:-23): if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
4596:-23): my $mm = new File::MMagic;
4597:-23): my $mime_type = $mm->checktype_filename($inputfile);
4598:-23): if ($mime_type =~ m{^image/}) {
4599:-23): if (open(PIPE,"identify $inputfile 2>&1 |")) {
4600:-23): my $imageinfo = <PIPE>;
4601:-23): if (!close(PIPE)) {
4602:-23): &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
4603:-23): }
4604:-23): chomp($imageinfo);
4605:-23): my ($fullsize) =
4606:-23): ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
4607:-23): if ($fullsize) {
4608:-23): ($fullwidth,$fullheight) = split(/x/,$fullsize);
4609:-23): }
4610:-23): }
4611:-23): }
4612:-23): }
4613:-23): return ($fullwidth,$fullheight);
4614:-23): }
4615:-23):
1.1172.2.109 raeburn 4616: sub bubblesheet_converter {
4617: my ($cdom,$fullpath,$config,$format) = @_;
4618: if ((&domain($cdom) ne '') &&
4619: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4620: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4621: my (%csvcols,%csvoptions);
4622: if (ref($config->{'fields'}) eq 'HASH') {
4623: %csvcols = %{$config->{'fields'}};
4624: }
4625: if (ref($config->{'options'}) eq 'HASH') {
4626: %csvoptions = %{$config->{'options'}};
4627: }
4628: my %csvbynum = reverse(%csvcols);
4629: my %scantronconf = &get_scantron_config($format,$cdom);
4630: if (keys(%scantronconf)) {
4631: my %bynum = (
4632: $scantronconf{CODEstart} => 'CODEstart',
4633: $scantronconf{IDstart} => 'IDstart',
4634: $scantronconf{PaperID} => 'PaperID',
4635: $scantronconf{FirstName} => 'FirstName',
4636: $scantronconf{LastName} => 'LastName',
4637: $scantronconf{Qstart} => 'Qstart',
4638: );
4639: my @ordered;
4640: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4641: push(@ordered,$bynum{$item});
4642: }
4643: my %mapstart = (
4644: CODEstart => 'CODE',
4645: IDstart => 'ID',
4646: PaperID => 'PaperID',
4647: FirstName => 'FirstName',
4648: LastName => 'LastName',
4649: Qstart => 'FirstQuestion',
4650: );
4651: my %maplength = (
4652: CODEstart => 'CODElength',
4653: IDstart => 'IDlength',
4654: PaperID => 'PaperIDlength',
4655: FirstName => 'FirstNamelength',
4656: LastName => 'LastNamelength',
4657: );
4658: if (open(my $fh,'<',$fullpath)) {
4659: my $output;
4660: my %lettdig = &letter_to_digits();
4661: my %diglett = reverse(%lettdig);
4662: my $numletts = scalar(keys(%lettdig));
4663: my $num = 0;
4664: while (my $line=<$fh>) {
4665: $num ++;
4666: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4667: $line =~ s{[\r\n]+$}{};
4668: my %found;
1.1172.2.143 raeburn 4669: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4670: my ($qstart,$record);
4671: for (my $i=0; $i<@values; $i++) {
4672: if ((($qstart ne '') && ($i > $qstart)) ||
4673: ($csvbynum{$i} eq 'FirstQuestion')) {
4674: if ($values[$i] eq '') {
4675: $values[$i] = $scantronconf{'Qoff'};
4676: } elsif ($scantronconf{'Qon'} eq 'number') {
4677: if ($values[$i] =~ /^[A-Ja-j]$/) {
4678: $values[$i] = $lettdig{uc($values[$i])};
4679: }
4680: } elsif ($scantronconf{'Qon'} eq 'letter') {
4681: if ($values[$i] =~ /^[0-9]$/) {
4682: $values[$i] = $diglett{$values[$i]};
4683: }
4684: } else {
4685: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4686: my $digit;
4687: if ($values[$i] =~ /^[A-Ja-j]$/) {
4688: $digit = $lettdig{uc($values[$i])}-1;
4689: if ($values[$i] eq 'J') {
4690: $digit += $numletts;
4691: }
4692: } elsif ($values[$i] =~ /^[0-9]$/) {
4693: $digit = $values[$i]-1;
4694: if ($values[$i] eq '0') {
4695: $digit += $numletts;
4696: }
4697: }
4698: my $qval='';
4699: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4700: if ($j == $digit) {
4701: $qval .= $scantronconf{'Qon'};
4702: } else {
4703: $qval .= $scantronconf{'Qoff'};
4704: }
4705: }
4706: $values[$i] = $qval;
4707: }
4708: }
4709: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4710: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4711: }
4712: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4713: if ($numblank > 0) {
4714: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4715: }
4716: if ($csvbynum{$i} eq 'FirstQuestion') {
4717: $qstart = $i;
4718: $found{$csvbynum{$i}} = $values[$i];
4719: } else {
4720: $found{'FirstQuestion'} .= $values[$i];
4721: }
4722: } elsif (exists($csvbynum{$i})) {
4723: if ($csvoptions{'rem'}) {
4724: $values[$i] =~ s/^\s+//;
4725: }
4726: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4727: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4728: $values[$i] = '0'.$values[$i];
4729: }
4730: }
4731: $found{$csvbynum{$i}} = $values[$i];
4732: }
4733: }
4734: foreach my $item (@ordered) {
4735: my $currlength = 1+length($record);
4736: my $numspaces = $scantronconf{$item} - $currlength;
4737: if ($numspaces > 0) {
4738: $record .= (' ' x $numspaces);
4739: }
4740: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4741: unless ($item eq 'Qstart') {
4742: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4743: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4744: }
4745: }
4746: $record .= $found{$mapstart{$item}};
4747: }
4748: }
4749: $output .= "$record\n";
4750: }
4751: close($fh);
4752: if ($output) {
4753: if (open(my $fh,'>',$fullpath)) {
4754: print $fh $output;
4755: close($fh);
4756: }
4757: }
4758: }
4759: }
4760: return;
4761: }
4762: }
4763:
4764: sub letter_to_digits {
4765: my %lettdig = (
4766: A => 1,
4767: B => 2,
4768: C => 3,
4769: D => 4,
4770: E => 5,
4771: F => 6,
4772: G => 7,
4773: H => 8,
4774: I => 9,
4775: J => 0,
4776: );
4777: return %lettdig;
4778: }
4779:
4780: sub get_scantron_config {
4781: my ($which,$cdom) = @_;
4782: my @lines = &get_scantronformat_file($cdom);
4783: my %config;
4784: #FIXME probably should move to XML it has already gotten a bit much now
4785: foreach my $line (@lines) {
4786: my ($name,$descrip)=split(/:/,$line);
4787: if ($name ne $which ) { next; }
4788: chomp($line);
4789: my @config=split(/:/,$line);
4790: $config{'name'}=$config[0];
4791: $config{'description'}=$config[1];
4792: $config{'CODElocation'}=$config[2];
4793: $config{'CODEstart'}=$config[3];
4794: $config{'CODElength'}=$config[4];
4795: $config{'IDstart'}=$config[5];
4796: $config{'IDlength'}=$config[6];
4797: $config{'Qstart'}=$config[7];
4798: $config{'Qlength'}=$config[8];
4799: $config{'Qoff'}=$config[9];
4800: $config{'Qon'}=$config[10];
4801: $config{'PaperID'}=$config[11];
4802: $config{'PaperIDlength'}=$config[12];
4803: $config{'FirstName'}=$config[13];
4804: $config{'FirstNamelength'}=$config[14];
4805: $config{'LastName'}=$config[15];
4806: $config{'LastNamelength'}=$config[16];
4807: $config{'BubblesPerRow'}=$config[17];
4808: last;
4809: }
4810: return %config;
4811: }
4812:
4813: sub get_scantronformat_file {
4814: my ($cdom) = @_;
4815: if ($cdom eq '') {
4816: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4817: }
4818: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4819: my $gottab = 0;
4820: my @lines;
4821: if (ref($domconfig{'scantron'}) eq 'HASH') {
4822: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4823: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4824: if ($formatfile ne '-1') {
4825: @lines = split("\n",$formatfile,-1);
4826: $gottab = 1;
4827: }
4828: }
4829: }
4830: if (!$gottab) {
4831: my $confname = $cdom.'-domainconfig';
4832: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4833: my $formatfile = &getfile($default);
4834: if ($formatfile ne '-1') {
4835: @lines = split("\n",$formatfile,-1);
4836: $gottab = 1;
4837: }
4838: }
4839: if (!$gottab) {
4840: my @domains = ¤t_machine_domains();
4841: if (grep(/^\Q$cdom\E$/,@domains)) {
4842: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4843: @lines = <$fh>;
4844: close($fh);
4845: }
4846: } else {
4847: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4848: @lines = <$fh>;
4849: close($fh);
4850: }
4851: }
1.1172.2.146. .8(raebu 4852:23): chomp(@lines);
1.1172.2.109 raeburn 4853: }
4854: return @lines;
4855: }
4856:
1.493 albertel 4857: sub removeuploadedurl {
1.984 neumanie 4858: my ($url)=@_;
4859: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4860: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4861: }
4862:
4863: sub removeuserfile {
4864: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4865: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4866: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4867: if ($result eq 'ok') {
1.798 raeburn 4868: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4869: my $metafile = $fname.'.meta';
4870: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4871: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4872: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4873: my $sqlresult =
1.823 albertel 4874: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4875: 'portfolio_metadata',$group,
4876: 'delete');
1.798 raeburn 4877: }
4878: }
4879: return $result;
1.257 www 4880: }
1.15 www 4881:
1.530 albertel 4882: sub mkdiruserfile {
4883: my ($docuname,$docudom,$dir)=@_;
4884: my $home=&homeserver($docuname,$docudom);
4885: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4886: }
4887:
1.531 albertel 4888: sub renameuserfile {
4889: my ($docuname,$docudom,$old,$new)=@_;
4890: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4891: my $result = &reply("renameuserfile:$docudom:$docuname:".
4892: &escape("$old").':'.&escape("$new"),$home);
4893: if ($result eq 'ok') {
4894: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4895: my $oldmeta = $old.'.meta';
4896: my $newmeta = $new.'.meta';
4897: my $metaresult =
4898: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4899: my $url = "/uploaded/$docudom/$docuname/$old";
4900: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4901: my $sqlresult =
1.823 albertel 4902: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4903: 'portfolio_metadata',$group,
4904: 'delete');
1.798 raeburn 4905: }
4906: }
4907: return $result;
1.531 albertel 4908: }
4909:
1.14 www 4910: # ------------------------------------------------------------------------- Log
4911:
4912: sub log {
4913: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4914: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4915: }
4916:
4917: # ------------------------------------------------------------------ Course Log
1.352 www 4918: #
4919: # This routine flushes several buffers of non-mission-critical nature
4920: #
1.157 www 4921:
4922: sub flushcourselogs {
1.352 www 4923: &logthis('Flushing log buffers');
4924: #
4925: # course logs
4926: # This is a log of all transactions in a course, which can be used
4927: # for data mining purposes
4928: #
4929: # It also collects the courseid database, which lists last transaction
4930: # times and course titles for all courseids
4931: #
4932: my %courseidbuffer=();
1.921 raeburn 4933: foreach my $crsid (keys(%courselogs)) {
1.352 www 4934: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4935: &escape($courselogs{$crsid}),
4936: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4937: delete $courselogs{$crsid};
4938: } else {
4939: &logthis('Failed to flush log buffer for '.$crsid);
4940: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4941: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4942: " exceeded maximum size, deleting.</font>");
4943: delete $courselogs{$crsid};
4944: }
1.352 www 4945: }
1.920 raeburn 4946: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4947: 'description' => $coursedescrbuf{$crsid},
4948: 'inst_code' => $courseinstcodebuf{$crsid},
4949: 'type' => $coursetypebuf{$crsid},
4950: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4951: };
1.191 harris41 4952: }
1.352 www 4953: #
4954: # Write course id database (reverse lookup) to homeserver of courses
4955: # Is used in pickcourse
4956: #
1.840 albertel 4957: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4958: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4959: $courseidbuffer{$crs_home},
4960: $crs_home,'timeonly');
1.352 www 4961: }
4962: #
4963: # File accesses
4964: # Writes to the dynamic metadata of resources to get hit counts, etc.
4965: #
1.449 matthew 4966: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4967: if ($entry =~ /___count$/) {
4968: my ($dom,$name);
1.807 albertel 4969: ($dom,$name,undef)=
1.811 albertel 4970: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4971: if (! defined($dom) || $dom eq '' ||
4972: ! defined($name) || $name eq '') {
1.620 albertel 4973: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4974: #
4975: # FIXME 11/29/2021
4976: # Typo in rev. 1.458 (2003/12/09)??
4977: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4978: #
1.1172.2.146. .13(raeb 4979:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142 raeburn 4980: # $dom and $name will always be null, so the &inc() call will default to storing this data
4981: # in a nohist_accesscount.db file for the user rather than the course.
4982: #
4983: # That said there is a lot of noise in the data being stored.
4984: # So counts for prtspool/ and adm/ etc. are recorded.
4985: #
4986: # A review of which items ending '___count' are written to %accesshash should likely be
4987: # made before deciding whether to set these to 'course.' instead of 'request.'
4988: #
4989: # Under the current scheme each user receives a nohist_accesscount.db file listing
4990: # accesses for things which are not published resources, regardless of course, and
4991: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4992: # anyone in the course for things which are not published resources.
4993: #
4994: # For an author, nohist_accesscount.db ends up having records for other items
4995: # mixed up with the legitimate access counts for the author's published resources.
4996: #
1.620 albertel 4997: $dom = $env{'request.'.$cid.'.domain'};
4998: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4999: }
1.450 matthew 5000: my $value = $accesshash{$entry};
5001: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5002: my %temphash=($url => $value);
1.449 matthew 5003: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5004: if ($result eq 'ok') {
5005: delete $accesshash{$entry};
5006: }
5007: } else {
1.811 albertel 5008: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5009: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5010: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5011: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5012: delete $accesshash{$entry};
5013: }
1.185 www 5014: }
1.191 harris41 5015: }
1.352 www 5016: #
5017: # Roles
5018: # Reverse lookup of user roles for course faculty/staff and co-authorship
5019: #
1.800 albertel 5020: foreach my $entry (keys(%userrolehash)) {
1.351 www 5021: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5022: split(/\:/,$entry);
5023: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 5024: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5025: $rudom,$runame) eq 'ok') {
5026: delete $userrolehash{$entry};
5027: }
5028: }
1.662 raeburn 5029: #
1.1172.2.90 raeburn 5030: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5031: #
5032: my %domrolebuffer = ();
1.1000 raeburn 5033: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5034: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5035: if ($domrolebuffer{$rudom}) {
5036: $domrolebuffer{$rudom}.='&'.&escape($entry).
5037: '='.&escape($domainrolehash{$entry});
5038: } else {
5039: $domrolebuffer{$rudom}.=&escape($entry).
5040: '='.&escape($domainrolehash{$entry});
5041: }
5042: delete $domainrolehash{$entry};
5043: }
5044: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 5045: my %servers;
5046: if (defined(&domain($dom,'primary'))) {
5047: my $primary=&domain($dom,'primary');
5048: my $hostname=&hostname($primary);
5049: $servers{$primary} = $hostname;
5050: } else {
5051: %servers = &get_servers($dom,'library');
5052: }
1.841 albertel 5053: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 5054: if (&reply('domroleput:'.$dom.':'.
5055: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5056: last;
5057: } else {
1.841 albertel 5058: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5059: }
1.662 raeburn 5060: }
5061: }
1.186 www 5062: $dumpcount++;
1.157 www 5063: }
5064:
5065: sub courselog {
5066: my $what=shift;
1.158 www 5067: $what=time.':'.$what;
1.620 albertel 5068: unless ($env{'request.course.id'}) { return ''; }
5069: $coursedombuf{$env{'request.course.id'}}=
5070: $env{'course.'.$env{'request.course.id'}.'.domain'};
5071: $coursenumbuf{$env{'request.course.id'}}=
5072: $env{'course.'.$env{'request.course.id'}.'.num'};
5073: $coursehombuf{$env{'request.course.id'}}=
5074: $env{'course.'.$env{'request.course.id'}.'.home'};
5075: $coursedescrbuf{$env{'request.course.id'}}=
5076: $env{'course.'.$env{'request.course.id'}.'.description'};
5077: $courseinstcodebuf{$env{'request.course.id'}}=
5078: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5079: $courseownerbuf{$env{'request.course.id'}}=
5080: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5081: $coursetypebuf{$env{'request.course.id'}}=
5082: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5083: if (defined $courselogs{$env{'request.course.id'}}) {
5084: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5085: } else {
1.620 albertel 5086: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5087: }
1.620 albertel 5088: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5089: &flushcourselogs();
5090: }
1.158 www 5091: }
5092:
5093: sub courseacclog {
5094: my $fnsymb=shift;
1.620 albertel 5095: unless ($env{'request.course.id'}) { return ''; }
5096: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5097: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5098: $what.=':POST';
1.583 matthew 5099: # FIXME: Probably ought to escape things....
1.800 albertel 5100: foreach my $key (keys(%env)) {
5101: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5102: my $formitem = $1;
5103: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5104: $what.=':'.$formitem.'='.$env{$key};
5105: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 5106: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 5107: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 5108: } else {
5109: $what.=':'.$formitem.'='.$env{$key};
5110: }
1.975 raeburn 5111: }
1.158 www 5112: }
1.191 harris41 5113: }
1.583 matthew 5114: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5115: # FIXME: We should not be depending on a form parameter that someone
5116: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5117: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5118: $what.= ':POST';
5119: # FIXME: Probably ought to escape things....
5120: foreach my $element ('courseexp','crsfulltext','crsrelated',
5121: 'crsdiscuss') {
1.620 albertel 5122: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5123: }
5124: }
1.158 www 5125: }
5126: &courselog($what);
1.149 www 5127: }
5128:
1.185 www 5129: sub countacc {
5130: my $url=&declutter(shift);
1.458 matthew 5131: return if (! defined($url) || $url eq '');
1.620 albertel 5132: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5133: #
5134: # Mark that this url was used in this course
5135: #
1.620 albertel 5136: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5137: #
5138: # Increase the access count for this resource in this child process
5139: #
1.281 www 5140: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5141: $accesshash{$key}++;
1.185 www 5142: }
1.349 www 5143:
1.361 www 5144: sub linklog {
5145: my ($from,$to)=@_;
5146: $from=&declutter($from);
5147: $to=&declutter($to);
5148: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5149: $accesshash{$to.'___'.$from.'___goto'}=1;
5150: }
1.1160 www 5151:
5152: sub statslog {
5153: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5154: if ($users<2) { return; }
5155: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5156: 'course' => $env{'request.course.id'},
5157: 'sections' => '"all"',
5158: 'num_students' => $users,
5159: 'part' => $part,
5160: 'symb' => $symb,
5161: 'mean_tries' => $av_attempts,
5162: 'deg_of_diff' => $degdiff});
5163: foreach my $key (keys(%dynstore)) {
5164: $accesshash{$key}=$dynstore{$key};
5165: }
5166: }
1.361 www 5167:
1.349 www 5168: sub userrolelog {
5169: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5170: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5171: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5172: $userrolehash
5173: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5174: =$tend.':'.$tstart;
1.662 raeburn 5175: }
1.1169 droeschl 5176: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5177: $userrolehash
5178: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5179: =$tend.':'.$tstart;
5180: }
1.1172.2.90 raeburn 5181: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5182: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5183: $domainrolehash
5184: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5185: = $tend.':'.$tstart;
5186: }
1.351 www 5187: }
5188:
1.957 raeburn 5189: sub courserolelog {
5190: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 5191: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5192: my $cdom = $1;
5193: my $cnum = $2;
5194: my $sec = $3;
5195: my $namespace = 'rolelog';
5196: my %storehash = (
5197: role => $trole,
5198: start => $tstart,
5199: end => $tend,
5200: selfenroll => $selfenroll,
5201: context => $context,
5202: );
5203: if ($trole eq 'gr') {
5204: $namespace = 'groupslog';
5205: $storehash{'group'} = $sec;
5206: } else {
5207: $storehash{'section'} = $sec;
1.1172.2.146. .16(raeb 5208:-23): my ($curruserdomstr,$newuserdomstr);
5209:-23): if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
5210:-23): $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
5211:-23): } else {
5212:-23): my %courseinfo = &coursedescription($cdom.'/'.$cnum);
5213:-23): $curruserdomstr = $courseinfo{'internal.userdomains'};
5214:-23): }
5215:-23): if ($curruserdomstr ne '') {
5216:-23): my @udoms = split(/,/,$curruserdomstr);
5217:-23): unless (grep(/^\Q$domain\E/,@udoms)) {
5218:-23): push(@udoms,$domain);
5219:-23): $newuserdomstr = join(',',sort(@udoms));
5220:-23): }
5221:-23): } else {
5222:-23): $newuserdomstr = $domain;
5223:-23): }
5224:-23): if ($newuserdomstr ne '') {
5225:-23): my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
5226:-23): $cdom,$cnum);
5227:-23): if ($putresult eq 'ok') {
5228:-23): unless (($selfenroll) || ($context eq 'selfenroll')) {
5229:-23): if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
5230:-23): ($context eq 'automated') || ($context eq 'domain')) {
5231:-23): $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
5232:-23): } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
5233:-23): &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
5234:-23): }
5235:-23): }
5236:-23): }
5237:-23): }
1.1172.2.9 raeburn 5238: }
5239: &write_log('course',$namespace,\%storehash,$delflag,$username,
5240: $domain,$cnum,$cdom);
5241: if (($trole ne 'st') || ($sec ne '')) {
5242: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5243: }
5244: }
5245: return;
5246: }
5247:
1.1172.2.9 raeburn 5248: sub domainrolelog {
5249: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5250: if ($area =~ m{^/($match_domain)/$}) {
5251: my $cdom = $1;
5252: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5253: my $namespace = 'rolelog';
5254: my %storehash = (
5255: role => $trole,
5256: start => $tstart,
5257: end => $tend,
5258: context => $context,
5259: );
5260: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5261: $domain,$domconfiguser,$cdom);
5262: }
5263: return;
5264:
5265: }
5266:
5267: sub coauthorrolelog {
5268: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5269: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5270: my $audom = $1;
5271: my $auname = $2;
5272: my $namespace = 'rolelog';
5273: my %storehash = (
5274: role => $trole,
5275: start => $tstart,
5276: end => $tend,
5277: context => $context,
5278: );
5279: &write_log('author',$namespace,\%storehash,$delflag,$username,
5280: $domain,$auname,$audom);
5281: }
5282: return;
5283: }
5284:
1.351 www 5285: sub get_course_adv_roles {
1.948 raeburn 5286: my ($cid,$codes) = @_;
1.620 albertel 5287: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5288: my %coursehash=&coursedescription($cid);
1.988 raeburn 5289: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5290: my %nothide=();
1.800 albertel 5291: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5292: if ($user !~ /:/) {
5293: $nothide{join(':',split(/[\@]/,$user))}=1;
5294: } else {
5295: $nothide{$user}=1;
5296: }
1.470 www 5297: }
1.1172.2.23 raeburn 5298: my @possdoms = ($coursehash{'domain'});
5299: if ($coursehash{'checkforpriv'}) {
5300: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5301: }
1.351 www 5302: my %returnhash=();
5303: my %dumphash=
5304: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5305: my $now=time;
1.997 raeburn 5306: my %privileged;
1.1000 raeburn 5307: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5308: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5309: if (($tstart) && ($tstart<0)) { next; }
5310: if (($tend) && ($tend<$now)) { next; }
5311: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5312: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5313: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 5314: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5315: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5316: if ($role eq 'cr') { next; }
1.948 raeburn 5317: if ($codes) {
5318: if ($section) { $role .= ':'.$section; }
5319: if ($returnhash{$role}) {
5320: $returnhash{$role}.=','.$username.':'.$domain;
5321: } else {
5322: $returnhash{$role}=$username.':'.$domain;
5323: }
1.351 www 5324: } else {
1.988 raeburn 5325: my $key=&plaintext($role,$crstype);
1.973 bisitz 5326: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5327: if ($returnhash{$key}) {
5328: $returnhash{$key}.=','.$username.':'.$domain;
5329: } else {
5330: $returnhash{$key}=$username.':'.$domain;
5331: }
1.351 www 5332: }
1.948 raeburn 5333: }
1.400 www 5334: return %returnhash;
5335: }
5336:
5337: sub get_my_roles {
1.937 raeburn 5338: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5339: unless (defined($uname)) { $uname=$env{'user.name'}; }
5340: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5341: my (%dumphash,%nothide);
1.1086 raeburn 5342: if ($context eq 'userroles') {
1.1166 raeburn 5343: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5344: } else {
1.1172.2.23 raeburn 5345: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5346: if ($hidepriv) {
5347: my %coursehash=&coursedescription($udom.'_'.$uname);
5348: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5349: if ($user !~ /:/) {
5350: $nothide{join(':',split(/[\@]/,$user))} = 1;
5351: } else {
5352: $nothide{$user} = 1;
5353: }
5354: }
5355: }
1.858 raeburn 5356: }
1.400 www 5357: my %returnhash=();
5358: my $now=time;
1.999 raeburn 5359: my %privileged;
1.800 albertel 5360: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5361: my ($role,$tend,$tstart);
5362: if ($context eq 'userroles') {
1.1149 raeburn 5363: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5364: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5365: } else {
5366: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5367: }
1.400 www 5368: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5369: my $status = 'active';
1.939 raeburn 5370: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5371: $status = 'previous';
5372: }
5373: if (($tstart) && ($now<$tstart)) {
5374: $status = 'future';
5375: }
5376: if (ref($types) eq 'ARRAY') {
5377: if (!grep(/^\Q$status\E$/,@{$types})) {
5378: next;
5379: }
5380: } else {
5381: if ($status ne 'active') {
5382: next;
5383: }
5384: }
1.867 raeburn 5385: my ($rolecode,$username,$domain,$section,$area);
5386: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5387: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5388: (undef,$domain,$username,$section) = split(/\//,$area);
5389: } else {
5390: ($role,$username,$domain,$section) = split(/\:/,$entry);
5391: }
1.832 raeburn 5392: if (ref($roledoms) eq 'ARRAY') {
5393: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5394: next;
5395: }
5396: }
5397: if (ref($roles) eq 'ARRAY') {
5398: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5399: if ($role =~ /^cr\//) {
5400: if (!grep(/^cr$/,@{$roles})) {
5401: next;
5402: }
1.1104 raeburn 5403: } elsif ($role =~ /^gr\//) {
5404: if (!grep(/^gr$/,@{$roles})) {
5405: next;
5406: }
1.922 raeburn 5407: } else {
5408: next;
5409: }
1.832 raeburn 5410: }
1.867 raeburn 5411: }
1.937 raeburn 5412: if ($hidepriv) {
1.1172.2.23 raeburn 5413: my @privroles = ('dc','su');
1.999 raeburn 5414: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5415: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5416: } else {
1.1172.2.23 raeburn 5417: my $possdoms = [$domain];
5418: if (ref($roledoms) eq 'ARRAY') {
5419: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5420: }
1.1172.2.23 raeburn 5421: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5422: if (!$nothide{$username.':'.$domain}) {
5423: next;
5424: }
5425: }
1.937 raeburn 5426: }
5427: }
1.933 raeburn 5428: if ($withsec) {
5429: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5430: $tstart.':'.$tend;
5431: } else {
5432: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5433: }
1.832 raeburn 5434: }
1.373 www 5435: return %returnhash;
1.399 www 5436: }
5437:
1.1172.2.89 raeburn 5438: sub get_all_adhocroles {
5439: my ($dom) = @_;
5440: my @roles_by_num = ();
5441: my %domdefaults = &get_domain_defaults($dom);
5442: my (%description,%access_in_dom,%access_info);
5443: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5444: my $count = 0;
5445: my %domcurrent = %{$domdefaults{'adhocroles'}};
5446: my %ordered;
5447: foreach my $role (sort(keys(%domcurrent))) {
5448: my ($order,$desc,$access_in_dom);
5449: if (ref($domcurrent{$role}) eq 'HASH') {
5450: $order = $domcurrent{$role}{'order'};
5451: $desc = $domcurrent{$role}{'desc'};
5452: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5453: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5454: }
5455: if ($order eq '') {
5456: $order = $count;
5457: }
5458: $ordered{$order} = $role;
5459: if ($desc ne '') {
5460: $description{$role} = $desc;
5461: } else {
5462: $description{$role}= $role;
5463: }
5464: $count++;
5465: }
5466: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5467: push(@roles_by_num,$ordered{$item});
5468: }
5469: }
5470: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5471: }
5472:
5473: sub get_my_adhocroles {
5474: my ($cid,$checkreg) = @_;
5475: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5476: if ($env{'request.course.id'} eq $cid) {
5477: $cdom = $env{'course.'.$cid.'.domain'};
5478: $cnum = $env{'course.'.$cid.'.num'};
5479: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5480: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5481: $cdom = $1;
5482: $cnum = $2;
5483: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5484: $cdom,$cnum);
5485: }
5486: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5487: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5488: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5489: if ($rosterhash{$user} ne '') {
5490: my $type = (split(/:/,$rosterhash{$user}))[5];
5491: return ([],{}) if ($type eq 'auto');
5492: }
5493: }
5494: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5495: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5496: my $then=$env{'user.login.time'};
5497: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5498: if (!$update) {
5499: $update = $then;
5500: }
5501: my @liveroles;
5502: foreach my $role ('dh','da') {
5503: if ($env{"user.role.$role./$cdom/"}) {
5504: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5505: my $limit = $update;
5506: if ($env{'request.role'} eq "$role./$cdom/") {
5507: $limit = $then;
5508: }
5509: my $activerole = 1;
5510: if ($tstart && $tstart>$limit) { $activerole = 0; }
5511: if ($tend && $tend <$limit) { $activerole = 0; }
5512: if ($activerole) {
5513: push(@liveroles,$role);
5514: }
5515: }
5516: }
5517: if (@liveroles) {
1.1172.2.89 raeburn 5518: if (&homeserver($cnum,$cdom) ne 'no_host') {
5519: my ($accessref,$accessinfo,%access_in_dom);
5520: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5521: if (ref($roles_by_num) eq 'ARRAY') {
5522: if (@{$roles_by_num}) {
5523: my %settings;
5524: if ($env{'request.course.id'} eq $cid) {
5525: foreach my $envkey (keys(%env)) {
5526: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5527: $settings{$1} = $env{$envkey};
5528: }
5529: }
5530: } else {
5531: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5532: }
5533: my %setincrs;
5534: if ($settings{'internal.adhocaccess'}) {
5535: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5536: }
5537: my @statuses;
5538: if ($env{'environment.inststatus'}) {
5539: @statuses = split(/,/,$env{'environment.inststatus'});
5540: }
5541: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5542: if (ref($accessref) eq 'HASH') {
5543: %access_in_dom = %{$accessref};
5544: }
5545: foreach my $role (@{$roles_by_num}) {
5546: my ($curraccess,@okstatus,@personnel);
5547: if ($setincrs{$role}) {
5548: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5549: if ($curraccess eq 'status') {
5550: @okstatus = split(/\&/,$rest);
5551: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5552: @personnel = split(/\&/,$rest);
5553: }
5554: } else {
5555: $curraccess = $access_in_dom{$role};
5556: if (ref($accessinfo) eq 'HASH') {
5557: if ($curraccess eq 'status') {
5558: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5559: @okstatus = @{$accessinfo->{$role}};
5560: }
5561: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5562: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5563: @personnel = @{$accessinfo->{$role}};
5564: }
5565: }
5566: }
5567: }
5568: if ($curraccess eq 'none') {
5569: next;
5570: } elsif ($curraccess eq 'all') {
5571: push(@possroles,$role);
1.1172.2.90 raeburn 5572: } elsif ($curraccess eq 'dh') {
5573: if (grep(/^dh$/,@liveroles)) {
5574: push(@possroles,$role);
5575: } else {
5576: next;
5577: }
5578: } elsif ($curraccess eq 'da') {
5579: if (grep(/^da$/,@liveroles)) {
5580: push(@possroles,$role);
5581: } else {
5582: next;
5583: }
1.1172.2.89 raeburn 5584: } elsif ($curraccess eq 'status') {
5585: if (@okstatus) {
5586: if (!@statuses) {
5587: if (grep(/^default$/,@okstatus)) {
5588: push(@possroles,$role);
5589: }
5590: } else {
5591: foreach my $status (@okstatus) {
5592: if (grep(/^\Q$status\E$/,@statuses)) {
5593: push(@possroles,$role);
5594: last;
5595: }
5596: }
5597: }
5598: }
5599: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5600: if (grep(/^\Q$user\E$/,@personnel)) {
5601: if ($curraccess eq 'exc') {
5602: push(@possroles,$role);
5603: }
5604: } elsif ($curraccess eq 'inc') {
5605: push(@possroles,$role);
5606: }
5607: }
5608: }
5609: }
5610: }
5611: }
5612: }
5613: }
5614: }
5615: unless (ref($description) eq 'HASH') {
5616: if (ref($roles_by_num) eq 'ARRAY') {
5617: my %desc;
5618: map { $desc{$_} = $_; } (@{$roles_by_num});
5619: $description = \%desc;
5620: } else {
5621: $description = {};
5622: }
5623: }
5624: return (\@possroles,$description);
5625: }
5626:
1.399 www 5627: # ----------------------------------------------------- Frontpage Announcements
5628: #
5629: #
5630:
5631: sub postannounce {
5632: my ($server,$text)=@_;
1.844 albertel 5633: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5634: unless ($text=~/\w/) { $text=''; }
5635: return &reply('setannounce:'.&escape($text),$server);
5636: }
5637:
5638: sub getannounce {
1.448 albertel 5639:
1.1172.2.96 raeburn 5640: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5641: my $announcement='';
1.800 albertel 5642: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5643: close($fh);
1.399 www 5644: if ($announcement=~/\w/) {
5645: return
5646: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5647: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5648: } else {
5649: return '';
5650: }
5651: } else {
5652: return '';
5653: }
1.351 www 5654: }
1.353 www 5655:
5656: # ---------------------------------------------------------- Course ID routines
5657: # Deal with domain's nohist_courseid.db files
5658: #
5659:
5660: sub courseidput {
1.921 raeburn 5661: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5662: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5663: my $outcome;
5664: if ($caller eq 'timeonly') {
5665: my $cids = '';
5666: foreach my $item (keys(%$storehash)) {
5667: $cids.=&escape($item).'&';
5668: }
5669: $cids=~s/\&$//;
5670: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5671: $coursehome);
5672: } else {
5673: my $items = '';
5674: foreach my $item (keys(%$storehash)) {
5675: $items.= &escape($item).'='.
5676: &freeze_escape($$storehash{$item}).'&';
5677: }
5678: $items=~s/\&$//;
5679: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5680: $coursehome);
1.918 raeburn 5681: }
5682: if ($outcome eq 'unknown_cmd') {
5683: my $what;
5684: foreach my $cid (keys(%$storehash)) {
5685: $what .= &escape($cid).'=';
1.921 raeburn 5686: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5687: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5688: }
5689: $what =~ s/\:$/&/;
5690: }
5691: $what =~ s/\&$//;
5692: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5693: } else {
5694: return $outcome;
5695: }
1.353 www 5696: }
5697:
5698: sub courseiddump {
1.921 raeburn 5699: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5700: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5701: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5702: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5703: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5704: my $as_hash = 1;
5705: my %returnhash;
5706: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5707: my %libserv = &all_library();
5708: foreach my $tryserver (keys(%libserv)) {
5709: if ( ( $hostidflag == 1
5710: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5711: || (!defined($hostidflag)) ) {
5712:
1.918 raeburn 5713: if (($domfilter eq '') ||
5714: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5715: my $rep;
5716: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5717: $rep = &LONCAPA::Lond::dump_course_id_handler(
5718: join(":", (&host_domain($tryserver), $sincefilter,
5719: &escape($descfilter), &escape($instcodefilter),
5720: &escape($ownerfilter), &escape($coursefilter),
5721: &escape($typefilter), &escape($regexp_ok),
5722: $as_hash, &escape($selfenrollonly),
5723: &escape($catfilter), $showhidden, $caller,
5724: &escape($cloner), &escape($cc_clone), $cloneonly,
5725: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5726: &escape($creationcontext),$domcloner,$hasuniquecode,
5727: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5728: } else {
5729: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5730: $sincefilter.':'.&escape($descfilter).':'.
5731: &escape($instcodefilter).':'.&escape($ownerfilter).
5732: ':'.&escape($coursefilter).':'.&escape($typefilter).
5733: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5734: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5735: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5736: &escape($cc_clone).':'.$cloneonly.':'.
5737: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5738: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5739: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5740: }
5741:
1.918 raeburn 5742: my @pairs=split(/\&/,$rep);
5743: foreach my $item (@pairs) {
5744: my ($key,$value)=split(/\=/,$item,2);
5745: $key = &unescape($key);
5746: next if ($key =~ /^error: 2 /);
5747: my $result = &thaw_unescape($value);
5748: if (ref($result) eq 'HASH') {
5749: $returnhash{$key}=$result;
5750: } else {
1.921 raeburn 5751: my @responses = split(/:/,$value);
5752: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5753: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5754: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5755: }
1.1008 raeburn 5756: }
1.353 www 5757: }
5758: }
5759: }
5760: }
5761: return %returnhash;
5762: }
5763:
1.1055 raeburn 5764: sub courselastaccess {
5765: my ($cdom,$cnum,$hostidref) = @_;
5766: my %returnhash;
5767: if ($cdom && $cnum) {
5768: my $chome = &homeserver($cnum,$cdom);
5769: if ($chome ne 'no_host') {
5770: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5771: &extract_lastaccess(\%returnhash,$rep);
5772: }
5773: } else {
5774: if (!$cdom) { $cdom=''; }
5775: my %libserv = &all_library();
5776: foreach my $tryserver (keys(%libserv)) {
5777: if (ref($hostidref) eq 'ARRAY') {
5778: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5779: }
5780: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5781: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5782: &extract_lastaccess(\%returnhash,$rep);
5783: }
5784: }
5785: }
5786: return %returnhash;
5787: }
5788:
5789: sub extract_lastaccess {
5790: my ($returnhash,$rep) = @_;
5791: if (ref($returnhash) eq 'HASH') {
5792: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5793: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5794: $rep eq '') {
5795: my @pairs=split(/\&/,$rep);
5796: foreach my $item (@pairs) {
5797: my ($key,$value)=split(/\=/,$item,2);
5798: $key = &unescape($key);
5799: next if ($key =~ /^error: 2 /);
5800: $returnhash->{$key} = &thaw_unescape($value);
5801: }
5802: }
5803: }
5804: return;
5805: }
5806:
1.658 raeburn 5807: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5808:
5809: sub dcmailput {
1.685 raeburn 5810: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5811: my $status = &Apache::lonnet::critical(
1.740 www 5812: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5813: &escape($message),$server);
1.662 raeburn 5814: return $status;
5815: }
5816:
1.658 raeburn 5817: sub dcmaildump {
5818: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5819: my %returnhash=();
1.846 albertel 5820:
5821: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5822: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5823: &escape($enddate).':';
5824: my @esc_senders=map { &escape($_)} @$senders;
5825: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5826: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5827: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5828: if (($key) && ($value)) {
5829: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5830: }
5831: }
5832: }
5833: return %returnhash;
5834: }
1.662 raeburn 5835: # ---------------------------------------------------------- Domain roles
5836:
5837: sub get_domain_roles {
5838: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5839: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5840: $startdate = '.';
5841: }
1.1018 raeburn 5842: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5843: $enddate = '.';
5844: }
1.922 raeburn 5845: my $rolelist;
5846: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5847: $rolelist = join('&',@{$roles});
1.922 raeburn 5848: }
1.662 raeburn 5849: my %personnel = ();
1.841 albertel 5850:
5851: my %servers = &get_servers($dom,'library');
5852: foreach my $tryserver (keys(%servers)) {
5853: %{$personnel{$tryserver}}=();
5854: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5855: &escape($startdate).':'.
5856: &escape($enddate).':'.
5857: &escape($rolelist), $tryserver))) {
5858: my ($key,$value) = split(/\=/,$line,2);
5859: if (($key) && ($value)) {
5860: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5861: }
5862: }
1.662 raeburn 5863: }
5864: return %personnel;
5865: }
1.658 raeburn 5866:
1.1172.2.89 raeburn 5867: sub get_active_domroles {
5868: my ($dom,$roles) = @_;
5869: return () unless (ref($roles) eq 'ARRAY');
5870: my $now = time;
5871: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5872: my %domroles;
5873: foreach my $server (keys(%dompersonnel)) {
5874: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5875: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5876: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5877: }
5878: }
5879: return %domroles;
5880: }
5881:
1.1057 www 5882: # ----------------------------------------------------------- Interval timing
1.149 www 5883:
1.1153 www 5884: {
5885: # Caches needed for speedup of navmaps
5886: # We don't want to cache this for very long at all (5 seconds at most)
5887: #
5888: # The user for whom we cache
5889: my $cachedkey='';
5890: # The cached times for this user
5891: my %cachedtimes=();
5892: # When this was last done
1.1172.2.66 raeburn 5893: my $cachedtime='';
1.1153 www 5894:
5895: sub load_all_first_access {
1.1172.2.146. .1(raebu 5896:22): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5897: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146. .1(raebu 5898:22): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5899:22): (!$ignorecache)) {
1.1154 raeburn 5900: return;
5901: }
5902: $cachedtime=time;
5903: $cachedkey=$uname.':'.$udom;
5904: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5905: }
5906:
1.504 albertel 5907: sub get_first_access {
1.1172.2.146. .1(raebu 5908:22): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5909: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5910: if ($argsymb) { $symb=$argsymb; }
5911: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5912: if ($argmap) { $map = $argmap; }
1.926 albertel 5913: if ($type eq 'course') {
5914: $res='course';
5915: } elsif ($type eq 'map') {
1.588 albertel 5916: $res=&symbread($map);
5917: } else {
5918: $res=$symb;
5919: }
1.1172.2.146. .1(raebu 5920:22): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5921: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5922: }
5923:
5924: sub set_first_access {
1.1162 raeburn 5925: my ($type,$interval)=@_;
1.790 albertel 5926: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5927: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5928: if ($type eq 'course') {
5929: $res='course';
5930: } elsif ($type eq 'map') {
1.588 albertel 5931: $res=&symbread($map);
5932: } else {
5933: $res=$symb;
5934: }
1.1153 www 5935: $cachedkey='';
1.1162 raeburn 5936: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5937: if ($firstaccess) {
5938: &logthis("First access time already set ($firstaccess) when attempting ".
5939: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5940: "in $courseid");
5941: return 'already_set';
5942: } else {
1.1162 raeburn 5943: my $start = time;
5944: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5945: $udom,$uname);
5946: if ($putres eq 'ok') {
5947: &put('timerinterval',{"$courseid\0$res"=>$interval},
5948: $udom,$uname);
5949: &appenv(
5950: {
5951: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5952: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5953: }
5954: );
1.1172.2.97 raeburn 5955: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5956: $cachedtimes{"$courseid\0$res"} = $start;
5957: }
1.1172.2.102 raeburn 5958: } elsif ($putres ne 'refused') {
5959: &logthis("Result: $putres when attempting to set first access time ".
5960: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5961: }
5962: return $putres;
1.505 albertel 5963: }
5964: return 'already_set';
1.504 albertel 5965: }
1.1153 www 5966: }
1.1172.2.32 raeburn 5967:
5968: sub checkout {
5969: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5970: my $now=time;
5971: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5972: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5973: my $infostr=&escape(
5974: 'CHECKOUTTOKEN&'.
5975: $tuname.'&'.
5976: $tudom.'&'.
5977: $tcrsid.'&'.
5978: $symb.'&'.
1.1172.2.134 raeburn 5979: $now.'&'.$ip);
1.1172.2.32 raeburn 5980: my $token=&reply('tmpput:'.$infostr,$lonhost);
5981: if ($token=~/^error\:/) {
5982: &logthis("<font color=\"blue\">WARNING: ".
5983: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5984: "</font>");
5985: return '';
5986: }
5987:
5988: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5989: $token=~tr/a-z/A-Z/;
5990:
5991: my %infohash=('resource.0.outtoken' => $token,
5992: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5993: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5994:
5995: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5996: return '';
5997: } else {
5998: &logthis("<font color=\"blue\">WARNING: ".
5999: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
6000: "</font>");
6001: }
6002:
6003: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
6004: &escape('Checkout '.$infostr.' - '.
6005: $token)) ne 'ok') {
6006: return '';
6007: } else {
6008: &logthis("<font color=\"blue\">WARNING: ".
6009: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
6010: "</font>");
6011: }
6012: return $token;
6013: }
6014:
6015: # ------------------------------------------------------------ Check in an item
6016:
6017: sub checkin {
6018: my $token=shift;
6019: my $now=time;
6020: my ($ta,$tb,$lonhost)=split(/\*/,$token);
6021: $lonhost=~tr/A-Z/a-z/;
6022: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
6023: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 6024: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 6025: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
6026: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
6027:
6028: unless (($tuname) && ($tudom)) {
6029: &logthis('Check in '.$token.' ('.$dtoken.') failed');
6030: return '';
6031: }
6032:
6033: unless (&allowed('mgr',$tcrsid)) {
6034: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
6035: $env{'user.name'}.' - '.$env{'user.domain'});
6036: return '';
6037: }
6038:
6039: my %infohash=('resource.0.intoken' => $token,
6040: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 6041: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 6042:
6043: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
6044: return '';
6045: }
6046:
6047: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
6048: &escape('Checkin - '.$token)) ne 'ok') {
6049: return '';
6050: }
6051:
6052: return ($symb,$tuname,$tudom,$tcrsid);
6053: }
6054:
1.110 www 6055: # --------------------------------------------- Set Expire Date for Spreadsheet
6056:
6057: sub expirespread {
6058: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6059: my $cid=$env{'request.course.id'};
1.110 www 6060: if ($cid) {
6061: my $now=time;
6062: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6063: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6064: $env{'course.'.$cid.'.num'}.
1.110 www 6065: ':nohist_expirationdates:'.
6066: &escape($key).'='.$now,
1.620 albertel 6067: $env{'course.'.$cid.'.home'})
1.110 www 6068: }
6069: return 'ok';
1.14 www 6070: }
6071:
1.109 www 6072: # ----------------------------------------------------- Devalidate Spreadsheets
6073:
6074: sub devalidate {
1.325 www 6075: my ($symb,$uname,$udom)=@_;
1.620 albertel 6076: my $cid=$env{'request.course.id'};
1.109 www 6077: if ($cid) {
1.391 matthew 6078: # delete the stored spreadsheets for
6079: # - the student level sheet of this user in course's homespace
6080: # - the assessment level sheet for this resource
6081: # for this user in user's homespace
1.553 albertel 6082: # - current conditional state info
1.325 www 6083: my $key=$uname.':'.$udom.':';
1.109 www 6084: my $status=
1.299 matthew 6085: &del('nohist_calculatedsheets',
1.391 matthew 6086: [$key.'studentcalc:'],
1.620 albertel 6087: $env{'course.'.$cid.'.domain'},
6088: $env{'course.'.$cid.'.num'})
1.133 albertel 6089: .' '.
6090: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6091: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6092: unless ($status eq 'ok ok') {
6093: &logthis('Could not devalidate spreadsheet '.
1.325 www 6094: $uname.' at '.$udom.' for '.
1.109 www 6095: $symb.': '.$status);
1.133 albertel 6096: }
1.553 albertel 6097: &delenv('user.state.'.$cid);
1.109 www 6098: }
6099: }
6100:
1.265 albertel 6101: sub get_scalar {
6102: my ($string,$end) = @_;
6103: my $value;
6104: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6105: $value = $1;
6106: } elsif ($$string =~ s/^([^&]*?)&//) {
6107: $value = $1;
6108: }
6109: return &unescape($value);
6110: }
6111:
6112: sub array2str {
6113: my (@array) = @_;
6114: my $result=&arrayref2str(\@array);
6115: $result=~s/^__ARRAY_REF__//;
6116: $result=~s/__END_ARRAY_REF__$//;
6117: return $result;
6118: }
6119:
1.204 albertel 6120: sub arrayref2str {
6121: my ($arrayref) = @_;
1.265 albertel 6122: my $result='__ARRAY_REF__';
1.204 albertel 6123: foreach my $elem (@$arrayref) {
1.265 albertel 6124: if(ref($elem) eq 'ARRAY') {
6125: $result.=&arrayref2str($elem).'&';
6126: } elsif(ref($elem) eq 'HASH') {
6127: $result.=&hashref2str($elem).'&';
6128: } elsif(ref($elem)) {
6129: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6130: } else {
6131: $result.=&escape($elem).'&';
6132: }
6133: }
6134: $result=~s/\&$//;
1.265 albertel 6135: $result .= '__END_ARRAY_REF__';
1.204 albertel 6136: return $result;
6137: }
6138:
1.168 albertel 6139: sub hash2str {
1.204 albertel 6140: my (%hash) = @_;
6141: my $result=&hashref2str(\%hash);
1.265 albertel 6142: $result=~s/^__HASH_REF__//;
6143: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6144: return $result;
6145: }
6146:
6147: sub hashref2str {
6148: my ($hashref)=@_;
1.265 albertel 6149: my $result='__HASH_REF__';
1.800 albertel 6150: foreach my $key (sort(keys(%$hashref))) {
6151: if (ref($key) eq 'ARRAY') {
6152: $result.=&arrayref2str($key).'=';
6153: } elsif (ref($key) eq 'HASH') {
6154: $result.=&hashref2str($key).'=';
6155: } elsif (ref($key)) {
1.265 albertel 6156: $result.='=';
1.800 albertel 6157: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6158: } else {
1.1132 raeburn 6159: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6160: }
6161:
1.800 albertel 6162: if(ref($hashref->{$key}) eq 'ARRAY') {
6163: $result.=&arrayref2str($hashref->{$key}).'&';
6164: } elsif(ref($hashref->{$key}) eq 'HASH') {
6165: $result.=&hashref2str($hashref->{$key}).'&';
6166: } elsif(ref($hashref->{$key})) {
1.265 albertel 6167: $result.='&';
1.800 albertel 6168: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6169: } else {
1.800 albertel 6170: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6171: }
6172: }
1.168 albertel 6173: $result=~s/\&$//;
1.265 albertel 6174: $result .= '__END_HASH_REF__';
1.168 albertel 6175: return $result;
6176: }
6177:
6178: sub str2hash {
1.265 albertel 6179: my ($string)=@_;
6180: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6181: return %$hash;
6182: }
6183:
6184: sub str2hashref {
1.168 albertel 6185: my ($string) = @_;
1.265 albertel 6186:
6187: my %hash;
6188:
6189: if($string !~ /^__HASH_REF__/) {
6190: if (! ($string eq '' || !defined($string))) {
6191: $hash{'error'}='Not hash reference';
6192: }
6193: return (\%hash, $string);
6194: }
6195:
6196: $string =~ s/^__HASH_REF__//;
6197:
6198: while($string !~ /^__END_HASH_REF__/) {
6199: #key
6200: my $key='';
6201: if($string =~ /^__HASH_REF__/) {
6202: ($key, $string)=&str2hashref($string);
6203: if(defined($key->{'error'})) {
6204: $hash{'error'}='Bad data';
6205: return (\%hash, $string);
6206: }
6207: } elsif($string =~ /^__ARRAY_REF__/) {
6208: ($key, $string)=&str2arrayref($string);
6209: if($key->[0] eq 'Array reference error') {
6210: $hash{'error'}='Bad data';
6211: return (\%hash, $string);
6212: }
6213: } else {
6214: $string =~ s/^(.*?)=//;
1.267 albertel 6215: $key=&unescape($1);
1.265 albertel 6216: }
6217: $string =~ s/^=//;
6218:
6219: #value
6220: my $value='';
6221: if($string =~ /^__HASH_REF__/) {
6222: ($value, $string)=&str2hashref($string);
6223: if(defined($value->{'error'})) {
6224: $hash{'error'}='Bad data';
6225: return (\%hash, $string);
6226: }
6227: } elsif($string =~ /^__ARRAY_REF__/) {
6228: ($value, $string)=&str2arrayref($string);
6229: if($value->[0] eq 'Array reference error') {
6230: $hash{'error'}='Bad data';
6231: return (\%hash, $string);
6232: }
6233: } else {
6234: $value=&get_scalar(\$string,'__END_HASH_REF__');
6235: }
6236: $string =~ s/^&//;
6237:
6238: $hash{$key}=$value;
1.204 albertel 6239: }
1.265 albertel 6240:
6241: $string =~ s/^__END_HASH_REF__//;
6242:
6243: return (\%hash, $string);
1.204 albertel 6244: }
6245:
6246: sub str2array {
1.265 albertel 6247: my ($string)=@_;
6248: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6249: return @$array;
6250: }
6251:
6252: sub str2arrayref {
1.204 albertel 6253: my ($string) = @_;
1.265 albertel 6254: my @array;
6255:
6256: if($string !~ /^__ARRAY_REF__/) {
6257: if (! ($string eq '' || !defined($string))) {
6258: $array[0]='Array reference error';
6259: }
6260: return (\@array, $string);
6261: }
6262:
6263: $string =~ s/^__ARRAY_REF__//;
6264:
6265: while($string !~ /^__END_ARRAY_REF__/) {
6266: my $value='';
6267: if($string =~ /^__HASH_REF__/) {
6268: ($value, $string)=&str2hashref($string);
6269: if(defined($value->{'error'})) {
6270: $array[0] ='Array reference error';
6271: return (\@array, $string);
6272: }
6273: } elsif($string =~ /^__ARRAY_REF__/) {
6274: ($value, $string)=&str2arrayref($string);
6275: if($value->[0] eq 'Array reference error') {
6276: $array[0] ='Array reference error';
6277: return (\@array, $string);
6278: }
6279: } else {
6280: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6281: }
6282: $string =~ s/^&//;
6283:
6284: push(@array, $value);
1.191 harris41 6285: }
1.265 albertel 6286:
6287: $string =~ s/^__END_ARRAY_REF__//;
6288:
6289: return (\@array, $string);
1.168 albertel 6290: }
6291:
1.167 albertel 6292: # -------------------------------------------------------------------Temp Store
6293:
1.168 albertel 6294: sub tmpreset {
6295: my ($symb,$namespace,$domain,$stuname) = @_;
6296: if (!$symb) {
6297: $symb=&symbread();
1.620 albertel 6298: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6299: }
6300: $symb=escape($symb);
6301:
1.620 albertel 6302: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6303: $namespace=~s/\//\_/g;
6304: $namespace=~s/\W//g;
6305:
1.620 albertel 6306: if (!$domain) { $domain=$env{'user.domain'}; }
6307: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6308: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6309: $stuname=&get_requestor_ip();
1.591 albertel 6310: }
1.1117 foxr 6311: my $path=LONCAPA::tempdir();
1.168 albertel 6312: my %hash;
6313: if (tie(%hash,'GDBM_File',
6314: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6315: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6316: foreach my $key (keys(%hash)) {
1.180 albertel 6317: if ($key=~ /:$symb/) {
1.168 albertel 6318: delete($hash{$key});
6319: }
6320: }
6321: }
6322: }
6323:
1.167 albertel 6324: sub tmpstore {
1.168 albertel 6325: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6326:
6327: if (!$symb) {
6328: $symb=&symbread();
1.620 albertel 6329: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6330: }
6331: $symb=escape($symb);
6332:
6333: if (!$namespace) {
6334: # I don't think we would ever want to store this for a course.
6335: # it seems this will only be used if we don't have a course.
1.620 albertel 6336: #$namespace=$env{'request.course.id'};
1.168 albertel 6337: #if (!$namespace) {
1.620 albertel 6338: $namespace=$env{'request.state'};
1.168 albertel 6339: #}
6340: }
6341: $namespace=~s/\//\_/g;
6342: $namespace=~s/\W//g;
1.620 albertel 6343: if (!$domain) { $domain=$env{'user.domain'}; }
6344: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6345: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6346: $stuname=&get_requestor_ip();
1.591 albertel 6347: }
1.168 albertel 6348: my $now=time;
6349: my %hash;
1.1117 foxr 6350: my $path=LONCAPA::tempdir();
1.168 albertel 6351: if (tie(%hash,'GDBM_File',
6352: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6353: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6354: $hash{"version:$symb"}++;
6355: my $version=$hash{"version:$symb"};
6356: my $allkeys='';
6357: foreach my $key (keys(%$storehash)) {
6358: $allkeys.=$key.':';
1.591 albertel 6359: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6360: }
6361: $hash{"$version:$symb:timestamp"}=$now;
6362: $allkeys.='timestamp';
6363: $hash{"$version:keys:$symb"}=$allkeys;
6364: if (untie(%hash)) {
6365: return 'ok';
6366: } else {
6367: return "error:$!";
6368: }
6369: } else {
6370: return "error:$!";
6371: }
6372: }
1.167 albertel 6373:
1.168 albertel 6374: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6375:
1.168 albertel 6376: sub tmprestore {
6377: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6378:
1.168 albertel 6379: if (!$symb) {
6380: $symb=&symbread();
1.620 albertel 6381: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6382: }
6383: $symb=escape($symb);
6384:
1.620 albertel 6385: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6386:
1.620 albertel 6387: if (!$domain) { $domain=$env{'user.domain'}; }
6388: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6389: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6390: $stuname=&get_requestor_ip();
1.591 albertel 6391: }
1.168 albertel 6392: my %returnhash;
6393: $namespace=~s/\//\_/g;
6394: $namespace=~s/\W//g;
6395: my %hash;
1.1117 foxr 6396: my $path=LONCAPA::tempdir();
1.168 albertel 6397: if (tie(%hash,'GDBM_File',
6398: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6399: &GDBM_READER(),0640)) {
1.168 albertel 6400: my $version=$hash{"version:$symb"};
6401: $returnhash{'version'}=$version;
6402: my $scope;
6403: for ($scope=1;$scope<=$version;$scope++) {
6404: my $vkeys=$hash{"$scope:keys:$symb"};
6405: my @keys=split(/:/,$vkeys);
6406: my $key;
6407: $returnhash{"$scope:keys"}=$vkeys;
6408: foreach $key (@keys) {
1.591 albertel 6409: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6410: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6411: }
6412: }
1.168 albertel 6413: if (!(untie(%hash))) {
6414: return "error:$!";
6415: }
6416: } else {
6417: return "error:$!";
6418: }
6419: return %returnhash;
1.167 albertel 6420: }
6421:
1.9 www 6422: # ----------------------------------------------------------------------- Store
6423:
6424: sub store {
1.1172.2.64 raeburn 6425: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6426: my $home='';
6427:
1.168 albertel 6428: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6429:
1.213 www 6430: $symb=&symbclean($symb);
1.122 albertel 6431: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6432:
1.620 albertel 6433: if (!$domain) { $domain=$env{'user.domain'}; }
6434: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6435:
6436: &devalidate($symb,$stuname,$domain);
1.109 www 6437:
6438: $symb=escape($symb);
1.187 www 6439: if (!$namespace) {
1.620 albertel 6440: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6441: return '';
6442: }
6443: }
1.620 albertel 6444: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6445:
1.1172.2.138 raeburn 6446: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6447: $$storehash{'host'}=$perlvar{'lonHostID'};
6448:
1.12 www 6449: my $namevalue='';
1.800 albertel 6450: foreach my $key (keys(%$storehash)) {
6451: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6452: }
1.12 www 6453: $namevalue=~s/\&$//;
1.187 www 6454: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6455: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6456: }
6457:
1.47 www 6458: # -------------------------------------------------------------- Critical Store
6459:
6460: sub cstore {
1.1172.2.64 raeburn 6461: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6462: my $home='';
6463:
1.168 albertel 6464: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6465:
1.213 www 6466: $symb=&symbclean($symb);
1.122 albertel 6467: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6468:
1.620 albertel 6469: if (!$domain) { $domain=$env{'user.domain'}; }
6470: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6471:
6472: &devalidate($symb,$stuname,$domain);
1.109 www 6473:
6474: $symb=escape($symb);
1.187 www 6475: if (!$namespace) {
1.620 albertel 6476: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6477: return '';
6478: }
6479: }
1.620 albertel 6480: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6481:
1.1172.2.138 raeburn 6482: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6483: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6484:
1.47 www 6485: my $namevalue='';
1.800 albertel 6486: foreach my $key (keys(%$storehash)) {
6487: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6488: }
1.47 www 6489: $namevalue=~s/\&$//;
1.187 www 6490: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6491: return critical
1.1172.2.64 raeburn 6492: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6493: }
6494:
1.9 www 6495: # --------------------------------------------------------------------- Restore
6496:
6497: sub restore {
1.124 www 6498: my ($symb,$namespace,$domain,$stuname) = @_;
6499: my $home='';
6500:
1.168 albertel 6501: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6502:
1.122 albertel 6503: if (!$symb) {
1.1172.2.26 raeburn 6504: return if ($namespace eq 'courserequests');
6505: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6506: } else {
1.1172.2.26 raeburn 6507: unless ($namespace eq 'courserequests') {
6508: $symb=&escape(&symbclean($symb));
6509: }
1.122 albertel 6510: }
1.188 www 6511: if (!$namespace) {
1.620 albertel 6512: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6513: return '';
6514: }
6515: }
1.620 albertel 6516: if (!$domain) { $domain=$env{'user.domain'}; }
6517: if (!$stuname) { $stuname=$env{'user.name'}; }
6518: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6519: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6520:
1.12 www 6521: my %returnhash=();
1.800 albertel 6522: foreach my $line (split(/\&/,$answer)) {
6523: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6524: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6525: }
1.75 www 6526: my $version;
6527: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6528: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6529: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6530: }
1.75 www 6531: }
1.13 www 6532: return %returnhash;
1.34 www 6533: }
6534:
6535: # ---------------------------------------------------------- Course Description
1.1118 foxr 6536: #
6537: #
1.34 www 6538:
6539: sub coursedescription {
1.731 albertel 6540: my ($courseid,$args)=@_;
1.34 www 6541: $courseid=~s/^\///;
1.49 www 6542: $courseid=~s/\_/\//g;
1.34 www 6543: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6544: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6545: my $normalid=$cdomain.'_'.$cnum;
6546: # need to always cache even if we get errors otherwise we keep
6547: # trying and trying and trying to get the course description.
6548: my %envhash=();
6549: my %returnhash=();
1.731 albertel 6550:
6551: my $expiretime=600;
6552: if ($env{'request.course.id'} eq $normalid) {
6553: $expiretime=120;
6554: }
6555:
6556: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6557: if (!$args->{'freshen_cache'}
6558: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6559: foreach my $key (keys(%env)) {
6560: next if ($key !~ /^\Q$prefix\E(.*)/);
6561: my ($setting) = $1;
6562: $returnhash{$setting} = $env{$key};
6563: }
6564: return %returnhash;
6565: }
6566:
1.1118 foxr 6567: # get the data again
6568:
1.731 albertel 6569: if (!$args->{'one_time'}) {
6570: $envhash{'course.'.$normalid.'.last_cache'}=time;
6571: }
1.811 albertel 6572:
1.34 www 6573: if ($chome ne 'no_host') {
1.302 albertel 6574: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6575: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6576: my $username = $env{'user.name'}; # Defult username
6577: if(defined $args->{'user'}) {
6578: $username = $args->{'user'};
6579: }
1.129 albertel 6580: $returnhash{'home'}= $chome;
6581: $returnhash{'domain'} = $cdomain;
6582: $returnhash{'num'} = $cnum;
1.741 raeburn 6583: if (!defined($returnhash{'type'})) {
6584: $returnhash{'type'} = 'Course';
6585: }
1.130 albertel 6586: while (my ($name,$value) = each %returnhash) {
1.53 www 6587: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6588: }
1.270 www 6589: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6590: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6591: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6592: $envhash{'course.'.$normalid.'.home'}=$chome;
6593: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6594: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6595: }
6596: }
1.731 albertel 6597: if (!$args->{'one_time'}) {
1.949 raeburn 6598: &appenv(\%envhash);
1.731 albertel 6599: }
1.302 albertel 6600: return %returnhash;
1.461 www 6601: }
6602:
1.1080 raeburn 6603: sub update_released_required {
6604: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6605: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6606: $cid = $env{'request.course.id'};
6607: $cdom = $env{'course.'.$cid.'.domain'};
6608: $cnum = $env{'course.'.$cid.'.num'};
6609: $chome = $env{'course.'.$cid.'.home'};
6610: }
6611: if ($needsrelease) {
6612: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6613: my $needsupdate;
6614: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6615: $needsupdate = 1;
6616: } else {
6617: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6618: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6619: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6620: $needsupdate = 1;
6621: }
6622: }
6623: if ($needsupdate) {
6624: my %needshash = (
6625: 'internal.releaserequired' => $needsrelease,
6626: );
6627: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6628: if ($putresult eq 'ok') {
6629: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6630: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6631: if (ref($crsinfo{$cid}) eq 'HASH') {
6632: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6633: &courseidput($cdom,\%crsinfo,$chome,'notime');
6634: }
6635: }
6636: }
6637: }
6638: return;
6639: }
6640:
1.461 www 6641: # -------------------------------------------------See if a user is privileged
6642:
6643: sub privileged {
1.1172.2.23 raeburn 6644: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6645: my $now = time;
1.1172.2.23 raeburn 6646: my $roles;
6647: if (ref($possroles) eq 'ARRAY') {
6648: $roles = $possroles;
6649: } else {
6650: $roles = ['dc','su'];
6651: }
6652: if (ref($possdomains) eq 'ARRAY') {
6653: my %privileged = &privileged_by_domain($possdomains,$roles);
6654: foreach my $dom (@{$possdomains}) {
6655: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6656: (ref($privileged{$dom}) eq 'HASH')) {
6657: foreach my $role (@{$roles}) {
6658: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6659: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6660: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6661: return 1 unless (($end && $end < $now) ||
6662: ($start && $start > $now));
6663: }
6664: }
6665: }
6666: }
6667: }
6668: } else {
6669: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6670: my $now = time;
1.1170 droeschl 6671:
1.1172.2.58 raeburn 6672: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6673: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6674: if (grep(/^\Q$trole\E$/,@{$roles})) {
6675: return 1 unless ($tend && $tend < $now)
6676: or ($tstart && $tstart > $now);
1.1170 droeschl 6677: }
1.1172.2.23 raeburn 6678: }
6679: }
1.461 www 6680: return 0;
1.9 www 6681: }
1.1 albertel 6682:
1.1172.2.23 raeburn 6683: sub privileged_by_domain {
6684: my ($domains,$roles) = @_;
6685: my %privileged = ();
6686: my $cachetime = 60*60*24;
6687: my $now = time;
6688: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6689: return %privileged;
6690: }
6691: foreach my $dom (@{$domains}) {
6692: next if (ref($privileged{$dom}) eq 'HASH');
6693: my $needroles;
6694: foreach my $role (@{$roles}) {
6695: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6696: if (defined($cached)) {
6697: if (ref($result) eq 'HASH') {
6698: $privileged{$dom}{$role} = $result;
6699: }
6700: } else {
6701: $needroles = 1;
6702: }
6703: }
6704: if ($needroles) {
6705: my %dompersonnel = &get_domain_roles($dom,$roles);
6706: $privileged{$dom} = {};
6707: foreach my $server (keys(%dompersonnel)) {
6708: if (ref($dompersonnel{$server}) eq 'HASH') {
6709: foreach my $item (keys(%{$dompersonnel{$server}})) {
6710: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6711: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6712: next if ($end && $end < $now);
6713: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6714: $dompersonnel{$server}{$item};
6715: }
6716: }
6717: }
6718: if (ref($privileged{$dom}) eq 'HASH') {
6719: foreach my $role (@{$roles}) {
6720: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6721: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6722: } else {
6723: my %hash = ();
6724: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6725: }
6726: }
6727: }
6728: }
6729: }
6730: return %privileged;
6731: }
6732:
1.103 harris41 6733: # -------------------------------------------------------- Get user privileges
1.11 www 6734:
6735: sub rolesinit {
1.1169 droeschl 6736: my ($domain, $username) = @_;
6737: my %userroles = ('user.login.time' => time);
6738: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6739:
6740: # firstaccess and timerinterval are related to timed maps/resources.
6741: # also, blocking can be triggered by an activating timer
6742: # it's saved in the user's %env.
6743: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6744: my %timerinterval = &dump('timerinterval', $domain, $username);
6745: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1172.2.146. .18(raeb 6746:-24): %timerintchk, %timerintenv,%coauthorenv);
1.1169 droeschl 6747:
1.1162 raeburn 6748: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6749: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6750: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6751: }
1.1169 droeschl 6752:
1.1162 raeburn 6753: foreach my $key (keys(%timerinterval)) {
6754: my ($cid,$rest) = split(/\0/,$key);
6755: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6756: }
1.1169 droeschl 6757:
1.11 www 6758: my %allroles=();
1.1162 raeburn 6759: my %allgroups=();
1.1172.2.146. .18(raeb 6760:-24): my %gotcoauconfig=();
.20(raeb 6761:-24): my %domdefaults=();
1.11 www 6762:
1.1172.2.58 raeburn 6763: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6764: my $role = $rolesdump{$area};
6765: $area =~ s/\_\w\w$//;
6766:
6767: my ($trole, $tend, $tstart, $group_privs);
6768:
6769: if ($role =~ /^cr/) {
6770: # Custom role, defined by a user
6771: # e.g., user.role.cr/msu/smith/mynewrole
6772: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6773: $trole = $1;
6774: ($tend, $tstart) = split('_', $2);
6775: } else {
6776: $trole = $role;
6777: }
6778: } elsif ($role =~ m|^gr/|) {
6779: # Role of member in a group, defined within a course/community
6780: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6781: ($trole, $tend, $tstart) = split(/_/, $role);
6782: next if $tstart eq '-1';
6783: ($trole, $group_privs) = split(/\//, $trole);
6784: $group_privs = &unescape($group_privs);
6785: } else {
6786: # Just a normal role, defined in roles.tab
6787: ($trole, $tend, $tstart) = split(/_/,$role);
6788: }
6789:
6790: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6791: $username);
6792: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6793:
6794: # role expired or not available yet?
6795: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6796: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6797:
6798: next if $area eq '' or $trole eq '';
6799:
6800: my $spec = "$trole.$area";
6801: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6802:
6803: if ($trole =~ /^cr\//) {
6804: # Custom role, defined by a user
6805: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6806: } elsif ($trole eq 'gr') {
6807: # Role of a member in a group, defined within a course/community
6808: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6809: next;
6810: } else {
6811: # Normal role, defined in roles.tab
6812: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1172.2.146. .18(raeb 6813:-24): if (($trole eq 'ca') || ($trole eq 'aa')) {
6814:-24): (undef,my ($audom,$auname)) = split(/\//,$area);
6815:-24): unless ($gotcoauconfig{$area}) {
6816:-24): my @ca_settings = ('authoreditors');
6817:-24): my %info = &userenvironment($audom,$auname,@ca_settings);
6818:-24): $gotcoauconfig{$area} = 1;
6819:-24): foreach my $item (@ca_settings) {
6820:-24): if (exists($info{$item})) {
6821:-24): my $name = $item;
6822:-24): if ($item eq 'authoreditors') {
6823:-24): $name = 'editors';
.20(raeb 6824:-24): unless ($info{'authoreditors'}) {
6825:-24): my %domdefs;
6826:-24): if (ref($domdefaults{$audom}) eq 'HASH') {
6827:-24): %domdefs = %{$domdefaults{$audom}};
6828:-24): } else {
6829:-24): %domdefs = &get_domain_defaults($audom);
6830:-24): $domdefaults{$audom} = \%domdefs;
6831:-24): }
6832:-24): if ($domdefs{$name} ne '') {
6833:-24): $info{'authoreditors'} = $domdefs{$name};
6834:-24): } else {
6835:-24): $info{'authoreditors'} = 'edit,xml';
6836:-24): }
6837:-24): }
.18(raeb 6838:-24): }
6839:-24): $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
6840:-24): }
6841:-24): }
6842:-24): }
6843:-24): }
1.1169 droeschl 6844: }
6845:
6846: my $cid = $tdomain.'_'.$trest;
6847: unless ($firstaccchk{$cid}) {
6848: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6849: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6850: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6851: $coursetimerstarts{$cid}{$item};
6852: }
6853: }
6854: $firstaccchk{$cid} = 1;
6855: }
6856: unless ($timerintchk{$cid}) {
6857: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6858: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6859: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6860: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6861: }
1.12 www 6862: }
1.1169 droeschl 6863: $timerintchk{$cid} = 1;
1.191 harris41 6864: }
1.11 www 6865: }
1.1169 droeschl 6866:
1.1172.2.91 raeburn 6867: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6868: \%allroles, \%allgroups);
1.1169 droeschl 6869: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6870: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6871:
1.1172.2.146. .18(raeb 6872:-24): return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11 www 6873: }
6874:
1.567 raeburn 6875: sub set_arearole {
1.1172.2.19 raeburn 6876: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6877: unless ($nolog) {
1.567 raeburn 6878: # log the associated role with the area
1.1172.2.19 raeburn 6879: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6880: }
1.743 albertel 6881: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6882: }
6883:
6884: sub custom_roleprivs {
6885: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6886: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6887: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6888: if (&hostname($homsvr) ne '') {
1.567 raeburn 6889: my ($rdummy,$roledef)=
6890: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6891: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6892: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6893: if (defined($syspriv)) {
1.1043 raeburn 6894: if ($trest =~ /^$match_community$/) {
6895: $syspriv =~ s/bre\&S//;
6896: }
1.567 raeburn 6897: $$allroles{'cm./'}.=':'.$syspriv;
6898: $$allroles{$spec.'./'}.=':'.$syspriv;
6899: }
6900: if ($tdomain ne '') {
6901: if (defined($dompriv)) {
6902: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6903: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6904: }
6905: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6906: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6907: my $rolename = $1;
6908: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6909: }
1.567 raeburn 6910: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6911: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6912: }
6913: }
6914: }
6915: }
6916: }
6917:
1.1172.2.89 raeburn 6918: sub course_adhocrole_privs {
6919: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6920: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6921: if ($overrides{"internal.adhocpriv.$rolename"}) {
6922: my (%currprivs,%storeprivs);
6923: foreach my $item (split(/:/,$coursepriv)) {
6924: my ($priv,$restrict) = split(/\&/,$item);
6925: $currprivs{$priv} = $restrict;
6926: }
6927: my (%possadd,%possremove,%full);
6928: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6929: my ($priv,$restrict)=split(/\&/,$item);
6930: $full{$priv} = $restrict;
6931: }
6932: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146. .6(raebu 6933:22): next if ($item eq '');
6934:22): my ($rule,$rest) = split(/=/,$item);
6935:22): next unless (($rule eq 'off') || ($rule eq 'on'));
6936:22): foreach my $priv (split(/:/,$rest)) {
6937:22): if ($priv ne '') {
6938:22): if ($rule eq 'off') {
6939:22): $possremove{$priv} = 1;
6940:22): } else {
6941:22): $possadd{$priv} = 1;
6942:22): }
6943:22): }
6944:22): }
6945:22): }
6946:22): foreach my $priv (sort(keys(%full))) {
6947:22): if (exists($currprivs{$priv})) {
6948:22): unless (exists($possremove{$priv})) {
6949:22): $storeprivs{$priv} = $currprivs{$priv};
6950:22): }
6951:22): } elsif (exists($possadd{$priv})) {
6952:22): $storeprivs{$priv} = $full{$priv};
6953:22): }
6954:22): }
6955:22): $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6956:22): }
6957:22): return $coursepriv;
1.1172.2.89 raeburn 6958: }
6959:
1.678 raeburn 6960: sub group_roleprivs {
6961: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6962: my $access = 1;
6963: my $now = time;
6964: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6965: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6966: if ($access) {
1.811 albertel 6967: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6968: $$allgroups{$course}{$group} .=':'.$group_privs;
6969: }
6970: }
1.567 raeburn 6971:
6972: sub standard_roleprivs {
6973: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6974: if (defined($pr{$trole.':s'})) {
6975: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6976: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6977: }
6978: if ($tdomain ne '') {
6979: if (defined($pr{$trole.':d'})) {
6980: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6981: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6982: }
6983: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6984: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6985: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6986: }
6987: }
6988: }
6989:
6990: sub set_userprivs {
1.1064 raeburn 6991: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6992: my $author=0;
6993: my $adv=0;
1.1172.2.91 raeburn 6994: my $rar=0;
1.678 raeburn 6995: my %grouproles = ();
6996: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6997: my @groupkeys;
1.1000 raeburn 6998: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6999: push(@groupkeys,$role);
7000: }
7001: if (ref($groups_roles) eq 'HASH') {
7002: foreach my $key (keys(%{$groups_roles})) {
7003: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7004: push(@groupkeys,$key);
7005: }
7006: }
7007: }
7008: if (@groupkeys > 0) {
7009: foreach my $role (@groupkeys) {
7010: my ($trole,$area,$sec,$extendedarea);
7011: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7012: $trole = $1;
7013: $area = $2;
7014: $sec = $3;
7015: $extendedarea = $area.$sec;
7016: if (exists($$allgroups{$area})) {
7017: foreach my $group (keys(%{$$allgroups{$area}})) {
7018: my $spec = $trole.'.'.$extendedarea;
7019: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7020: $$allgroups{$area}{$group};
1.1064 raeburn 7021: }
1.678 raeburn 7022: }
7023: }
7024: }
7025: }
7026: }
1.800 albertel 7027: foreach my $group (keys(%grouproles)) {
7028: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7029: }
1.800 albertel 7030: foreach my $role (keys(%{$allroles})) {
7031: my %thesepriv;
1.941 raeburn 7032: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7033: foreach my $item (split(/:/,$$allroles{$role})) {
7034: if ($item ne '') {
7035: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7036: if ($restrictions eq '') {
7037: $thesepriv{$privilege}='F';
7038: } elsif ($thesepriv{$privilege} ne 'F') {
7039: $thesepriv{$privilege}.=$restrictions;
7040: }
7041: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 7042: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7043: }
7044: }
7045: my $thesestr='';
1.1104 raeburn 7046: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7047: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7048: }
7049: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7050: }
1.1172.2.91 raeburn 7051: return ($author,$adv,$rar);
1.567 raeburn 7052: }
7053:
1.994 raeburn 7054: sub role_status {
1.1104 raeburn 7055: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7056: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 7057: my ($one,$two) = split(m{\./},$rolekey,2);
7058: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7059: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 7060: $$where = '/'.$two;
1.994 raeburn 7061: $$trolecode=$$role.'.'.$$where;
7062: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7063: $$tstatus='is';
1.1104 raeburn 7064: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7065: $$tstatus='future';
1.1034 raeburn 7066: if ($$tstart<$now) {
7067: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7068: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7069: my (%allroles,%allgroups,$group_privs,
7070: %groups_roles,@rolecodes);
1.1002 raeburn 7071: my %userroles = (
7072: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7073: );
1.1064 raeburn 7074: @rolecodes = ('cm');
1.1002 raeburn 7075: my $spec=$$role.'.'.$$where;
7076: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7077: if ($$role =~ /^cr\//) {
7078: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7079: push(@rolecodes,'cr');
1.1002 raeburn 7080: } elsif ($$role eq 'gr') {
1.1064 raeburn 7081: push(@rolecodes,$$role);
1.1002 raeburn 7082: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7083: $env{'user.name'});
1.1064 raeburn 7084: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7085: (undef,my $group_privs) = split(/\//,$trole);
7086: $group_privs = &unescape($group_privs);
7087: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7088: 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 7089: &get_groups_roles($tdomain,$trest,
7090: \%course_roles,\@rolecodes,
7091: \%groups_roles);
1.1002 raeburn 7092: } else {
1.1064 raeburn 7093: push(@rolecodes,$$role);
1.1002 raeburn 7094: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7095: }
1.1172.2.91 raeburn 7096: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7097: \%groups_roles);
1.1064 raeburn 7098: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 7099: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7100: }
7101: }
1.1034 raeburn 7102: $$tstatus = 'is';
1.1002 raeburn 7103: }
1.994 raeburn 7104: }
7105: if ($$tend) {
1.1104 raeburn 7106: if ($$tend<$update) {
1.994 raeburn 7107: $$tstatus='expired';
7108: } elsif ($$tend<$now) {
7109: $$tstatus='will_not';
7110: }
7111: }
7112: }
7113: }
7114: }
7115:
1.1104 raeburn 7116: sub get_groups_roles {
7117: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7118: return unless((ref($cdom_courseroles) eq 'HASH') &&
7119: (ref($rolecodes) eq 'ARRAY') &&
7120: (ref($groups_roles) eq 'HASH'));
7121: if (keys(%{$cdom_courseroles}) > 0) {
7122: my ($cnum) = ($rest =~ /^($match_courseid)/);
7123: if ($cdom ne '' && $cnum ne '') {
7124: foreach my $key (keys(%{$cdom_courseroles})) {
7125: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7126: my $crsrole = $1;
7127: my $crssec = $2;
7128: if ($crsrole =~ /^cr/) {
7129: unless (grep(/^cr$/,@{$rolecodes})) {
7130: push(@{$rolecodes},'cr');
7131: }
7132: } else {
7133: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7134: push(@{$rolecodes},$crsrole);
7135: }
7136: }
7137: my $rolekey = "$crsrole./$cdom/$cnum";
7138: if ($crssec ne '') {
7139: $rolekey .= "/$crssec";
7140: }
7141: $rolekey .= './';
7142: $groups_roles->{$rolekey} = $rolecodes;
7143: }
7144: }
7145: }
7146: }
7147: return;
7148: }
7149:
7150: sub delete_env_groupprivs {
7151: my ($where,$courseroles,$possroles) = @_;
7152: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7153: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7154: unless (ref($courseroles->{$udom}) eq 'HASH') {
7155: %{$courseroles->{$udom}} =
7156: &get_my_roles('','','userroles',['active'],
7157: $possroles,[$udom],1);
7158: }
7159: if (ref($courseroles->{$udom}) eq 'HASH') {
7160: foreach my $item (keys(%{$courseroles->{$udom}})) {
7161: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7162: my $area = '/'.$cdom.'/'.$cnum;
7163: my $privkey = "user.priv.$crsrole.$area";
7164: if ($crssec ne '') {
7165: $privkey .= '/'.$crssec;
7166: }
7167: $privkey .= ".$area/$group";
7168: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7169: }
7170: }
7171: return;
7172: }
7173:
1.994 raeburn 7174: sub check_adhoc_privs {
1.1172.2.86 raeburn 7175: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7176: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 7177: if ($sec) {
7178: $cckey .= '/'.$sec;
7179: }
1.1172.2.9 raeburn 7180: my $setprivs;
1.994 raeburn 7181: if ($env{$cckey}) {
7182: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7183: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7184: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 7185: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 7186: $setprivs = 1;
1.994 raeburn 7187: }
7188: } else {
1.1172.2.87 raeburn 7189: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 7190: $setprivs = 1;
1.994 raeburn 7191: }
1.1172.2.9 raeburn 7192: return $setprivs;
1.994 raeburn 7193: }
7194:
7195: sub set_adhoc_privileges {
1.1172.2.84 raeburn 7196: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 7197: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7198: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 7199: if ($sec ne '') {
7200: $area .= '/'.$sec;
7201: }
1.994 raeburn 7202: my $spec = $role.'.'.$area;
7203: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 7204: $env{'user.name'},1);
1.1172.2.84 raeburn 7205: my %rolehash = ();
1.1172.2.89 raeburn 7206: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7207: my $rolename = $1;
1.1172.2.84 raeburn 7208: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 7209: my %domdef = &get_domain_defaults($dcdom);
7210: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7211: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7212: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7213: }
7214: }
1.1172.2.84 raeburn 7215: } else {
7216: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7217: }
1.1172.2.91 raeburn 7218: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7219: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 7220: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146. .1(raebu 7221:22): unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7222:22): ($caller eq 'tiny')) {
1.1088 raeburn 7223: &appenv( {'request.role' => $spec,
7224: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 7225: 'request.course.sec' => $sec,
1.1088 raeburn 7226: }
7227: );
7228: my $tadv=0;
7229: if (&allowed('adv') eq 'F') { $tadv=1; }
7230: &appenv({'request.role.adv' => $tadv});
7231: }
1.994 raeburn 7232: }
7233:
1.12 www 7234: # --------------------------------------------------------------- get interface
7235:
7236: sub get {
1.131 albertel 7237: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7238: my $items='';
1.800 albertel 7239: foreach my $item (@$storearr) {
7240: $items.=&escape($item).'&';
1.191 harris41 7241: }
1.12 www 7242: $items=~s/\&$//;
1.620 albertel 7243: if (!$udomain) { $udomain=$env{'user.domain'}; }
7244: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7245: my $uhome=&homeserver($uname,$udomain);
7246:
1.133 albertel 7247: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7248: my @pairs=split(/\&/,$rep);
1.273 albertel 7249: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7250: return @pairs;
7251: }
1.15 www 7252: my %returnhash=();
1.42 www 7253: my $i=0;
1.800 albertel 7254: foreach my $item (@$storearr) {
7255: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7256: $i++;
1.191 harris41 7257: }
1.15 www 7258: return %returnhash;
1.27 www 7259: }
7260:
7261: # --------------------------------------------------------------- del interface
7262:
7263: sub del {
1.133 albertel 7264: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7265: my $items='';
1.800 albertel 7266: foreach my $item (@$storearr) {
7267: $items.=&escape($item).'&';
1.191 harris41 7268: }
1.984 neumanie 7269:
1.27 www 7270: $items=~s/\&$//;
1.620 albertel 7271: if (!$udomain) { $udomain=$env{'user.domain'}; }
7272: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7273: my $uhome=&homeserver($uname,$udomain);
7274: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7275: }
7276:
7277: # -------------------------------------------------------------- dump interface
7278:
1.1172.2.22 raeburn 7279: sub unserialize {
7280: my ($rep, $escapedkeys) = @_;
7281:
7282: return {} if $rep =~ /^error/;
7283:
7284: my %returnhash=();
7285: foreach my $item (split(/\&/,$rep)) {
7286: my ($key, $value) = split(/=/, $item, 2);
7287: $key = unescape($key) unless $escapedkeys;
7288: next if $key =~ /^error: 2 /;
7289: $returnhash{$key} = &thaw_unescape($value);
7290: }
7291: return \%returnhash;
7292: }
7293:
7294: # see Lond::dump_with_regexp
7295: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7296: sub dump {
1.1172.2.146. .1(raebu 7297:22): my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7298: if (!$udomain) { $udomain=$env{'user.domain'}; }
7299: if (!$uname) { $uname=$env{'user.name'}; }
7300: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7301:
1.1172.2.55 raeburn 7302: if ($regexp) {
7303: $regexp=&escape($regexp);
7304: } else {
7305: $regexp='.';
7306: }
1.1172.2.22 raeburn 7307: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
7308: # user is hosted on this machine
1.1172.2.55 raeburn 7309: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 7310: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 7311: return %{&unserialize($reply, $escapedkeys)};
7312: }
1.1172.2.146. .1(raebu 7313:22): my $rep;
7314:22): if ($encrypt) {
7315:22): $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7316:22): } else {
7317:22): $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7318:22): }
1.755 albertel 7319: my @pairs=split(/\&/,$rep);
7320: my %returnhash=();
1.1098 foxr 7321: if (!($rep =~ /^error/ )) {
7322: foreach my $item (@pairs) {
7323: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 7324: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 7325: next if ($key =~ /^error: 2 /);
7326: $returnhash{$key}=&thaw_unescape($value);
7327: }
1.755 albertel 7328: }
7329: return %returnhash;
1.407 www 7330: }
7331:
1.1098 foxr 7332:
1.717 albertel 7333: # --------------------------------------------------------- dumpstore interface
7334:
7335: sub dumpstore {
7336: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 7337: # same as dump but keys must be escaped. They may contain colon separated
7338: # lists of values that may themself contain colons (e.g. symbs).
7339: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7340: }
7341:
1.407 www 7342: # -------------------------------------------------------------- keys interface
7343:
7344: sub getkeys {
7345: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7346: if (!$udomain) { $udomain=$env{'user.domain'}; }
7347: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7348: my $uhome=&homeserver($uname,$udomain);
7349: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7350: my @keyarray=();
1.800 albertel 7351: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7352: next if ($key =~ /^error: 2 /);
1.800 albertel 7353: push(@keyarray,&unescape($key));
1.407 www 7354: }
7355: return @keyarray;
1.318 matthew 7356: }
7357:
1.319 matthew 7358: # --------------------------------------------------------------- currentdump
7359: sub currentdump {
1.328 matthew 7360: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7361: $courseid = $env{'request.course.id'} if (! defined($courseid));
7362: $sdom = $env{'user.domain'} if (! defined($sdom));
7363: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7364: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 7365: my $rep;
7366:
7367: if (grep { $_ eq $uhome } current_machine_ids()) {
7368: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7369: $courseid)));
7370: } else {
7371: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7372: }
7373:
1.318 matthew 7374: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7375: #
1.318 matthew 7376: my %returnhash=();
1.319 matthew 7377: #
7378: if ($rep eq "unknown_cmd") {
7379: # an old lond will not know currentdump
7380: # Do a dump and make it look like a currentdump
1.822 albertel 7381: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7382: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7383: my %hash = @tmp;
7384: @tmp=();
1.424 matthew 7385: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7386: } else {
7387: my @pairs=split(/\&/,$rep);
1.800 albertel 7388: foreach my $pair (@pairs) {
7389: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7390: my ($symb,$param) = split(/:/,$key);
7391: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7392: &thaw_unescape($value);
1.319 matthew 7393: }
1.191 harris41 7394: }
1.12 www 7395: return %returnhash;
1.424 matthew 7396: }
7397:
7398: sub convert_dump_to_currentdump{
7399: my %hash = %{shift()};
7400: my %returnhash;
7401: # Code ripped from lond, essentially. The only difference
7402: # here is the unescaping done by lonnet::dump(). Conceivably
7403: # we might run in to problems with parameter names =~ /^v\./
7404: while (my ($key,$value) = each(%hash)) {
7405: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7406: $symb = &unescape($symb);
7407: $param = &unescape($param);
1.424 matthew 7408: next if ($v eq 'version' || $symb eq 'keys');
7409: next if (exists($returnhash{$symb}) &&
7410: exists($returnhash{$symb}->{$param}) &&
7411: $returnhash{$symb}->{'v.'.$param} > $v);
7412: $returnhash{$symb}->{$param}=$value;
7413: $returnhash{$symb}->{'v.'.$param}=$v;
7414: }
7415: #
7416: # Remove all of the keys in the hashes which keep track of
7417: # the version of the parameter.
7418: while (my ($symb,$param_hash) = each(%returnhash)) {
7419: # use a foreach because we are going to delete from the hash.
7420: foreach my $key (keys(%$param_hash)) {
7421: delete($param_hash->{$key}) if ($key =~ /^v\./);
7422: }
7423: }
7424: return \%returnhash;
1.12 www 7425: }
7426:
1.627 albertel 7427: # ------------------------------------------------------ critical inc interface
7428:
7429: sub cinc {
7430: return &inc(@_,'critical');
7431: }
7432:
1.449 matthew 7433: # --------------------------------------------------------------- inc interface
7434:
7435: sub inc {
1.627 albertel 7436: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7437: if (!$udomain) { $udomain=$env{'user.domain'}; }
7438: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7439: my $uhome=&homeserver($uname,$udomain);
7440: my $items='';
7441: if (! ref($store)) {
7442: # got a single value, so use that instead
7443: $items = &escape($store).'=&';
7444: } elsif (ref($store) eq 'SCALAR') {
7445: $items = &escape($$store).'=&';
7446: } elsif (ref($store) eq 'ARRAY') {
7447: $items = join('=&',map {&escape($_);} @{$store});
7448: } elsif (ref($store) eq 'HASH') {
7449: while (my($key,$value) = each(%{$store})) {
7450: $items.= &escape($key).'='.&escape($value).'&';
7451: }
7452: }
7453: $items=~s/\&$//;
1.627 albertel 7454: if ($critical) {
7455: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7456: } else {
7457: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7458: }
1.449 matthew 7459: }
7460:
1.12 www 7461: # --------------------------------------------------------------- put interface
7462:
7463: sub put {
1.1172.2.146. .1(raebu 7464:22): my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7465: if (!$udomain) { $udomain=$env{'user.domain'}; }
7466: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7467: my $uhome=&homeserver($uname,$udomain);
1.12 www 7468: my $items='';
1.800 albertel 7469: foreach my $item (keys(%$storehash)) {
7470: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7471: }
1.12 www 7472: $items=~s/\&$//;
1.1172.2.146. .1(raebu 7473:22): if ($encrypt) {
7474:22): return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7475:22): } else {
7476:22): return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7477:22): }
1.47 www 7478: }
7479:
1.631 albertel 7480: # ------------------------------------------------------------ newput interface
7481:
7482: sub newput {
7483: my ($namespace,$storehash,$udomain,$uname)=@_;
7484: if (!$udomain) { $udomain=$env{'user.domain'}; }
7485: if (!$uname) { $uname=$env{'user.name'}; }
7486: my $uhome=&homeserver($uname,$udomain);
7487: my $items='';
7488: foreach my $key (keys(%$storehash)) {
7489: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7490: }
7491: $items=~s/\&$//;
7492: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7493: }
7494:
7495: # --------------------------------------------------------- putstore interface
7496:
1.524 raeburn 7497: sub putstore {
1.1172.2.59 raeburn 7498: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7499: if (!$udomain) { $udomain=$env{'user.domain'}; }
7500: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7501: my $uhome=&homeserver($uname,$udomain);
7502: my $items='';
1.715 albertel 7503: foreach my $key (keys(%$storehash)) {
7504: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7505: }
1.715 albertel 7506: $items=~s/\&$//;
1.716 albertel 7507: my $esc_symb=&escape($symb);
7508: my $esc_v=&escape($version);
1.715 albertel 7509: my $reply =
1.716 albertel 7510: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7511: $uhome);
1.1172.2.59 raeburn 7512: if (($tolog) && ($reply eq 'ok')) {
7513: my $namevalue='';
7514: foreach my $key (keys(%{$storehash})) {
7515: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7516: }
1.1172.2.134 raeburn 7517: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7518: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7519: '&host='.&escape($perlvar{'lonHostID'}).
7520: '&version='.$esc_v.
7521: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7522: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7523: }
1.715 albertel 7524: if ($reply eq 'unknown_cmd') {
1.716 albertel 7525: # gfall back to way things use to be done
1.715 albertel 7526: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7527: $uname);
1.524 raeburn 7528: }
1.715 albertel 7529: return $reply;
7530: }
7531:
7532: sub old_putstore {
1.716 albertel 7533: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7534: if (!$udomain) { $udomain=$env{'user.domain'}; }
7535: if (!$uname) { $uname=$env{'user.name'}; }
7536: my $uhome=&homeserver($uname,$udomain);
7537: my %newstorehash;
1.800 albertel 7538: foreach my $item (keys(%$storehash)) {
7539: my $key = $version.':'.&escape($symb).':'.$item;
7540: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7541: }
7542: my $items='';
7543: my %allitems = ();
1.800 albertel 7544: foreach my $item (keys(%newstorehash)) {
7545: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7546: my $key = $1.':keys:'.$2;
7547: $allitems{$key} .= $3.':';
7548: }
1.800 albertel 7549: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7550: }
1.800 albertel 7551: foreach my $item (keys(%allitems)) {
7552: $allitems{$item} =~ s/\:$//;
7553: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7554: }
7555: $items=~s/\&$//;
7556: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7557: }
7558:
1.47 www 7559: # ------------------------------------------------------ critical put interface
7560:
7561: sub cput {
1.134 albertel 7562: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7563: if (!$udomain) { $udomain=$env{'user.domain'}; }
7564: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7565: my $uhome=&homeserver($uname,$udomain);
1.47 www 7566: my $items='';
1.800 albertel 7567: foreach my $item (keys(%$storehash)) {
7568: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7569: }
1.47 www 7570: $items=~s/\&$//;
1.134 albertel 7571: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7572: }
7573:
7574: # -------------------------------------------------------------- eget interface
7575:
7576: sub eget {
1.133 albertel 7577: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7578: my $items='';
1.800 albertel 7579: foreach my $item (@$storearr) {
7580: $items.=&escape($item).'&';
1.191 harris41 7581: }
1.12 www 7582: $items=~s/\&$//;
1.620 albertel 7583: if (!$udomain) { $udomain=$env{'user.domain'}; }
7584: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7585: my $uhome=&homeserver($uname,$udomain);
7586: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7587: my @pairs=split(/\&/,$rep);
7588: my %returnhash=();
1.42 www 7589: my $i=0;
1.800 albertel 7590: foreach my $item (@$storearr) {
7591: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7592: $i++;
1.191 harris41 7593: }
1.12 www 7594: return %returnhash;
7595: }
7596:
1.667 albertel 7597: # ------------------------------------------------------------ tmpput interface
7598: sub tmpput {
1.802 raeburn 7599: my ($storehash,$server,$context)=@_;
1.667 albertel 7600: my $items='';
1.800 albertel 7601: foreach my $item (keys(%$storehash)) {
7602: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7603: }
7604: $items=~s/\&$//;
1.802 raeburn 7605: if (defined($context)) {
7606: $items .= ':'.&escape($context);
7607: }
1.667 albertel 7608: return &reply("tmpput:$items",$server);
7609: }
7610:
7611: # ------------------------------------------------------------ tmpget interface
7612: sub tmpget {
1.688 albertel 7613: my ($token,$server)=@_;
7614: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7615: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7616: my %returnhash;
1.1172.2.85 raeburn 7617: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7618: return %returnhash;
7619: }
1.667 albertel 7620: foreach my $item (split(/\&/,$rep)) {
7621: my ($key,$value)=split(/=/,$item);
7622: $returnhash{&unescape($key)}=&thaw_unescape($value);
7623: }
7624: return %returnhash;
7625: }
7626:
1.1113 raeburn 7627: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7628: sub tmpdel {
7629: my ($token,$server)=@_;
7630: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7631: return &reply("tmpdel:$token",$server);
7632: }
7633:
1.1172.2.13 raeburn 7634: # ------------------------------------------------------------ get_timebased_id
7635:
7636: sub get_timebased_id {
7637: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7638: $maxtries) = @_;
7639: my ($newid,$error,$dellock);
7640: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7641: return ('','ok','invalid call to get suffix');
7642: }
7643:
7644: # set defaults for any optional args for which values were not supplied
7645: if ($who eq '') {
7646: $who = $env{'user.name'}.':'.$env{'user.domain'};
7647: }
7648: if (!$locktries) {
7649: $locktries = 3;
7650: }
7651: if (!$maxtries) {
7652: $maxtries = 10;
7653: }
7654:
7655: if (($cdom eq '') || ($cnum eq '')) {
7656: if ($env{'request.course.id'}) {
7657: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7658: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7659: }
7660: if (($cdom eq '') || ($cnum eq '')) {
7661: return ('','ok','call to get suffix not in course context');
7662: }
7663: }
7664:
7665: # construct locking item
7666: my $lockhash = {
7667: $prefix."\0".'locked_'.$keyid => $who,
7668: };
7669: my $tries = 0;
7670:
7671: # attempt to get lock on nohist_$namespace file
7672: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7673: while (($gotlock ne 'ok') && $tries <$locktries) {
7674: $tries ++;
7675: sleep 1;
7676: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7677: }
7678:
7679: # attempt to get unique identifier, based on current timestamp
7680: if ($gotlock eq 'ok') {
7681: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7682: my $id = time;
7683: $newid = $id;
1.1172.2.56 raeburn 7684: if ($idtype eq 'addcode') {
7685: $newid .= &sixnum_code();
7686: }
1.1172.2.13 raeburn 7687: my $idtries = 0;
7688: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7689: if ($idtype eq 'concat') {
7690: $newid = $id.$idtries;
1.1172.2.56 raeburn 7691: } elsif ($idtype eq 'addcode') {
7692: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7693: } else {
7694: $newid ++;
7695: }
7696: $idtries ++;
7697: }
7698: if (!exists($inuse{$prefix."\0".$newid})) {
7699: my %new_item = (
7700: $prefix."\0".$newid => $who,
7701: );
7702: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7703: $cdom,$cnum);
7704: if ($putresult ne 'ok') {
7705: undef($newid);
7706: $error = 'error saving new item: '.$putresult;
7707: }
7708: } else {
1.1172.2.56 raeburn 7709: undef($newid);
1.1172.2.13 raeburn 7710: $error = ('error: no unique suffix available for the new item ');
7711: }
7712: # remove lock
7713: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7714: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7715: } else {
7716: $error = "error: could not obtain lockfile\n";
7717: $dellock = 'ok';
1.1172.2.58 raeburn 7718: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7719: $dellock = 'nolock';
7720: }
1.1172.2.13 raeburn 7721: }
7722: return ($newid,$dellock,$error);
7723: }
7724:
1.1172.2.56 raeburn 7725: sub sixnum_code {
7726: my $code;
7727: for (0..6) {
7728: $code .= int( rand(9) );
7729: }
7730: return $code;
7731: }
7732:
1.765 albertel 7733: # -------------------------------------------------- portfolio access checking
7734:
7735: sub portfolio_access {
1.1172.2.77 raeburn 7736: my ($requrl,$clientip) = @_;
1.765 albertel 7737: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7738: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7739: if ($result) {
7740: my %setters;
7741: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7742: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7743: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7744: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7745: return 'B';
7746: }
7747: } else {
1.1172.2.142 raeburn 7748: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7749: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7750: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7751: return 'B';
7752: }
7753: }
7754: }
1.765 albertel 7755: if ($result eq 'ok') {
1.766 albertel 7756: return 'F';
1.765 albertel 7757: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7758: return 'A';
1.765 albertel 7759: }
1.766 albertel 7760: return '';
1.765 albertel 7761: }
7762:
7763: sub get_portfolio_access {
1.1172.2.77 raeburn 7764: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7765:
7766: if (!ref($access_hash)) {
7767: my $current_perms = &get_portfile_permissions($udom,$unum);
7768: my %access_controls = &get_access_controls($current_perms,$group,
7769: $file_name);
7770: $access_hash = $access_controls{$file_name};
7771: }
7772:
1.1172.2.77 raeburn 7773: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7774: my $now = time;
7775: if (ref($access_hash) eq 'HASH') {
7776: foreach my $key (keys(%{$access_hash})) {
7777: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7778: if ($start > $now) {
7779: next;
7780: }
7781: if ($end && $end<$now) {
7782: next;
7783: }
7784: if ($scope eq 'public') {
7785: $public = $key;
7786: last;
7787: } elsif ($scope eq 'guest') {
7788: $guest = $key;
7789: } elsif ($scope eq 'domains') {
7790: push(@domains,$key);
7791: } elsif ($scope eq 'users') {
7792: push(@users,$key);
7793: } elsif ($scope eq 'course') {
7794: push(@courses,$key);
7795: } elsif ($scope eq 'group') {
7796: push(@groups,$key);
1.1172.2.77 raeburn 7797: } elsif ($scope eq 'ip') {
7798: push(@ips,$key);
1.765 albertel 7799: }
7800: }
7801: if ($public) {
7802: return 'ok';
1.1172.2.77 raeburn 7803: } elsif (@ips > 0) {
7804: my $allowed;
7805: foreach my $ipkey (@ips) {
7806: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7807: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7808: $allowed = 1;
7809: last;
7810: }
7811: }
7812: }
7813: if ($allowed) {
7814: return 'ok';
7815: }
1.765 albertel 7816: }
7817: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7818: if ($guest) {
7819: return $guest;
7820: }
7821: } else {
7822: if (@domains > 0) {
7823: foreach my $domkey (@domains) {
7824: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7825: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7826: return 'ok';
7827: }
7828: }
7829: }
7830: }
7831: if (@users > 0) {
7832: foreach my $userkey (@users) {
1.865 raeburn 7833: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7834: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7835: if (ref($item) eq 'HASH') {
7836: if (($item->{'uname'} eq $env{'user.name'}) &&
7837: ($item->{'udom'} eq $env{'user.domain'})) {
7838: return 'ok';
7839: }
7840: }
7841: }
7842: }
1.765 albertel 7843: }
7844: }
7845: my %roleshash;
7846: my @courses_and_groups = @courses;
7847: push(@courses_and_groups,@groups);
7848: if (@courses_and_groups > 0) {
7849: my (%allgroups,%allroles);
7850: my ($start,$end,$role,$sec,$group);
7851: foreach my $envkey (%env) {
1.1060 raeburn 7852: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7853: my $cid = $2.'_'.$3;
7854: if ($1 eq 'gr') {
7855: $group = $4;
7856: $allgroups{$cid}{$group} = $env{$envkey};
7857: } else {
7858: if ($4 eq '') {
7859: $sec = 'none';
7860: } else {
7861: $sec = $4;
7862: }
7863: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7864: }
1.811 albertel 7865: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7866: my $cid = $2.'_'.$3;
7867: if ($4 eq '') {
7868: $sec = 'none';
7869: } else {
7870: $sec = $4;
7871: }
7872: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7873: }
7874: }
7875: if (keys(%allroles) == 0) {
7876: return;
7877: }
7878: foreach my $key (@courses_and_groups) {
7879: my %content = %{$$access_hash{$key}};
7880: my $cnum = $content{'number'};
7881: my $cdom = $content{'domain'};
7882: my $cid = $cdom.'_'.$cnum;
7883: if (!exists($allroles{$cid})) {
7884: next;
7885: }
7886: foreach my $role_id (keys(%{$content{'roles'}})) {
7887: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7888: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7889: my @status = @{$content{'roles'}{$role_id}{'access'}};
7890: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7891: foreach my $role (keys(%{$allroles{$cid}})) {
7892: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7893: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7894: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7895: if (grep/^all$/,@sections) {
7896: return 'ok';
7897: } else {
7898: if (grep/^$sec$/,@sections) {
7899: return 'ok';
7900: }
7901: }
7902: }
7903: }
7904: if (keys(%{$allgroups{$cid}}) == 0) {
7905: if (grep/^none$/,@groups) {
7906: return 'ok';
7907: }
7908: } else {
7909: if (grep/^all$/,@groups) {
7910: return 'ok';
7911: }
7912: foreach my $group (keys(%{$allgroups{$cid}})) {
7913: if (grep/^$group$/,@groups) {
7914: return 'ok';
7915: }
7916: }
7917: }
7918: }
7919: }
7920: }
7921: }
7922: }
7923: if ($guest) {
7924: return $guest;
7925: }
7926: }
7927: }
7928: return;
7929: }
7930:
7931: sub course_group_datechecker {
7932: my ($dates,$now,$status) = @_;
7933: my ($start,$end) = split(/\./,$dates);
7934: if (!$start && !$end) {
7935: return 'ok';
7936: }
7937: if (grep/^active$/,@{$status}) {
7938: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7939: return 'ok';
7940: }
7941: }
7942: if (grep/^previous$/,@{$status}) {
7943: if ($end > $now ) {
7944: return 'ok';
7945: }
7946: }
7947: if (grep/^future$/,@{$status}) {
7948: if ($start > $now) {
7949: return 'ok';
7950: }
7951: }
7952: return;
7953: }
7954:
7955: sub parse_portfolio_url {
7956: my ($url) = @_;
7957:
7958: my ($type,$udom,$unum,$group,$file_name);
7959:
1.823 albertel 7960: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7961: $type = 1;
7962: $udom = $1;
7963: $unum = $2;
7964: $file_name = $3;
1.823 albertel 7965: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7966: $type = 2;
7967: $udom = $1;
7968: $unum = $2;
7969: $group = $3;
7970: $file_name = $3.'/'.$4;
7971: }
7972: if (wantarray) {
7973: return ($type,$udom,$unum,$file_name,$group);
7974: }
7975: return $type;
7976: }
7977:
7978: sub is_portfolio_url {
7979: my ($url) = @_;
7980: return scalar(&parse_portfolio_url($url));
7981: }
7982:
1.798 raeburn 7983: sub is_portfolio_file {
7984: my ($file) = @_;
1.820 raeburn 7985: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7986: return 1;
7987: }
7988: return;
7989: }
7990:
1.1172.2.146. .13(raeb 7991:-23): sub is_coursetool_logo {
7992:-23): my ($uri) = @_;
7993:-23): if ($env{'request.course.id'}) {
7994:-23): my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
7995:-23): if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
7996:-23): return 1;
7997:-23): }
7998:-23): }
7999:-23): return;
8000:-23): }
8001:-23):
1.976 raeburn 8002: sub usertools_access {
1.1084 raeburn 8003: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8004: my ($access,%tools);
8005: if ($context eq '') {
8006: $context = 'tools';
8007: }
8008: if ($context eq 'requestcourses') {
8009: %tools = (
8010: official => 1,
8011: unofficial => 1,
1.1006 raeburn 8012: community => 1,
1.1172.2.37 raeburn 8013: textbook => 1,
1.1172.2.146. .13(raeb 8014:-23): lti => 1,
1.985 raeburn 8015: );
1.1172.2.9 raeburn 8016: } elsif ($context eq 'requestauthor') {
8017: %tools = (
8018: requestauthor => 1,
8019: );
1.1172.2.146. .18(raeb 8020:-24): } elsif ($context eq 'authordefaults') {
8021:-24): %tools = (
8022:-24): webdav => 1,
8023:-24): );
1.985 raeburn 8024: } else {
8025: %tools = (
8026: aboutme => 1,
8027: blog => 1,
8028: portfolio => 1,
1.1172.2.146. .6(raebu 8029:22): timezone => 1,
1.985 raeburn 8030: );
8031: }
1.976 raeburn 8032: return if (!defined($tools{$tool}));
8033:
1.1172.2.35 raeburn 8034: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8035: $udom = $env{'user.domain'};
8036: $uname = $env{'user.name'};
8037: }
8038:
1.978 raeburn 8039: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8040: if ($action ne 'reload') {
1.985 raeburn 8041: if ($context eq 'requestcourses') {
8042: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 8043: } elsif ($context eq 'requestauthor') {
8044: return $env{'environment.canrequest.author'};
1.1172.2.146. .18(raeb 8045:-24): } elsif ($context eq 'authordefaults') {
8046:-24): if ($tool eq 'webdav') {
8047:-24): return $env{'environment.availabletools.'.$tool};
8048:-24): }
1.985 raeburn 8049: } else {
8050: return $env{'environment.availabletools.'.$tool};
8051: }
8052: }
1.976 raeburn 8053: }
8054:
1.1172.2.9 raeburn 8055: my ($toolstatus,$inststatus,$envkey);
8056: if ($context eq 'requestauthor') {
8057: $envkey = $context;
1.1172.2.146. .18(raeb 8058:-24): } elsif ($context eq 'authordefaults') {
8059:-24): if ($tool eq 'webdav') {
8060:-24): $envkey = 'tools.'.$tool;
8061:-24): }
1.1172.2.9 raeburn 8062: } else {
8063: $envkey = $context.'.'.$tool;
8064: }
1.976 raeburn 8065:
1.985 raeburn 8066: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8067: ($action ne 'reload')) {
1.1172.2.9 raeburn 8068: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8069: $inststatus = $env{'environment.inststatus'};
8070: } else {
1.1084 raeburn 8071: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 8072: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8073: $inststatus = $userenvref->{'inststatus'};
8074: } else {
1.1172.2.9 raeburn 8075: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8076: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8077: $inststatus = $userenv{'inststatus'};
8078: }
1.976 raeburn 8079: }
8080:
8081: if ($toolstatus ne '') {
8082: if ($toolstatus) {
8083: $access = 1;
8084: } else {
8085: $access = 0;
8086: }
8087: return $access;
8088: }
8089:
1.1084 raeburn 8090: my ($is_adv,%domdef);
8091: if (ref($is_advref) eq 'HASH') {
8092: $is_adv = $is_advref->{'is_adv'};
8093: } else {
8094: $is_adv = &is_advanced_user($udom,$uname);
8095: }
8096: if (ref($domdefref) eq 'HASH') {
8097: %domdef = %{$domdefref};
8098: } else {
8099: %domdef = &get_domain_defaults($udom);
8100: }
1.976 raeburn 8101: if (ref($domdef{$tool}) eq 'HASH') {
8102: if ($is_adv) {
8103: if ($domdef{$tool}{'_LC_adv'} ne '') {
8104: if ($domdef{$tool}{'_LC_adv'}) {
8105: $access = 1;
8106: } else {
8107: $access = 0;
8108: }
8109: return $access;
8110: }
8111: }
8112: if ($inststatus ne '') {
8113: my ($hasaccess,$hasnoaccess);
8114: foreach my $affiliation (split(/:/,$inststatus)) {
8115: if ($domdef{$tool}{$affiliation} ne '') {
8116: if ($domdef{$tool}{$affiliation}) {
8117: $hasaccess = 1;
8118: } else {
8119: $hasnoaccess = 1;
8120: }
8121: }
8122: }
8123: if ($hasaccess || $hasnoaccess) {
8124: if ($hasaccess) {
8125: $access = 1;
8126: } elsif ($hasnoaccess) {
8127: $access = 0;
8128: }
8129: return $access;
8130: }
8131: } else {
8132: if ($domdef{$tool}{'default'} ne '') {
8133: if ($domdef{$tool}{'default'}) {
8134: $access = 1;
8135: } elsif ($domdef{$tool}{'default'} == 0) {
8136: $access = 0;
8137: }
8138: return $access;
8139: }
8140: }
8141: } else {
1.1172.2.6 raeburn 8142: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8143: $access = 1;
8144: } else {
8145: $access = 0;
8146: }
1.976 raeburn 8147: return $access;
8148: }
8149: }
8150:
1.1050 raeburn 8151: sub is_course_owner {
8152: my ($cdom,$cnum,$udom,$uname) = @_;
8153: if (($udom eq '') || ($uname eq '')) {
8154: $udom = $env{'user.domain'};
8155: $uname = $env{'user.name'};
8156: }
8157: unless (($udom eq '') || ($uname eq '')) {
8158: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8159: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8160: return 1;
8161: } else {
8162: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
8163: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8164: return 1;
8165: }
8166: }
8167: }
8168: }
8169: return;
8170: }
8171:
1.976 raeburn 8172: sub is_advanced_user {
8173: my ($udom,$uname) = @_;
1.1085 raeburn 8174: if ($udom ne '' && $uname ne '') {
8175: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8176: if (wantarray) {
8177: return ($env{'user.adv'},$env{'user.author'});
8178: } else {
8179: return $env{'user.adv'};
8180: }
1.1085 raeburn 8181: }
8182: }
1.976 raeburn 8183: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8184: my %allroles;
1.1128 raeburn 8185: my ($is_adv,$is_author);
1.976 raeburn 8186: foreach my $role (keys(%roleshash)) {
8187: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8188: my $area = '/'.$tdomain.'/'.$trest;
8189: if ($sec ne '') {
8190: $area .= '/'.$sec;
8191: }
8192: if (($area ne '') && ($trole ne '')) {
8193: my $spec=$trole.'.'.$area;
8194: if ($trole =~ /^cr\//) {
8195: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8196: } elsif ($trole ne 'gr') {
8197: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8198: }
1.1128 raeburn 8199: if ($trole eq 'au') {
8200: $is_author = 1;
8201: }
1.976 raeburn 8202: }
8203: }
8204: foreach my $role (keys(%allroles)) {
8205: last if ($is_adv);
8206: foreach my $item (split(/:/,$allroles{$role})) {
8207: if ($item ne '') {
8208: my ($privilege,$restrictions)=split(/&/,$item);
8209: if ($privilege eq 'adv') {
8210: $is_adv = 1;
8211: last;
8212: }
8213: }
8214: }
8215: }
1.1128 raeburn 8216: if (wantarray) {
8217: return ($is_adv,$is_author);
8218: }
1.976 raeburn 8219: return $is_adv;
8220: }
1.798 raeburn 8221:
1.1035 raeburn 8222: sub check_can_request {
1.1172.2.146. .13(raeb 8223:-23): my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8224: my $canreq = 0;
1.1172.2.146. .13(raeb 8225:-23): if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8226:-23): $uname = $env{'user.name'};
8227:-23): $udom = $env{'user.domain'};
8228:-23): }
1.1035 raeburn 8229: my ($types,$typename) = &Apache::loncommon::course_types();
8230: my @options = ('approval','validate','autolimit');
8231: my $optregex = join('|',@options);
8232: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8233: foreach my $type (@{$types}) {
1.1172.2.146. .13(raeb 8234:-23): if (&usertools_access($uname,$udom,$type,undef,
8235:-23): 'requestcourses')) {
1.1035 raeburn 8236: $canreq ++;
1.1036 raeburn 8237: if (ref($request_domains) eq 'HASH') {
1.1172.2.146. .13(raeb 8238:-23): push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8239: }
1.1172.2.146. .13(raeb 8240:-23): if ($dom eq $udom) {
1.1035 raeburn 8241: $can_request->{$type} = 1;
8242: }
8243: }
1.1172.2.146. .13(raeb 8244:-23): if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8245:-23): ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8246: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8247: if (@curr > 0) {
1.1036 raeburn 8248: foreach my $item (@curr) {
8249: if (ref($request_domains) eq 'HASH') {
8250: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8251: if ($otherdom ne '') {
8252: if (ref($request_domains->{$type}) eq 'ARRAY') {
8253: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8254: push(@{$request_domains->{$type}},$otherdom);
8255: }
8256: } else {
8257: push(@{$request_domains->{$type}},$otherdom);
8258: }
8259: }
8260: }
8261: }
1.1172.2.146. .13(raeb 8262:-23): unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8263: $canreq ++;
1.1035 raeburn 8264: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8265: $can_request->{$type} = 1;
8266: }
8267: }
8268: }
8269: }
8270: }
8271: }
8272: return $canreq;
8273: }
8274:
1.341 www 8275: # ---------------------------------------------- Custom access rule evaluation
8276:
8277: sub customaccess {
8278: my ($priv,$uri)=@_;
1.807 albertel 8279: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8280: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8281: $udom = &LONCAPA::clean_domain($udom);
8282: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8283: my $access=0;
1.800 albertel 8284: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8285: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8286: if ($type eq 'user') {
8287: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8288: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8289: if ($tdom) {
8290: if ($tdom ne $env{'user.domain'}) { next; }
8291: }
1.896 albertel 8292: if ($tuname) {
8293: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8294: }
8295: $access=($effect eq 'allow');
8296: last;
8297: }
8298: } else {
8299: if ($role) {
8300: if ($role ne $urole) { next; }
8301: }
8302: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8303: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8304: if ($tdom) {
8305: if ($tdom ne $udom) { next; }
8306: }
8307: if ($tcrs) {
8308: if ($tcrs ne $ucrs) { next; }
8309: }
8310: if ($tsec) {
8311: if ($tsec ne $usec) { next; }
8312: }
8313: $access=($effect eq 'allow');
8314: last;
8315: }
8316: if ($realm eq '' && $role eq '') {
8317: $access=($effect eq 'allow');
8318: }
1.402 bowersj2 8319: }
1.341 www 8320: }
8321: return $access;
8322: }
8323:
1.103 harris41 8324: # ------------------------------------------------- Check for a user privilege
1.12 www 8325:
8326: sub allowed {
1.1172.2.146. .1(raebu 8327:22): my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8328: my $ver_orguri=$uri;
1.439 www 8329: $uri=&deversion($uri);
1.152 www 8330: my $orguri=$uri;
1.52 www 8331: $uri=&declutter($uri);
1.809 raeburn 8332:
1.810 raeburn 8333: if ($priv eq 'evb') {
1.1172.2.146. .3(raebu 8334:22): # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8335: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8336: return $1;
8337: } else {
8338: return;
8339: }
8340: }
8341:
1.620 albertel 8342: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8343: # Free bre access to adm and meta resources
1.1172.2.146. .1(raebu 8344:22): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8345: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8346: && ($priv eq 'bre')) {
1.14 www 8347: return 'F';
1.159 www 8348: }
8349:
1.545 banghart 8350: # Free bre access to user's own portfolio contents
1.714 raeburn 8351: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8352: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8353: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8354: my %setters;
1.1172.2.142 raeburn 8355: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8356: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8357: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8358: return 'B';
8359: } else {
8360: return 'F';
8361: }
1.545 banghart 8362: }
8363:
1.762 raeburn 8364: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8365: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8366: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8367: if (exists($env{'request.course.id'})) {
8368: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8369: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8370: if (($domain eq $cdom) && ($name eq $cnum)) {
8371: my $courseprivid=$env{'request.course.id'};
8372: $courseprivid=~s/\_/\//;
8373: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8374: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8375: return $1;
1.762 raeburn 8376: } else {
8377: if ($env{'request.course.sec'}) {
8378: $courseprivid.='/'.$env{'request.course.sec'};
8379: }
8380: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8381: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8382: return $2;
8383: }
1.714 raeburn 8384: }
8385: }
8386: }
8387: }
8388:
1.159 www 8389: # Free bre to public access
8390:
8391: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8392:22): my $copyright;
8393:22): unless ($uri =~ /ext\.tool/) {
8394:22): $copyright=&metadata($uri,'copyright');
8395:22): }
1.620 albertel 8396: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8397: return 'F';
8398: }
1.238 www 8399: if ($copyright eq 'priv') {
8400: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8401: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8402: return '';
8403: }
8404: }
8405: if ($copyright eq 'domain') {
8406: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8407: unless (($env{'user.domain'} eq $1) ||
8408: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8409: return '';
8410: }
1.262 matthew 8411: }
1.620 albertel 8412: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8413: # Library role, so allow browsing of resources in this domain.
8414: return 'F';
1.238 www 8415: }
1.341 www 8416: if ($copyright eq 'custom') {
8417: unless (&customaccess($priv,$uri)) { return ''; }
8418: }
1.14 www 8419: }
1.264 matthew 8420: # Domain coordinator is trying to create a course
1.620 albertel 8421: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8422: # uri is the requested domain in this case.
8423: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8424: # a role of dc for the domain in question.
1.620 albertel 8425: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8426: }
1.29 www 8427:
1.52 www 8428: my $thisallowed='';
8429: my $statecond=0;
8430: my $courseprivid='';
8431:
1.1039 raeburn 8432: my $ownaccess;
1.1043 raeburn 8433: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8434: if (($priv eq 'bro') && ($env{'user.author'})) {
8435: if ($uri eq '') {
8436: $ownaccess = 1;
8437: } else {
8438: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8439: my $udom = $env{'user.domain'};
8440: my $uname = $env{'user.name'};
8441: if ($uri =~ m{^\Q$udom\E/?$}) {
8442: $ownaccess = 1;
1.1040 raeburn 8443: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8444: unless ($uri =~ m{\.\./}) {
8445: $ownaccess = 1;
8446: }
8447: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8448: my $now = time;
8449: if ($uri =~ m{^([^/]+)/?$}) {
8450: my $adom = $1;
8451: foreach my $key (keys(%env)) {
1.1042 raeburn 8452: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8453: my ($start,$end) = split(/\./,$env{$key});
8454: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8455: $ownaccess = 1;
8456: last;
8457: }
8458: }
8459: }
8460: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8461: my $adom = $1;
8462: my $aname = $2;
1.1042 raeburn 8463: foreach my $role ('ca','aa') {
8464: if ($env{"user.role.$role./$adom/$aname"}) {
8465: my ($start,$end) =
1.1172.2.142 raeburn 8466: split(/\./,$env{"user.role.$role./$adom/$aname"});
8467: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8468: $ownaccess = 1;
8469: last;
8470: }
1.1039 raeburn 8471: }
8472: }
8473: }
8474: }
8475: }
8476: }
8477: }
8478:
1.52 www 8479: # Course
8480:
1.620 albertel 8481: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8482: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8483: $thisallowed.=$1;
8484: }
1.52 www 8485: }
1.29 www 8486:
1.52 www 8487: # Domain
8488:
1.620 albertel 8489: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8490: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8491: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8492: $thisallowed.=$1;
8493: }
1.12 www 8494: }
1.52 www 8495:
1.1141 raeburn 8496: # User who is not author or co-author might still be able to edit
8497: # resource of an author in the domain (e.g., if Domain Coordinator).
8498: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8499: (&allowed('mdc',$env{'request.course.id'}))) {
8500: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8501: $thisallowed.=$1;
8502: }
8503: }
8504:
1.52 www 8505: # Course: uri itself is a course
1.66 www 8506: my $courseuri=$uri;
8507: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8508: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8509:
1.620 albertel 8510: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8511: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8512: if ($priv eq 'mip') {
8513: my $rem = $1;
8514: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8515: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8516: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8517: if ($cdom ne '') {
8518: my %passwdconf = &get_passwdconf($cdom);
8519: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8520: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8521: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8522: my @inststatuses = split(':',$env{'environment.inststatus'});
8523: unless (@inststatuses) {
8524: @inststatuses = ('default');
8525: }
8526: foreach my $status (@inststatuses) {
8527: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8528: $thisallowed.=$rem;
8529: }
8530: }
8531: }
8532: }
8533: }
8534: }
8535: }
8536: } else {
8537: unless (($priv eq 'bro') && (!$ownaccess)) {
8538: $thisallowed.=$1;
8539: }
1.1039 raeburn 8540: }
1.12 www 8541: }
1.29 www 8542:
1.665 albertel 8543: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8544: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8545: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8546: $thisallowed='';
1.671 raeburn 8547: my ($match)=&is_on_map($uri);
8548: if ($match) {
8549: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8550: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8551: my $value = $1;
1.1172.2.146. .1(raebu 8552:22): my $deeplinkblock;
8553:22): unless ($nodeeplinkcheck) {
8554:22): $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8555:22): }
8556:22): if ($deeplinkblock) {
8557:22): $thisallowed='D';
8558:22): } elsif ($noblockcheck) {
1.1172.2.65 raeburn 8559: $thisallowed.=$value;
1.1162 raeburn 8560: } else {
1.1172.2.126 raeburn 8561: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8562: if (@blockers > 0) {
8563: $thisallowed = 'B';
8564: } else {
8565: $thisallowed.=$value;
8566: }
1.1162 raeburn 8567: }
1.671 raeburn 8568: }
8569: } else {
1.705 albertel 8570: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8571: if ($refuri) {
8572: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8573: $thisallowed='F';
1.671 raeburn 8574: } else {
8575: $refuri=&declutter($refuri);
8576: my ($match) = &is_on_map($refuri);
8577: if ($match) {
1.1172.2.146. .1(raebu 8578:22): my $deeplinkblock;
8579:22): unless ($nodeeplinkcheck) {
8580:22): $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8581:22): }
8582:22): if ($deeplinkblock) {
8583:22): $thisallowed='D';
8584:22): } elsif ($noblockcheck) {
1.1162 raeburn 8585: $thisallowed='F';
1.1172.2.65 raeburn 8586: } else {
1.1172.2.127 raeburn 8587: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8588: if (@blockers > 0) {
8589: $thisallowed = 'B';
8590: } else {
8591: $thisallowed='F';
8592: }
1.1162 raeburn 8593: }
1.671 raeburn 8594: }
1.669 raeburn 8595: }
1.671 raeburn 8596: }
8597: }
1.314 www 8598: }
1.492 albertel 8599:
1.766 albertel 8600: if ($priv eq 'bre'
8601: && $thisallowed ne 'F'
8602: && $thisallowed ne '2'
8603: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8604: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8605: }
8606:
1.52 www 8607: # Full access at system, domain or course-wide level? Exit.
1.29 www 8608: if ($thisallowed=~/F/) {
8609: return 'F';
8610: }
8611:
1.52 www 8612: # If this is generating or modifying users, exit with special codes
1.29 www 8613:
1.643 www 8614: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8615: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8616: my ($audom,$auname)=split('/',$uri);
1.643 www 8617: # no author name given, so this just checks on the general right to make a co-author in this domain
8618: unless ($auname) { return $thisallowed; }
8619: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8620: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8621: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8622: ($audom ne $env{'request.role.domain'}))) { return ''; }
8623: }
1.52 www 8624: return $thisallowed;
8625: }
8626: #
1.103 harris41 8627: # Gathered so far: system, domain and course wide privileges
1.52 www 8628: #
8629: # Course: See if uri or referer is an individual resource that is part of
8630: # the course
8631:
1.620 albertel 8632: if ($env{'request.course.id'}) {
1.232 www 8633:
1.1172.2.146. .13(raeb 8634:-23): if ($priv eq 'bre') {
8635:-23): if (&is_coursetool_logo($uri)) {
8636:-23): return 'F';
8637:-23): }
8638:-23): }
8639:-23):
1.1172.2.115 raeburn 8640: # If this is modifying password (internal auth) domains must match for user and user's role.
8641:
8642: if ($priv eq 'mip') {
8643: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8644: return $thisallowed;
8645: } else {
8646: return '';
8647: }
8648: }
8649:
1.620 albertel 8650: $courseprivid=$env{'request.course.id'};
8651: if ($env{'request.course.sec'}) {
8652: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8653: }
8654: $courseprivid=~s/\_/\//;
8655: my $checkreferer=1;
1.232 www 8656: my ($match,$cond)=&is_on_map($uri);
8657: if ($match) {
8658: $statecond=$cond;
1.620 albertel 8659: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8660: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8661: my $value = $1;
8662: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8663:22): my $deeplinkblock;
8664:22): unless ($nodeeplinkcheck) {
8665:22): $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8666:22): }
8667:22): if ($deeplinkblock) {
8668:22): $thisallowed = 'D';
8669:22): } elsif ($noblockcheck) {
1.1162 raeburn 8670: $thisallowed.=$value;
1.1172.2.65 raeburn 8671: } else {
1.1172.2.126 raeburn 8672: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8673: if (@blockers > 0) {
8674: $thisallowed = 'B';
8675: } else {
8676: $thisallowed.=$value;
8677: }
1.1162 raeburn 8678: }
8679: } else {
8680: $thisallowed.=$value;
8681: }
1.52 www 8682: $checkreferer=0;
8683: }
1.29 www 8684: }
1.1172.2.126 raeburn 8685:
1.148 www 8686: if ($checkreferer) {
1.620 albertel 8687: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8688: unless ($refuri) {
1.800 albertel 8689: foreach my $key (keys(%env)) {
8690: if ($key=~/^httpref\..*\*/) {
8691: my $pattern=$key;
1.156 www 8692: $pattern=~s/^httpref\.\/res\///;
1.148 www 8693: $pattern=~s/\*/\[\^\/\]\+/g;
8694: $pattern=~s/\//\\\//g;
1.152 www 8695: if ($orguri=~/$pattern/) {
1.800 albertel 8696: $refuri=$env{$key};
1.148 www 8697: }
8698: }
1.191 harris41 8699: }
1.148 www 8700: }
1.232 www 8701:
1.148 www 8702: if ($refuri) {
1.152 www 8703: $refuri=&declutter($refuri);
1.232 www 8704: my ($match,$cond)=&is_on_map($refuri);
8705: if ($match) {
8706: my $refstatecond=$cond;
1.620 albertel 8707: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8708: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8709: my $value = $1;
8710: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8711:22): my $deeplinkblock;
8712:22): unless ($nodeeplinkcheck) {
8713:22): $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8714:22): }
8715:22): if ($deeplinkblock) {
8716:22): $thisallowed = 'D';
8717:22): } elsif ($noblockcheck) {
1.1162 raeburn 8718: $thisallowed.=$value;
1.1172.2.65 raeburn 8719: } else {
1.1172.2.127 raeburn 8720: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8721: if (@blockers > 0) {
8722: $thisallowed = 'B';
8723: } else {
8724: $thisallowed.=$value;
8725: }
1.1162 raeburn 8726: }
8727: } else {
8728: $thisallowed.=$value;
8729: }
1.53 www 8730: $uri=$refuri;
8731: $statecond=$refstatecond;
1.52 www 8732: }
8733: }
1.148 www 8734: }
1.29 www 8735: }
1.52 www 8736: }
1.29 www 8737:
1.52 www 8738: #
1.103 harris41 8739: # Gathered now: all privileges that could apply, and condition number
1.52 www 8740: #
8741: #
8742: # Full or no access?
8743: #
1.29 www 8744:
1.52 www 8745: if ($thisallowed=~/F/) {
8746: return 'F';
8747: }
1.29 www 8748:
1.52 www 8749: unless ($thisallowed) {
8750: return '';
8751: }
1.29 www 8752:
1.52 www 8753: # Restrictions exist, deal with them
8754: #
8755: # C:according to course preferences
8756: # R:according to resource settings
8757: # L:unless locked
8758: # X:according to user session state
8759: #
8760:
8761: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8762: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8763: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8764: # courses, and 2 minutes for current course, in which user has st or ta role
8765: # which is neither expired nor a future role (unless current course).
1.52 www 8766:
1.1172.2.142 raeburn 8767: my ($needlockcheck,$now,$crsonly);
1.52 www 8768: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8769: $now = time;
8770: if ($priv eq 'bre') {
8771: if ($uri ne '') {
8772: if ($orguri =~ m{^/+res/}) {
8773: if ($uri =~ m{^lib/templates/}) {
8774: if ($env{'request.course.id'}) {
8775: $crsonly = 1;
8776: $needlockcheck = 1;
8777: }
8778: } else {
8779: $needlockcheck = 1;
8780: }
8781: } elsif ($env{'request.course.id'}) {
8782: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8783: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8784: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8785: $crsonly = 1;
8786: }
8787: $needlockcheck = 1;
8788: }
8789: }
8790: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8791: $needlockcheck = 1;
8792: }
8793: }
8794: if ($needlockcheck) {
8795: foreach my $envkey (keys(%env)) {
1.54 www 8796: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8797: my $courseid=$2;
8798: my $roleid=$1.'.'.$2;
1.92 www 8799: $courseid=~s/^\///;
1.1172.2.142 raeburn 8800: unless ($env{'request.role'} eq $roleid) {
8801: my ($start,$end) = split(/\./,$env{$envkey});
8802: next unless (($now >= $start) && (!$end || $end > $now));
8803: }
1.54 www 8804: my $expiretime=600;
1.620 albertel 8805: if ($env{'request.role'} eq $roleid) {
1.54 www 8806: $expiretime=120;
8807: }
8808: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8809: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8810: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8811: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8812: }
1.620 albertel 8813: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8814: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8815: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8816: &log($env{'user.domain'},$env{'user.name'},
8817: $env{'user.home'},
1.57 www 8818: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8819: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8820: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8821: return '';
8822: }
8823: }
1.620 albertel 8824: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8825: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8826: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8827: &log($env{'user.domain'},$env{'user.name'},
8828: $env{'user.home'},
1.57 www 8829: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8830: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8831: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8832: return '';
8833: }
8834: }
8835: }
1.29 www 8836: }
1.52 www 8837: }
1.1172.2.126 raeburn 8838:
1.52 www 8839: #
8840: # Rest of the restrictions depend on selected course
8841: #
8842:
1.620 albertel 8843: unless ($env{'request.course.id'}) {
1.766 albertel 8844: if ($thisallowed eq 'A') {
8845: return 'A';
1.814 raeburn 8846: } elsif ($thisallowed eq 'B') {
8847: return 'B';
1.766 albertel 8848: } else {
8849: return '1';
8850: }
1.52 www 8851: }
1.29 www 8852:
1.52 www 8853: #
8854: # Now user is definitely in a course
8855: #
1.53 www 8856:
8857:
8858: # Course preferences
8859:
8860: if ($thisallowed=~/C/) {
1.620 albertel 8861: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8862: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8863: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8864: =~/\Q$rolecode\E/) {
1.1103 raeburn 8865: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8866: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8867: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8868: $env{'request.course.id'});
8869: }
1.237 www 8870: return '';
8871: }
8872:
1.620 albertel 8873: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8874: =~/\Q$unamedom\E/) {
1.1103 raeburn 8875: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8876: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8877: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8878: $env{'request.course.id'});
8879: }
1.54 www 8880: return '';
8881: }
1.53 www 8882: }
8883:
8884: # Resource preferences
8885:
8886: if ($thisallowed=~/R/) {
1.620 albertel 8887: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8888: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8889: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8890: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8891: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8892: }
8893: return '';
1.54 www 8894: }
1.53 www 8895: }
1.30 www 8896:
1.1172.2.146. .1(raebu 8897:22): # Restricted for deeplinked session?
8898:22):
8899:22): if ($env{'request.deeplink.login'}) {
8900:22): if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8901:22): if (!$symb) { $symb=&symbread($uri,1); }
8902:22): if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8903:22): return '';
8904:22): }
8905:22): }
8906:22): }
8907:22):
1.246 www 8908: # Restricted by state or randomout?
1.30 www 8909:
1.52 www 8910: if ($thisallowed=~/X/) {
1.620 albertel 8911: if ($env{'acc.randomout'}) {
1.579 albertel 8912: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8913: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8914: return '';
8915: }
1.247 www 8916: }
8917: if (&condval($statecond)) {
1.52 www 8918: return '2';
8919: } else {
8920: return '';
8921: }
8922: }
1.30 www 8923:
1.766 albertel 8924: if ($thisallowed eq 'A') {
8925: return 'A';
1.814 raeburn 8926: } elsif ($thisallowed eq 'B') {
8927: return 'B';
1.1172.2.146. .1(raebu 8928:22): } elsif ($thisallowed eq 'D') {
8929:22): return 'D';
1.766 albertel 8930: }
1.52 www 8931: return 'F';
1.232 www 8932: }
1.1162 raeburn 8933:
1.1172.2.13 raeburn 8934: # ------------------------------------------- Check construction space access
8935:
8936: sub constructaccess {
8937: my ($url,$setpriv)=@_;
8938:
8939: # We do not allow editing of previous versions of files
8940: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8941:
8942: # Get username and domain from URL
8943: my ($ownername,$ownerdomain,$ownerhome);
8944:
8945: ($ownerdomain,$ownername) =
1.1172.2.146. .19(raeb 8946:-24): ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8947:
8948: # The URL does not really point to any authorspace, forget it
8949: unless (($ownername) && ($ownerdomain)) { return ''; }
8950:
8951: # Now we need to see if the user has access to the authorspace of
8952: # $ownername at $ownerdomain
8953:
8954: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8955: # Real author for this?
8956: $ownerhome = $env{'user.home'};
8957: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8958: return ($ownername,$ownerdomain,$ownerhome);
8959: }
8960: } else {
8961: # Co-author for this?
8962: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8963: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8964: $ownerhome = &homeserver($ownername,$ownerdomain);
8965: return ($ownername,$ownerdomain,$ownerhome);
8966: }
8967: }
8968:
8969: # We don't have any access right now. If we are not possibly going to do anything about this,
8970: # we might as well leave
8971: unless ($setpriv) { return ''; }
8972:
8973: # Backdoor access?
8974: my $allowed=&allowed('eco',$ownerdomain);
8975: # Nope
8976: unless ($allowed) { return ''; }
8977: # Looks like we may have access, but could be locked by the owner of the construction space
8978: if ($allowed eq 'U') {
8979: my %blocked=&get('environment',['domcoord.author'],
8980: $ownerdomain,$ownername);
8981: # Is blocked by owner
8982: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8983: }
8984: if (($allowed eq 'F') || ($allowed eq 'U')) {
8985: # Grant temporary access
8986: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8987: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8988: if (!$update) { $update = $then; }
8989: my $refresh=$env{'user.refresh.time'};
8990: if (!$refresh) { $refresh = $update; }
8991: my $now = time;
8992: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8993: $now,'ca','constructaccess');
8994: $ownerhome = &homeserver($ownername,$ownerdomain);
8995: return($ownername,$ownerdomain,$ownerhome);
8996: }
8997: # No business here
8998: return '';
8999: }
9000:
1.1172.2.66 raeburn 9001: # ----------------------------------------------------------- Content Blocking
9002:
9003: {
9004: # Caches for faster Course Contents display where content blocking
9005: # is in operation (i.e., interval param set) for timed quiz.
9006: #
9007: # User for whom data are being temporarily cached.
9008: my $cacheduser='';
1.1172.2.126 raeburn 9009: # Course for which data are being temporarily cached.
9010: my $cachedcid='';
1.1172.2.66 raeburn 9011: # Cached blockers for this user (a hash of blocking items).
9012: my %cachedblockers=();
9013: # When the data were last cached.
9014: my $cachedlast='';
9015:
9016: sub load_all_blockers {
1.1172.2.128 raeburn 9017: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 9018: if (($uname ne '') && ($udom ne '')) {
9019: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 9020: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 9021: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 9022: return;
9023: }
9024: }
9025: $cachedlast=time;
9026: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 9027: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 9028: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 9029: return;
1.1172.2.66 raeburn 9030: }
9031:
1.1162 raeburn 9032: sub get_comm_blocks {
9033: my ($cdom,$cnum) = @_;
9034: if ($cdom eq '' || $cnum eq '') {
9035: return unless ($env{'request.course.id'});
9036: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9037: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9038: }
9039: my %commblocks;
9040: my $hashid=$cdom.'_'.$cnum;
9041: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9042: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9043: %commblocks = %{$blocksref};
9044: } else {
9045: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
9046: my $cachetime = 600;
9047: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9048: }
9049: return %commblocks;
9050: }
9051:
1.1172.2.66 raeburn 9052: sub get_commblock_resources {
9053: my ($blocks) = @_;
9054: my %blockers = ();
9055: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 9056: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9057: if ($env{'request.course.sec'}) {
9058: $courseurl .= '/'.$env{'request.course.sec'};
9059: }
9060: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9061: my %commblocks;
9062: if (ref($blocks) eq 'HASH') {
9063: %commblocks = %{$blocks};
9064: } else {
9065: %commblocks = &get_comm_blocks();
9066: }
1.1172.2.66 raeburn 9067: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 9068: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 9069: return %blockers unless (ref($navmap));
9070: my $now = time;
1.1162 raeburn 9071: foreach my $block (keys(%commblocks)) {
9072: if ($block =~ /^(\d+)____(\d+)$/) {
9073: my ($start,$end) = ($1,$2);
9074: if ($start <= $now && $end >= $now) {
9075: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9076: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9077: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 9078: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9079: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9080: }
9081: }
9082: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 9083: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9084: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9085: }
9086: }
9087: }
9088: }
9089: }
9090: } elsif ($block =~ /^firstaccess____(.+)$/) {
9091: my $item = $1;
9092: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9093: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 9094: my (@interval,$mapname);
1.1172.2.66 raeburn 9095: my $type = 'map';
9096: if ($item eq 'course') {
9097: $type = 'course';
9098: @interval=&EXT("resource.0.interval");
9099: } else {
9100: if ($item =~ /___\d+___/) {
9101: $type = 'resource';
9102: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9103: } else {
1.1172.2.142 raeburn 9104: $mapname = &deversion($item);
9105: if (ref($navmap)) {
9106: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9107: @interval = ($timelimit,'map');
1.1162 raeburn 9108: }
9109: }
1.1172.2.66 raeburn 9110: }
1.1172.2.146. .1(raebu 9111:22): if ($interval[0] =~ /^(\d+)/) {
9112:22): my $timelimit = $1;
1.1172.2.66 raeburn 9113: my $first_access;
9114: if ($type eq 'resource') {
9115: $first_access=&get_first_access($interval[1],$item);
9116: } elsif ($type eq 'map') {
9117: $first_access=&get_first_access($interval[1],undef,$item);
9118: } else {
9119: $first_access=&get_first_access($interval[1]);
9120: }
9121: if ($first_access) {
1.1172.2.146. .1(raebu 9122:22): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 9123: if ($timesup > $now) {
9124: my $activeblock;
1.1172.2.142 raeburn 9125: if ($type eq 'resource') {
9126: if (ref($navmap)) {
9127: my $res = $navmap->getBySymb($item);
9128: if ($res->answerable()) {
9129: $activeblock = 1;
9130: }
9131: }
9132: } elsif ($type eq 'map') {
9133: my $mapsymb = &symbread($mapname,1);
9134: if (($mapsymb) && (ref($navmap))) {
9135: my $mapres = $navmap->getBySymb($mapsymb);
9136: if (ref($mapres)) {
9137: my $first = $mapres->map_start();
9138: my $finish = $mapres->map_finish();
9139: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9140: if (ref($it)) {
9141: my $res;
9142: while ($res = $it->next(undef,1)) {
9143: next unless (ref($res));
9144: my $symb = $res->symb();
9145: next if (($symb eq $mapsymb) || ($symb eq ''));
9146: @interval=&EXT("resource.0.interval",$symb);
9147: if ($interval[1] eq 'map') {
9148: if ($res->answerable()) {
9149: $activeblock = 1;
9150: last;
9151: }
9152: }
9153: }
9154: }
9155: }
1.1172.2.66 raeburn 9156: }
9157: }
9158: if ($activeblock) {
9159: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9160: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9161: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9162: }
9163: }
9164: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9165: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9166: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9167: }
1.1162 raeburn 9168: }
9169: }
9170: }
9171: }
9172: }
9173: }
9174: }
9175: }
9176: }
1.1172.2.66 raeburn 9177: return %blockers;
1.1162 raeburn 9178: }
9179:
1.1172.2.66 raeburn 9180: sub has_comm_blocking {
1.1172.2.128 raeburn 9181: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 9182: my @blockers;
9183: return unless ($env{'request.course.id'});
9184: return unless ($priv eq 'bre');
9185: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 9186: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9187: if ($env{'request.course.sec'}) {
9188: $courseurl .= '/'.$env{'request.course.sec'};
9189: }
9190: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 9191: my %blockinfo;
9192: if (ref($blocks) eq 'HASH') {
9193: %blockinfo = &get_commblock_resources($blocks);
9194: } else {
9195: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9196: %blockinfo = %cachedblockers;
9197: }
9198: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 9199: my (%possibles,@symbs);
9200: if (!$symb) {
1.1172.2.128 raeburn 9201: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9202: }
1.1172.2.66 raeburn 9203: if ($symb) {
9204: @symbs = ($symb);
9205: } elsif (keys(%possibles)) {
9206: @symbs = keys(%possibles);
9207: }
9208: my $noblock;
9209: foreach my $symb (@symbs) {
9210: last if ($noblock);
9211: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 9212: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 9213: if ($block =~ /^firstaccess____(.+)$/) {
9214: my $item = $1;
1.1172.2.126 raeburn 9215: unless ($blocked) {
9216: if (($item eq $map) || ($item eq $symb)) {
9217: $noblock = 1;
9218: last;
9219: }
1.1172.2.66 raeburn 9220: }
1.1162 raeburn 9221: }
1.1172.2.128 raeburn 9222: if (ref($blockinfo{$block}) eq 'HASH') {
9223: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9224: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 9225: unless (grep(/^\Q$block\E$/,@blockers)) {
9226: push(@blockers,$block);
9227: }
9228: }
9229: }
1.1172.2.128 raeburn 9230: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9231: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 9232: unless (grep(/^\Q$block\E$/,@blockers)) {
9233: push(@blockers,$block);
9234: }
1.1172.2.66 raeburn 9235: }
9236: }
1.1162 raeburn 9237: }
9238: }
9239: }
1.1172.2.126 raeburn 9240: unless ($noblock) {
9241: return @blockers;
9242: }
9243: return;
1.1172.2.66 raeburn 9244: }
1.1162 raeburn 9245: }
9246:
1.1172.2.146. .1(raebu 9247:22): sub deeplink_check {
9248:22): my ($priv,$symb,$uri) = @_;
9249:22): return unless ($env{'request.course.id'});
9250:22): return unless ($priv eq 'bre');
9251:22): return if ($env{'request.state'} eq 'construct');
9252:22): return if ($env{'request.role.adv'});
9253:22): my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9254:22): my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9255:22): my (%possibles,@symbs);
9256:22): if (!$symb) {
9257:22): $symb = &symbread($uri,1,1,1,\%possibles);
9258:22): }
9259:22): if ($symb) {
9260:22): @symbs = ($symb);
9261:22): } elsif (keys(%possibles)) {
9262:22): @symbs = keys(%possibles);
9263:22): }
9264:22):
9265:22): my ($deeplink_symb,$allow);
9266:22): if ($env{'request.deeplink.login'}) {
9267:22): $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
9268:22): }
9269:22): foreach my $symb (@symbs) {
9270:22): last if ($allow);
9271:22): my $deeplink = &EXT("resource.0.deeplink",$symb);
9272:22): if ($deeplink eq '') {
9273:22): $allow = 1;
9274:22): } else {
9275:22): my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9276:22): if ($state ne 'only') {
9277:22): $allow = 1;
9278:22): } else {
9279:22): my $check_deeplink_entry;
9280:22): if ($protect ne 'none') {
9281:22): my ($acctype,$item) = split(/:/,$protect);
9282:22): if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9283:22): if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9284:22): $check_deeplink_entry = 1
9285:22): }
9286:22): } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9287:22): if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9288:22): $check_deeplink_entry = 1;
9289:22): }
9290:22): } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9291:22): if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9292:22): $check_deeplink_entry = 1;
9293:22): }
9294:22): }
9295:22): }
9296:22): if (($protect eq 'none') || ($check_deeplink_entry)) {
9297:22): if ($scope eq 'res') {
9298:22): if ($symb eq $deeplink_symb) {
9299:22): $allow = 1;
9300:22): }
9301:22): } elsif (($scope eq 'map') || ($scope eq 'rec')) {
9302:22): my ($map_from_symb,$map_from_login);
9303:22): $map_from_symb = &deversion((&decode_symb($symb))[0]);
9304:22): if ($deeplink_symb =~ /\.(page|sequence)$/) {
9305:22): $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9306:22): } else {
9307:22): $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9308:22): }
9309:22): if (($map_from_symb) && ($map_from_login)) {
9310:22): if ($map_from_symb eq $map_from_login) {
9311:22): $allow = 1;
9312:22): } elsif ($scope eq 'rec') {
9313:22): my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9314:22): if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9315:22): $allow = 1;
9316:22): }
9317:22): }
9318:22): }
9319:22): }
9320:22): }
9321:22): }
9322:22): }
9323:22): }
9324:22): return if ($allow);
9325:22): return 1;
9326:22): }
9327:22):
1.1172.2.66 raeburn 9328: # -------------------------------- Deversion and split uri into path an filename
9329:
1.1133 foxr 9330: #
1.1172.2.66 raeburn 9331: # Removes the version from a URI and
1.1133 foxr 9332: # splits it in to its filename and path to the filename.
9333: # Seems like File::Basename could have done this more clearly.
9334: # Parameters:
9335: # $uri - input URI
9336: # Returns:
9337: # Two element list consisting of
9338: # $pathname - the URI up to and excluding the trailing /
9339: # $filename - The part of the URI following the last /
9340: # NOTE:
9341: # Another realization of this is simply:
9342: # use File::Basename;
9343: # ...
9344: # $uri = shift;
9345: # $filename = basename($uri);
9346: # $path = dirname($uri);
9347: # return ($filename, $path);
9348: #
9349: # The implementation below is probably faster however.
9350: #
1.710 albertel 9351: sub split_uri_for_cond {
9352: my $uri=&deversion(&declutter(shift));
9353: my @uriparts=split(/\//,$uri);
9354: my $filename=pop(@uriparts);
9355: my $pathname=join('/',@uriparts);
9356: return ($pathname,$filename);
9357: }
1.232 www 9358: # --------------------------------------------------- Is a resource on the map?
9359:
9360: sub is_on_map {
1.710 albertel 9361: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9362: #Trying to find the conditional for the file
1.620 albertel 9363: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9364: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9365: if ($match) {
1.289 bowersj2 9366: return (1,$1);
9367: } else {
1.434 www 9368: return (0,0);
1.289 bowersj2 9369: }
1.12 www 9370: }
9371:
1.427 www 9372: # --------------------------------------------------------- Get symb from alias
9373:
9374: sub get_symb_from_alias {
9375: my $symb=shift;
9376: my ($map,$resid,$url)=&decode_symb($symb);
9377: # Already is a symb
9378: if ($url) { return $symb; }
9379: # Must be an alias
9380: my $aliassymb='';
9381: my %bighash;
1.620 albertel 9382: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9383: &GDBM_READER(),0640)) {
9384: my $rid=$bighash{'mapalias_'.$symb};
9385: if ($rid) {
9386: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9387: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9388: $resid,$bighash{'src_'.$rid});
1.427 www 9389: }
9390: untie %bighash;
9391: }
9392: return $aliassymb;
9393: }
9394:
1.12 www 9395: # ----------------------------------------------------------------- Define Role
9396:
9397: sub definerole {
9398: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 9399: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9400: foreach my $role (split(':',$sysrole)) {
9401: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9402: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9403: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9404: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9405: return "refused:s:$crole&$cqual";
9406: }
9407: }
1.191 harris41 9408: }
1.800 albertel 9409: foreach my $role (split(':',$domrole)) {
9410: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9411: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9412: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9413: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9414: return "refused:d:$crole&$cqual";
9415: }
9416: }
1.191 harris41 9417: }
1.800 albertel 9418: foreach my $role (split(':',$courole)) {
9419: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9420: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9421: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9422: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9423: return "refused:c:$crole&$cqual";
9424: }
9425: }
1.191 harris41 9426: }
1.1172.2.84 raeburn 9427: my $uhome;
9428: if (($uname ne '') && ($udom ne '')) {
9429: $uhome = &homeserver($uname,$udom);
9430: return $uhome if ($uhome eq 'no_host');
9431: } else {
9432: $uname = $env{'user.name'};
9433: $udom = $env{'user.domain'};
9434: $uhome = $env{'user.home'};
9435: }
1.620 albertel 9436: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 9437: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9438: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 9439: return reply($command,$uhome);
1.12 www 9440: } else {
9441: return 'refused';
9442: }
1.105 harris41 9443: }
9444:
9445: # ---------------- Make a metadata query against the network of library servers
9446:
9447: sub metadata_query {
1.1172.2.33 raeburn 9448: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9449: my %rhash;
1.845 albertel 9450: my %libserv = &all_library();
1.244 matthew 9451: my @server_list = (defined($server_array) ? @$server_array
9452: : keys(%libserv) );
9453: for my $server (@server_list) {
1.1172.2.33 raeburn 9454: my $domains = '';
9455: if (ref($domains_hash) eq 'HASH') {
9456: $domains = $domains_hash->{$server};
9457: }
1.118 harris41 9458: unless ($custom or $customshow) {
1.1172.2.33 raeburn 9459: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9460: $rhash{$server}=$reply;
9461: }
9462: else {
9463: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 9464: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9465: $server);
9466: $rhash{$server}=$reply;
9467: }
1.112 harris41 9468: }
1.118 harris41 9469: return \%rhash;
1.240 www 9470: }
9471:
9472: # ----------------------------------------- Send log queries and wait for reply
9473:
9474: sub log_query {
9475: my ($uname,$udom,$query,%filters)=@_;
9476: my $uhome=&homeserver($uname,$udom);
9477: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9478: my $uhost=&hostname($uhome);
1.800 albertel 9479: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9480: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9481: $uhome);
1.479 albertel 9482: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9483: return get_query_reply($queryid);
9484: }
9485:
1.818 raeburn 9486: # -------------------------- Update MySQL table for portfolio file
9487:
9488: sub update_portfolio_table {
1.821 raeburn 9489: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9490: if ($group ne '') {
9491: $file_name =~s /^\Q$group\E//;
9492: }
1.818 raeburn 9493: my $homeserver = &homeserver($uname,$udom);
9494: my $queryid=
1.821 raeburn 9495: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9496: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9497: my $reply = &get_query_reply($queryid);
9498: return $reply;
9499: }
9500:
1.899 raeburn 9501: # -------------------------- Update MySQL allusers table
9502:
9503: sub update_allusers_table {
9504: my ($uname,$udom,$names) = @_;
9505: my $homeserver = &homeserver($uname,$udom);
9506: my $queryid=
9507: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9508: 'lastname='.&escape($names->{'lastname'}).'%%'.
9509: 'firstname='.&escape($names->{'firstname'}).'%%'.
9510: 'middlename='.&escape($names->{'middlename'}).'%%'.
9511: 'generation='.&escape($names->{'generation'}).'%%'.
9512: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9513: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9514: return;
1.899 raeburn 9515: }
9516:
1.508 raeburn 9517: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9518:
9519: sub fetch_enrollment_query {
1.511 raeburn 9520: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 9521: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9522: my $maxtries = 1;
1.508 raeburn 9523: if ($context eq 'automated') {
9524: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 9525: $sleep = 2;
9526: $loopmax = 100;
1.547 raeburn 9527: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9528: } else {
9529: $homeserver = &homeserver($cnum,$dom);
9530: }
1.838 albertel 9531: my $host=&hostname($homeserver);
1.506 raeburn 9532: my $cmd = '';
1.1000 raeburn 9533: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9534: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9535: }
9536: $cmd =~ s/%%$//;
9537: $cmd = &escape($cmd);
9538: my $query = 'fetchenrollment';
1.620 albertel 9539: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9540: unless ($queryid=~/^\Q$host\E\_/) {
9541: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9542: return 'error: '.$queryid;
9543: }
1.1172.2.93 raeburn 9544: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9545: my $tries = 1;
9546: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 9547: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9548: $tries ++;
9549: }
1.526 raeburn 9550: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9551: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9552: } else {
1.901 albertel 9553: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9554: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9555: foreach my $line (@responses) {
9556: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9557: $$replyref{$key} = $value;
9558: }
9559: } else {
1.1117 foxr 9560: my $pathname = LONCAPA::tempdir();
1.800 albertel 9561: foreach my $line (@responses) {
9562: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9563: $$replyref{$key} = $value;
9564: if ($value > 0) {
1.800 albertel 9565: foreach my $item (@{$$affiliatesref{$key}}) {
9566: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9567: my $destname = $pathname.'/'.$filename;
9568: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9569: if ($xml_classlist =~ /^error/) {
9570: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9571: } else {
1.1172.2.96 raeburn 9572: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9573: print FILE &unescape($xml_classlist);
9574: close(FILE);
1.526 raeburn 9575: } else {
9576: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9577: }
9578: }
9579: }
9580: }
9581: }
9582: }
9583: return 'ok';
9584: }
9585: return 'error';
9586: }
9587:
1.242 www 9588: sub get_query_reply {
1.1172.2.79 raeburn 9589: my ($queryid,$sleep,$loopmax) = @_;
9590: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9591: $sleep = 0.2;
9592: }
9593: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9594: $loopmax = 100;
9595: }
1.1117 foxr 9596: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9597: my $reply='';
1.1172.2.79 raeburn 9598: for (1..$loopmax) {
9599: sleep($sleep);
1.240 www 9600: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9601: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9602: $reply = join('',<$fh>);
9603: close($fh);
1.240 www 9604: } else { return 'error: reply_file_error'; }
1.242 www 9605: return &unescape($reply);
9606: }
1.240 www 9607: }
1.242 www 9608: return 'timeout:'.$queryid;
1.240 www 9609: }
9610:
9611: sub courselog_query {
1.241 www 9612: #
9613: # possible filters:
9614: # url: url or symb
9615: # username
9616: # domain
9617: # action: view, submit, grade
9618: # start: timestamp
9619: # end: timestamp
9620: #
1.240 www 9621: my (%filters)=@_;
1.620 albertel 9622: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9623: if ($filters{'url'}) {
9624: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9625: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9626: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9627: }
1.620 albertel 9628: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9629: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9630: return &log_query($cname,$cdom,'courselog',%filters);
9631: }
9632:
9633: sub userlog_query {
1.858 raeburn 9634: #
9635: # possible filters:
9636: # action: log check role
9637: # start: timestamp
9638: # end: timestamp
9639: #
1.240 www 9640: my ($uname,$udom,%filters)=@_;
9641: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9642: }
9643:
1.506 raeburn 9644: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9645:
9646: sub auto_run {
1.508 raeburn 9647: my ($cnum,$cdom) = @_;
1.876 raeburn 9648: my $response = 0;
9649: my $settings;
9650: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9651: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9652: $settings = $domconfig{'autoenroll'};
9653: if ($settings->{'run'} eq '1') {
9654: $response = 1;
9655: }
9656: } else {
1.934 raeburn 9657: my $homeserver;
9658: if (&is_course($cdom,$cnum)) {
9659: $homeserver = &homeserver($cnum,$cdom);
9660: } else {
9661: $homeserver = &domain($cdom,'primary');
9662: }
9663: if ($homeserver ne 'no_host') {
9664: $response = &reply('autorun:'.$cdom,$homeserver);
9665: }
1.876 raeburn 9666: }
1.506 raeburn 9667: return $response;
9668: }
1.776 albertel 9669:
1.506 raeburn 9670: sub auto_get_sections {
1.508 raeburn 9671: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9672: my $homeserver;
9673: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9674: $homeserver = &homeserver($cnum,$cdom);
9675: }
9676: if (!defined($homeserver)) {
9677: if ($cdom =~ /^$match_domain$/) {
9678: $homeserver = &domain($cdom,'primary');
9679: }
9680: }
9681: my @secs;
9682: if (defined($homeserver)) {
9683: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9684: unless ($response eq 'refused') {
9685: @secs = split(/:/,$response);
9686: }
1.506 raeburn 9687: }
9688: return @secs;
9689: }
1.776 albertel 9690:
1.506 raeburn 9691: sub auto_new_course {
1.1099 raeburn 9692: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9693: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9694: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9695: return $response;
9696: }
1.776 albertel 9697:
1.506 raeburn 9698: sub auto_validate_courseID {
1.508 raeburn 9699: my ($cnum,$cdom,$inst_course_id) = @_;
9700: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9701: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9702: return $response;
9703: }
1.776 albertel 9704:
1.1007 raeburn 9705: sub auto_validate_instcode {
1.1020 raeburn 9706: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9707: my ($homeserver,$response);
9708: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9709: $homeserver = &homeserver($cnum,$cdom);
9710: }
9711: if (!defined($homeserver)) {
9712: if ($cdom =~ /^$match_domain$/) {
9713: $homeserver = &domain($cdom,'primary');
9714: }
9715: }
1.1065 raeburn 9716: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9717: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9718: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9719: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9720: }
9721:
1.1172.2.141 raeburn 9722: sub auto_validate_inst_crosslist {
9723: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9724: my ($homeserver,$response);
9725: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9726: $homeserver = &homeserver($cnum,$cdom);
9727: }
9728: if (!defined($homeserver)) {
9729: if ($cdom =~ /^$match_domain$/) {
9730: $homeserver = &domain($cdom,'primary');
9731: }
9732: }
9733: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9734: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9735: &escape($instcode).':'.&escape($inst_xlist).':'.
9736: &escape($coowner),$homeserver);
9737: }
9738: return $response;
9739: }
9740:
1.506 raeburn 9741: sub auto_create_password {
1.873 raeburn 9742: my ($cnum,$cdom,$authparam,$udom) = @_;
9743: my ($homeserver,$response);
1.506 raeburn 9744: my $create_passwd = 0;
9745: my $authchk = '';
1.873 raeburn 9746: if ($udom =~ /^$match_domain$/) {
9747: $homeserver = &domain($udom,'primary');
9748: }
9749: if ($homeserver eq '') {
9750: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9751: $homeserver = &homeserver($cnum,$cdom);
9752: }
9753: }
9754: if ($homeserver eq '') {
9755: $authchk = 'nodomain';
1.506 raeburn 9756: } else {
1.873 raeburn 9757: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9758: if ($response eq 'refused') {
9759: $authchk = 'refused';
9760: } else {
1.901 albertel 9761: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9762: }
1.506 raeburn 9763: }
9764: return ($authparam,$create_passwd,$authchk);
9765: }
9766:
1.706 raeburn 9767: sub auto_photo_permission {
9768: my ($cnum,$cdom,$students) = @_;
9769: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9770: my ($outcome,$perm_reqd,$conditions) =
9771: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9772: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9773: return (undef,undef);
9774: }
1.706 raeburn 9775: return ($outcome,$perm_reqd,$conditions);
9776: }
9777:
9778: sub auto_checkphotos {
9779: my ($uname,$udom,$pid) = @_;
9780: my $homeserver = &homeserver($uname,$udom);
9781: my ($result,$resulttype);
9782: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9783: &escape($uname).':'.&escape($pid),
9784: $homeserver));
1.709 albertel 9785: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9786: return (undef,undef);
9787: }
1.706 raeburn 9788: if ($outcome) {
9789: ($result,$resulttype) = split(/:/,$outcome);
9790: }
9791: return ($result,$resulttype);
9792: }
9793:
9794: sub auto_photochoice {
9795: my ($cnum,$cdom) = @_;
9796: my $homeserver = &homeserver($cnum,$cdom);
9797: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9798: &escape($cdom),
9799: $homeserver)));
1.709 albertel 9800: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9801: return (undef,undef);
9802: }
1.706 raeburn 9803: return ($update,$comment);
9804: }
9805:
9806: sub auto_photoupdate {
9807: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9808: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9809: my $host=&hostname($homeserver);
1.706 raeburn 9810: my $cmd = '';
9811: my $maxtries = 1;
1.800 albertel 9812: foreach my $affiliate (keys(%{$affiliatesref})) {
9813: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9814: }
9815: $cmd =~ s/%%$//;
9816: $cmd = &escape($cmd);
9817: my $query = 'institutionalphotos';
9818: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9819: unless ($queryid=~/^\Q$host\E\_/) {
9820: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9821: return 'error: '.$queryid;
9822: }
9823: my $reply = &get_query_reply($queryid);
9824: my $tries = 1;
9825: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9826: $reply = &get_query_reply($queryid);
9827: $tries ++;
9828: }
9829: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9830: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9831: } else {
9832: my @responses = split(/:/,$reply);
9833: my $outcome = shift(@responses);
9834: foreach my $item (@responses) {
9835: my ($key,$value) = split(/=/,$item);
9836: $$photo{$key} = $value;
9837: }
9838: return $outcome;
9839: }
9840: return 'error';
9841: }
9842:
1.521 raeburn 9843: sub auto_instcode_format {
1.793 albertel 9844: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9845: $cat_order) = @_;
1.521 raeburn 9846: my $courses = '';
1.772 raeburn 9847: my @homeservers;
1.521 raeburn 9848: if ($caller eq 'global') {
1.841 albertel 9849: my %servers = &get_servers($codedom,'library');
9850: foreach my $tryserver (keys(%servers)) {
9851: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9852: push(@homeservers,$tryserver);
9853: }
1.584 raeburn 9854: }
1.1022 raeburn 9855: } elsif ($caller eq 'requests') {
9856: if ($codedom =~ /^$match_domain$/) {
9857: my $chome = &domain($codedom,'primary');
9858: unless ($chome eq 'no_host') {
9859: push(@homeservers,$chome);
9860: }
9861: }
1.521 raeburn 9862: } else {
1.772 raeburn 9863: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9864: }
1.793 albertel 9865: foreach my $code (keys(%{$instcodes})) {
9866: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9867: }
9868: chop($courses);
1.772 raeburn 9869: my $ok_response = 0;
9870: my $response;
9871: while (@homeservers > 0 && $ok_response == 0) {
9872: my $server = shift(@homeservers);
9873: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9874: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9875: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9876: split(/:/,$response);
1.772 raeburn 9877: %{$codes} = (%{$codes},&str2hash($codes_str));
9878: push(@{$codetitles},&str2array($codetitles_str));
9879: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9880: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9881: $ok_response = 1;
9882: }
9883: }
9884: if ($ok_response) {
1.521 raeburn 9885: return 'ok';
1.772 raeburn 9886: } else {
9887: return $response;
1.521 raeburn 9888: }
9889: }
9890:
1.792 raeburn 9891: sub auto_instcode_defaults {
9892: my ($domain,$returnhash,$code_order) = @_;
9893: my @homeservers;
1.841 albertel 9894:
9895: my %servers = &get_servers($domain,'library');
9896: foreach my $tryserver (keys(%servers)) {
9897: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9898: push(@homeservers,$tryserver);
9899: }
1.792 raeburn 9900: }
1.841 albertel 9901:
1.792 raeburn 9902: my $response;
1.841 albertel 9903: foreach my $server (@homeservers) {
1.792 raeburn 9904: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9905: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9906:
9907: foreach my $pair (split(/\&/,$response)) {
9908: my ($name,$value)=split(/\=/,$pair);
9909: if ($name eq 'code_order') {
9910: @{$code_order} = split(/\&/,&unescape($value));
9911: } else {
9912: $returnhash->{&unescape($name)}=&unescape($value);
9913: }
9914: }
9915: return 'ok';
1.792 raeburn 9916: }
1.841 albertel 9917:
9918: return $response;
1.1003 raeburn 9919: }
9920:
9921: sub auto_possible_instcodes {
1.1007 raeburn 9922: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9923: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9924: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9925: return;
9926: }
1.1003 raeburn 9927: my (@homeservers,$uhome);
9928: if (defined(&domain($domain,'primary'))) {
9929: $uhome=&domain($domain,'primary');
9930: push(@homeservers,&domain($domain,'primary'));
9931: } else {
9932: my %servers = &get_servers($domain,'library');
9933: foreach my $tryserver (keys(%servers)) {
9934: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9935: push(@homeservers,$tryserver);
9936: }
9937: }
9938: }
9939: my $response;
9940: foreach my $server (@homeservers) {
9941: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9942: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9943: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9944: split(':',$response);
9945: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9946: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9947: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9948: my ($name,$value)=split('=',$item);
9949: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9950: }
9951: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9952: my ($name,$value)=split('=',$item);
9953: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9954: }
9955: return 'ok';
9956: }
9957: return $response;
9958: }
1.792 raeburn 9959:
1.1010 raeburn 9960: sub auto_courserequest_checks {
9961: my ($dom) = @_;
1.1020 raeburn 9962: my ($homeserver,%validations);
9963: if ($dom =~ /^$match_domain$/) {
9964: $homeserver = &domain($dom,'primary');
9965: }
9966: unless ($homeserver eq 'no_host') {
9967: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9968: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9969: my @items = split(/&/,$response);
9970: foreach my $item (@items) {
9971: my ($key,$value) = split('=',$item);
9972: $validations{&unescape($key)} = &thaw_unescape($value);
9973: }
9974: }
9975: }
1.1010 raeburn 9976: return %validations;
9977: }
9978:
1.1020 raeburn 9979: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9980: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9981: my ($homeserver,$response);
9982: if ($dom =~ /^$match_domain$/) {
9983: $homeserver = &domain($dom,'primary');
9984: }
1.1172.2.43 raeburn 9985: unless ($homeserver eq 'no_host') {
9986: my $customdata;
9987: if (ref($custominfo) eq 'HASH') {
9988: $customdata = &freeze_escape($custominfo);
9989: }
1.1020 raeburn 9990: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9991: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9992: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9993: $customdata,$homeserver));
1.1020 raeburn 9994: }
9995: return $response;
9996: }
9997:
1.777 albertel 9998: sub auto_validate_class_sec {
1.918 raeburn 9999: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10000: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10001: my $ownerlist;
10002: if (ref($owners) eq 'ARRAY') {
10003: $ownerlist = join(',',@{$owners});
10004: } else {
10005: $ownerlist = $owners;
10006: }
1.773 raeburn 10007: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10008: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10009: return $response;
10010: }
10011:
1.1172.2.141 raeburn 10012: sub auto_instsec_reformat {
10013: my ($cdom,$action,$instsecref) = @_;
10014: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10015: my @homeservers;
10016: if (defined(&domain($cdom,'primary'))) {
10017: push(@homeservers,&domain($cdom,'primary'));
10018: } else {
10019: my %servers = &get_servers($cdom,'library');
10020: foreach my $tryserver (keys(%servers)) {
10021: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10022: push(@homeservers,$tryserver);
10023: }
10024: }
10025: }
10026: my $response;
10027: my %reformatted = %{$instsecref};
10028: foreach my $server (@homeservers) {
10029: if (ref($instsecref) eq 'HASH') {
10030: my $info = &freeze_escape($instsecref);
10031: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10032: $action.':'.$info,$server);
10033: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10034: my @items = split(/&/,$response);
10035: foreach my $item (@items) {
10036: my ($key,$value) = split(/=/,$item);
10037: $reformatted{&unescape($key)} = &thaw_unescape($value);
10038: }
10039: }
10040: }
10041: return %reformatted;
10042: }
10043:
1.1172.2.94 raeburn 10044: sub auto_validate_instclasses {
10045: my ($cdom,$cnum,$owners,$classesref) = @_;
10046: my ($homeserver,%validations);
10047: $homeserver = &homeserver($cnum,$cdom);
10048: unless ($homeserver eq 'no_host') {
10049: my $ownerlist;
10050: if (ref($owners) eq 'ARRAY') {
10051: $ownerlist = join(',',@{$owners});
10052: } else {
10053: $ownerlist = $owners;
10054: }
10055: if (ref($classesref) eq 'HASH') {
10056: my $classes = &freeze_escape($classesref);
10057: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10058: ':'.$cdom.':'.$classes,$homeserver);
10059: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10060: my @items = split(/&/,$response);
10061: foreach my $item (@items) {
10062: my ($key,$value) = split('=',$item);
10063: $validations{&unescape($key)} = &thaw_unescape($value);
10064: }
10065: }
10066: }
10067: }
10068: return %validations;
10069: }
10070:
1.1172.2.38 raeburn 10071: sub auto_crsreq_update {
10072: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 10073: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 10074: my ($homeserver,%crsreqresponse);
10075: if ($cdom =~ /^$match_domain$/) {
10076: $homeserver = &domain($cdom,'primary');
10077: }
10078: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10079: my $info;
10080: if (ref($inbound) eq 'HASH') {
10081: $info = &freeze_escape($inbound);
10082: }
10083: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10084: ':'.&escape($action).':'.&escape($ownername).':'.
10085: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 10086: &escape($title).':'.&escape($code).':'.
10087: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 10088: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10089: my @items = split(/&/,$response);
10090: foreach my $item (@items) {
10091: my ($key,$value) = split('=',$item);
10092: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10093: }
10094: }
10095: }
10096: return \%crsreqresponse;
10097: }
10098:
1.1172.2.78 raeburn 10099: sub auto_export_grades {
10100: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10101: my ($homeserver,%exportresponse);
10102: if ($cdom =~ /^$match_domain$/) {
10103: $homeserver = &domain($cdom,'primary');
10104: }
10105: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10106: my $info;
10107: if (ref($inforef) eq 'HASH') {
10108: $info = &freeze_escape($inforef);
10109: }
10110: if (ref($gradesref) eq 'HASH') {
10111: my $grades = &freeze_escape($gradesref);
10112: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10113: $info.':'.$grades,$homeserver);
10114: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10115: my @items = split(/&/,$response);
10116: foreach my $item (@items) {
10117: my ($key,$value) = split('=',$item);
10118: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10119: }
10120: }
10121: }
10122: }
10123: return \%exportresponse;
10124: }
10125:
1.1172.2.68 raeburn 10126: sub check_instcode_cloning {
10127: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10128: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10129: return;
10130: }
10131: my $canclone;
10132: if (@{$code_order} > 0) {
10133: my $instcoderegexp ='^';
10134: my @clonecodes = split(/\&/,$cloner);
10135: foreach my $item (@{$code_order}) {
10136: if (grep(/^\Q$item\E=/,@clonecodes)) {
10137: foreach my $pair (@clonecodes) {
10138: my ($key,$val) = split(/\=/,$pair,2);
10139: $val = &unescape($val);
10140: if ($key eq $item) {
10141: $instcoderegexp .= '('.$val.')';
10142: last;
10143: }
10144: }
10145: } else {
10146: $instcoderegexp .= $codedefaults->{$item};
10147: }
10148: }
10149: $instcoderegexp .= '$';
10150: my (@from,@to);
10151: eval {
10152: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10153: (@to) = ($clonetocode =~ /$instcoderegexp/);
10154: };
10155: if ((@from > 0) && (@to > 0)) {
10156: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10157: if (!@diffs) {
10158: $canclone = 1;
10159: }
10160: }
10161: }
10162: return $canclone;
10163: }
10164:
10165: sub default_instcode_cloning {
10166: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10167: my (%codedefaults,@code_order,$canclone);
10168: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10169: %codedefaults = %{$codedefaultsref};
10170: @code_order = @{$codeorderref};
10171: } elsif ($clonedom) {
10172: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10173: }
10174: if (($domdefclone) && (@code_order)) {
10175: my @clonecodes = split(/\+/,$domdefclone);
10176: my $instcoderegexp ='^';
10177: foreach my $item (@code_order) {
10178: if (grep(/^\Q$item\E$/,@clonecodes)) {
10179: $instcoderegexp .= '('.$codedefaults{$item}.')';
10180: } else {
10181: $instcoderegexp .= $codedefaults{$item};
10182: }
10183: }
10184: $instcoderegexp .= '$';
10185: my (@from,@to);
10186: eval {
10187: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10188: (@to) = ($clonetocode =~ /$instcoderegexp/);
10189: };
10190: if ((@from > 0) && (@to > 0)) {
10191: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10192: if (!@diffs) {
10193: $canclone = 1;
10194: }
10195: }
10196: }
10197: return $canclone;
10198: }
10199:
1.679 raeburn 10200: # ------------------------------------------------------- Course Group routines
10201:
10202: sub get_coursegroups {
1.809 raeburn 10203: my ($cdom,$cnum,$group,$namespace) = @_;
10204: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10205: }
10206:
1.679 raeburn 10207: sub modify_coursegroup {
10208: my ($cdom,$cnum,$groupsettings) = @_;
10209: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10210: }
10211:
1.809 raeburn 10212: sub toggle_coursegroup_status {
10213: my ($cdom,$cnum,$group,$action) = @_;
10214: my ($from_namespace,$to_namespace);
10215: if ($action eq 'delete') {
10216: $from_namespace = 'coursegroups';
10217: $to_namespace = 'deleted_groups';
10218: } else {
10219: $from_namespace = 'deleted_groups';
10220: $to_namespace = 'coursegroups';
10221: }
10222: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10223: if (my $tmp = &error(%curr_group)) {
10224: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10225: return ('read error',$tmp);
10226: } else {
10227: my %savedsettings = %curr_group;
1.809 raeburn 10228: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10229: my $deloutcome;
10230: if ($result eq 'ok') {
1.809 raeburn 10231: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10232: } else {
10233: return ('write error',$result);
10234: }
10235: if ($deloutcome eq 'ok') {
10236: return 'ok';
10237: } else {
10238: return ('delete error',$deloutcome);
10239: }
10240: }
10241: }
10242:
1.679 raeburn 10243: sub modify_group_roles {
1.957 raeburn 10244: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10245: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10246: my $role = 'gr/'.&escape($userprivs);
10247: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10248: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10249: if ($result eq 'ok') {
10250: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10251: }
1.679 raeburn 10252: return $result;
10253: }
10254:
10255: sub modify_coursegroup_membership {
10256: my ($cdom,$cnum,$membership) = @_;
10257: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10258: return $result;
10259: }
10260:
1.682 raeburn 10261: sub get_active_groups {
10262: my ($udom,$uname,$cdom,$cnum) = @_;
10263: my $now = time;
10264: my %groups = ();
10265: foreach my $key (keys(%env)) {
1.811 albertel 10266: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10267: my ($start,$end) = split(/\./,$env{$key});
10268: if (($end!=0) && ($end<$now)) { next; }
10269: if (($start!=0) && ($start>$now)) { next; }
10270: if ($1 eq $cdom && $2 eq $cnum) {
10271: $groups{$3} = $env{$key} ;
10272: }
10273: }
10274: }
10275: return %groups;
10276: }
10277:
1.683 raeburn 10278: sub get_group_membership {
10279: my ($cdom,$cnum,$group) = @_;
10280: return(&dump('groupmembership',$cdom,$cnum,$group));
10281: }
10282:
10283: sub get_users_groups {
10284: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10285: my @usersgroups;
1.683 raeburn 10286: my $cachetime=1800;
10287:
10288: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10289: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10290: if (defined($cached)) {
1.734 albertel 10291: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10292: } else {
10293: $grouplist = '';
1.816 raeburn 10294: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10295: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10296: my $access_end = $env{'course.'.$courseid.
10297: '.default_enrollment_end_date'};
10298: my $now = time;
10299: foreach my $key (keys(%roleshash)) {
10300: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10301: my $group = $1;
10302: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10303: my $start = $2;
10304: my $end = $1;
10305: if ($start == -1) { next; } # deleted from group
10306: if (($start!=0) && ($start>$now)) { next; }
10307: if (($end!=0) && ($end<$now)) {
10308: if ($access_end && $access_end < $now) {
10309: if ($access_end - $end < 86400) {
10310: push(@usersgroups,$group);
1.733 raeburn 10311: }
10312: }
1.817 raeburn 10313: next;
1.733 raeburn 10314: }
1.817 raeburn 10315: push(@usersgroups,$group);
1.683 raeburn 10316: }
10317: }
10318: }
1.817 raeburn 10319: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10320: $grouplist = join(':',@usersgroups);
10321: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10322: }
1.733 raeburn 10323: return @usersgroups;
1.683 raeburn 10324: }
10325:
10326: sub devalidate_getgroups_cache {
10327: my ($udom,$uname,$cdom,$cnum)=@_;
10328: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10329:
1.683 raeburn 10330: my $hashid="$udom:$uname:$courseid";
10331: &devalidate_cache_new('getgroups',$hashid);
10332: }
10333:
1.12 www 10334: # ------------------------------------------------------------------ Plain Text
10335:
10336: sub plaintext {
1.988 raeburn 10337: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10338: if ($short =~ m{^cr/}) {
1.758 albertel 10339: return (split('/',$short))[-1];
10340: }
1.742 raeburn 10341: if (!defined($cid)) {
10342: $cid = $env{'request.course.id'};
10343: }
10344: my %rolenames = (
1.1008 raeburn 10345: Course => 'std',
10346: Community => 'alt1',
1.742 raeburn 10347: );
1.1037 raeburn 10348: if ($cid ne '') {
10349: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10350: unless ($forcedefault) {
10351: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10352: &Apache::lonlocal::mt_escape(\$roletext);
10353: return &Apache::lonlocal::mt($roletext);
10354: }
10355: }
10356: }
10357: if ((defined($type)) && (defined($rolenames{$type})) &&
10358: (defined($rolenames{$type})) &&
10359: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10360: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10361: } elsif ($cid ne '') {
10362: my $crstype = $env{'course.'.$cid.'.type'};
10363: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10364: (defined($prp{$short}{$rolenames{$crstype}}))) {
10365: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10366: }
1.742 raeburn 10367: }
1.1037 raeburn 10368: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10369: }
10370:
10371: # ----------------------------------------------------------------- Assign Role
10372:
10373: sub assignrole {
1.957 raeburn 10374: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10375: $context)=@_;
1.21 www 10376: my $mrole;
10377: if ($role =~ /^cr\//) {
1.393 www 10378: my $cwosec=$url;
1.811 albertel 10379: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10380: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10381: my $refused = 1;
10382: if ($context eq 'requestcourses') {
10383: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10384: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10385: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10386: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10387: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10388: if ($crsenv{'internal.courseowner'} eq
10389: $env{'user.name'}.':'.$env{'user.domain'}) {
10390: $refused = '';
10391: }
10392: }
10393: }
10394: }
10395: }
10396: if ($refused) {
10397: &logthis('Refused custom assignrole: '.
10398: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10399: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10400: return 'refused';
10401: }
1.104 www 10402: }
1.21 www 10403: $mrole='cr';
1.678 raeburn 10404: } elsif ($role =~ /^gr\//) {
10405: my $cwogrp=$url;
1.811 albertel 10406: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10407: unless (&allowed('mdg',$cwogrp)) {
10408: &logthis('Refused group assignrole: '.
10409: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10410: $env{'user.name'}.' at '.$env{'user.domain'});
10411: return 'refused';
10412: }
10413: $mrole='gr';
1.21 www 10414: } else {
1.82 www 10415: my $cwosec=$url;
1.811 albertel 10416: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10417: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10418: my $refused;
10419: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10420: if (!(&allowed('c'.$role,$url))) {
10421: $refused = 1;
10422: }
10423: } else {
10424: $refused = 1;
10425: }
1.947 raeburn 10426: if ($refused) {
1.1045 raeburn 10427: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10428: if (!$selfenroll && $context eq 'course') {
10429: my %crsenv;
10430: if ($role eq 'cc' || $role eq 'co') {
10431: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10432: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10433: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10434: if ($crsenv{'internal.courseowner'} eq
10435: $env{'user.name'}.':'.$env{'user.domain'}) {
10436: $refused = '';
10437: }
10438: }
10439: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10440: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10441: if ($crsenv{'internal.courseowner'} eq
10442: $env{'user.name'}.':'.$env{'user.domain'}) {
10443: $refused = '';
10444: }
10445: }
10446: }
10447: }
1.1172.2.146. .13(raeb 10448:-23): } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10449:-23): if ($role eq 'st') {
10450:-23): $refused = '';
10451:-23): } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10452:-23): $refused = '';
10453:-23): }
1.1017 raeburn 10454: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10455: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10456: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10457: my $wrongcc;
10458: if ($cnum =~ /^$match_community$/) {
10459: $wrongcc = 1 if ($role eq 'cc');
10460: } else {
10461: $wrongcc = 1 if ($role eq 'co');
10462: }
10463: unless ($wrongcc) {
10464: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10465: if ($crsenv{'internal.courseowner'} eq
10466: $env{'user.name'}.':'.$env{'user.domain'}) {
10467: $refused = '';
10468: }
1.1017 raeburn 10469: }
10470: }
1.1172.2.9 raeburn 10471: } elsif ($context eq 'requestauthor') {
10472: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10473: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10474: if ($env{'environment.requestauthor'} eq 'automatic') {
10475: $refused = '';
10476: } else {
10477: my %domdefaults = &get_domain_defaults($udom);
10478: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10479: my $checkbystatus;
10480: if ($env{'user.adv'}) {
10481: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10482: if ($disposition eq 'automatic') {
10483: $refused = '';
10484: } elsif ($disposition eq '') {
10485: $checkbystatus = 1;
10486: }
10487: } else {
10488: $checkbystatus = 1;
10489: }
10490: if ($checkbystatus) {
10491: if ($env{'environment.inststatus'}) {
10492: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10493: foreach my $type (@inststatuses) {
10494: if (($type ne '') &&
10495: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10496: $refused = '';
10497: }
10498: }
10499: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10500: $refused = '';
10501: }
10502: }
10503: }
10504: }
10505: }
1.1017 raeburn 10506: }
10507: if ($refused) {
1.947 raeburn 10508: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10509: ' '.$role.' '.$end.' '.$start.' by '.
10510: $env{'user.name'}.' at '.$env{'user.domain'});
10511: return 'refused';
10512: }
1.932 raeburn 10513: }
1.1131 raeburn 10514: } elsif ($role eq 'au') {
10515: if ($url ne '/'.$udom.'/') {
10516: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10517: ' to assign author role for '.$uname.':'.$udom.
10518: ' in domain: '.$url.' refused (wrong domain).');
10519: return 'refused';
10520: }
1.104 www 10521: }
1.21 www 10522: $mrole=$role;
10523: }
1.620 albertel 10524: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10525: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10526: if ($end) { $command.='_'.$end; }
1.21 www 10527: if ($start) {
10528: if ($end) {
1.81 www 10529: $command.='_'.$start;
1.21 www 10530: } else {
1.81 www 10531: $command.='_0_'.$start;
1.21 www 10532: }
10533: }
1.739 raeburn 10534: my $origstart = $start;
10535: my $origend = $end;
1.957 raeburn 10536: my $delflag;
1.357 www 10537: # actually delete
10538: if ($deleteflag) {
1.373 www 10539: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10540: # modify command to delete the role
1.620 albertel 10541: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10542: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10543: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10544: # set start and finish to negative values for userrolelog
10545: $start=-1;
10546: $end=-1;
1.957 raeburn 10547: $delflag = 1;
1.357 www 10548: }
10549: }
10550: # send command
1.349 www 10551: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10552: # log new user role if status is ok
1.349 www 10553: if ($answer eq 'ok') {
1.663 raeburn 10554: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 10555: if (($role eq 'cc') || ($role eq 'in') ||
10556: ($role eq 'ep') || ($role eq 'ad') ||
10557: ($role eq 'ta') || ($role eq 'st') ||
10558: ($role=~/^cr/) || ($role eq 'gr') ||
10559: ($role eq 'co')) {
1.1172.2.13 raeburn 10560: # for course roles, perform group memberships changes triggered by role change.
10561: unless ($role =~ /^gr/) {
10562: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10563: $origstart,$selfenroll,$context);
10564: }
1.1172.2.9 raeburn 10565: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10566: $selfenroll,$context);
10567: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10568: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10569: ($role eq 'da')) {
1.1172.2.9 raeburn 10570: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10571: $context);
10572: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10573: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10574: $context);
10575: }
1.1053 raeburn 10576: if ($role eq 'cc') {
10577: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10578: }
1.349 www 10579: }
10580: return $answer;
1.169 harris41 10581: }
10582:
1.1053 raeburn 10583: sub autoupdate_coowners {
10584: my ($url,$end,$start,$uname,$udom) = @_;
10585: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10586: if (($cdom ne '') && ($cnum ne '')) {
10587: my $now = time;
10588: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10589: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10590: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10591: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10592: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10593: if ($instcode ne '') {
1.1056 raeburn 10594: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10595: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10596: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10597: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10598: unless ($result eq 'valid') {
10599: if ($xlists ne '') {
10600: foreach my $xlist (split(',',$xlists)) {
10601: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10602: $result =
10603: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10604: $inst_crosslist,$uname.':'.$udom);
10605: last if ($result eq 'valid');
10606: }
10607: }
10608: }
1.1056 raeburn 10609: if ($result eq 'valid') {
10610: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10611: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10612: push(@newcoowners,$coowner);
10613: }
10614: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10615: push(@newcoowners,$uname.':'.$udom);
10616: }
10617: @newcoowners = sort(@newcoowners);
10618: } else {
10619: push(@newcoowners,$uname.':'.$udom);
10620: }
1.1172.2.141 raeburn 10621: } elsif ($coursehash{'internal.co-owners'}) {
10622: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10623: unless ($coowner eq $uname.':'.$udom) {
10624: push(@newcoowners,$coowner);
1.1053 raeburn 10625: }
10626: }
1.1172.2.141 raeburn 10627: unless (@newcoowners > 0) {
10628: $delcoowners = 1;
10629: $coowners = '';
10630: }
1.1053 raeburn 10631: }
10632: if (@newcoowners || $delcoowners) {
10633: &store_coowners($cdom,$cnum,$coursehash{'home'},
10634: $delcoowners,@newcoowners);
10635: }
10636: }
10637: }
10638: }
10639: }
10640: }
10641: }
10642:
10643: sub store_coowners {
10644: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10645: my $cid = $cdom.'_'.$cnum;
10646: my ($coowners,$delresult,$putresult);
10647: if (@newcoowners) {
10648: $coowners = join(',',@newcoowners);
10649: my %coownershash = (
10650: 'internal.co-owners' => $coowners,
10651: );
10652: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10653: if ($putresult eq 'ok') {
10654: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10655: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10656: }
10657: }
10658: }
10659: if ($delcoowners) {
10660: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10661: if ($delresult eq 'ok') {
10662: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10663: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10664: }
10665: }
10666: }
10667: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10668: my %crsinfo =
10669: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10670: if (ref($crsinfo{$cid}) eq 'HASH') {
10671: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10672: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10673: }
10674: }
10675: }
10676:
1.169 harris41 10677: # -------------------------------------------------- Modify user authentication
1.197 www 10678: # Overrides without validation
10679:
1.169 harris41 10680: sub modifyuserauth {
10681: my ($udom,$uname,$umode,$upass)=@_;
10682: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10683: my $allowed;
10684: if (&allowed('mau',$udom)) {
10685: $allowed = 1;
10686: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10687: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10688: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10689: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10690: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10691: if (($cdom ne '') && ($cnum ne '')) {
10692: my $is_owner = &is_course_owner($cdom,$cnum);
10693: if ($is_owner) {
10694: $allowed = 1;
10695: }
10696: }
10697: }
10698: unless ($allowed) { return 'refused'; }
1.197 www 10699: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10700: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10701: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10702: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10703: &escape($upass),$uhome);
1.1172.2.134 raeburn 10704: my $ip = &get_requestor_ip();
1.620 albertel 10705: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10706: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10707: '(Remote '.$ip.'): '.$reply);
1.197 www 10708: &log($udom,,$uname,$uhome,
1.620 albertel 10709: 'Authentication changed by '.$env{'user.domain'}.', '.
10710: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10711: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10712: unless ($reply eq 'ok') {
1.197 www 10713: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10714: return 'error: '.$reply;
10715: }
1.170 harris41 10716: return 'ok';
1.80 www 10717: }
10718:
1.81 www 10719: # --------------------------------------------------------------- Modify a user
1.80 www 10720:
1.81 www 10721: sub modifyuser {
1.206 matthew 10722: my ($udom, $uname, $uid,
10723: $umode, $upass, $first,
10724: $middle, $last, $gene,
1.1058 raeburn 10725: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10726: $udom= &LONCAPA::clean_domain($udom);
10727: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10728: my $showcandelete = 'none';
10729: if (ref($candelete) eq 'ARRAY') {
10730: if (@{$candelete} > 0) {
10731: $showcandelete = join(', ',@{$candelete});
10732: }
10733: }
1.81 www 10734: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10735: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10736: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10737: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10738: ' desiredhome not specified').
1.620 albertel 10739: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10740: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10741: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10742: my $newuser;
10743: if ($uhome eq 'no_host') {
10744: $newuser = 1;
1.1172.2.146. .13(raeb 10745:-23): unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10746:-23): ($umode eq 'lti')) {
10747:-23): return 'error: more information needed to create new user';
10748:-23): }
1.1075 raeburn 10749: }
1.80 www 10750: # ----------------------------------------------------------------- Create User
1.406 albertel 10751: if (($uhome eq 'no_host') &&
1.1172.2.146. .13(raeb 10752:-23): (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10753: my $unhome='';
1.844 albertel 10754: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10755: $unhome = $desiredhome;
1.620 albertel 10756: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10757: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10758: } else { # load balancing routine for determining $unhome
1.81 www 10759: my $loadm=10000000;
1.841 albertel 10760: my %servers = &get_servers($udom,'library');
10761: foreach my $tryserver (keys(%servers)) {
10762: my $answer=reply('load',$tryserver);
10763: if (($answer=~/\d+/) && ($answer<$loadm)) {
10764: $loadm=$answer;
10765: $unhome=$tryserver;
10766: }
1.80 www 10767: }
10768: }
10769: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10770: return 'error: unable to find a home server for '.$uname.
10771: ' in domain '.$udom;
1.80 www 10772: }
10773: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10774: &escape($upass),$unhome);
10775: unless ($reply eq 'ok') {
10776: return 'error: '.$reply;
10777: }
1.230 stredwic 10778: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10779: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10780: return 'error: unable verify users home machine.';
1.80 www 10781: }
1.209 matthew 10782: } # End of creation of new user
1.80 www 10783: # ---------------------------------------------------------------------- Add ID
10784: if ($uid) {
10785: $uid=~tr/A-Z/a-z/;
10786: my %uidhash=&idrget($udom,$uname);
1.196 www 10787: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10788: && (!$forceid)) {
1.80 www 10789: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10790: return 'error: user id "'.$uid.'" does not match '.
10791: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10792: }
10793: } else {
10794: &idput($udom,($uname => $uid));
10795: }
10796: }
10797: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10798: my @tmp=&get('environment',
1.899 raeburn 10799: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10800: 'permanentemail','inststatus'],
1.134 albertel 10801: $udom,$uname);
1.1075 raeburn 10802: my (%names,%oldnames);
1.313 matthew 10803: if ($tmp[0] =~ m/^error:.*/) {
10804: %names=();
10805: } else {
10806: %names = @tmp;
1.1075 raeburn 10807: %oldnames = %names;
1.313 matthew 10808: }
1.388 www 10809: #
1.1058 raeburn 10810: # If name, email and/or uid are blank (e.g., because an uploaded file
10811: # of users did not contain them), do not overwrite existing values
10812: # unless field is in $candelete array ref.
10813: #
10814:
10815: my @fields = ('firstname','middlename','lastname','generation',
10816: 'permanentemail','id');
10817: my %newvalues;
10818: if (ref($candelete) eq 'ARRAY') {
10819: foreach my $field (@fields) {
10820: if (grep(/^\Q$field\E$/,@{$candelete})) {
10821: if ($field eq 'firstname') {
10822: $names{$field} = $first;
10823: } elsif ($field eq 'middlename') {
10824: $names{$field} = $middle;
10825: } elsif ($field eq 'lastname') {
10826: $names{$field} = $last;
10827: } elsif ($field eq 'generation') {
10828: $names{$field} = $gene;
10829: } elsif ($field eq 'permanentemail') {
10830: $names{$field} = $email;
10831: } elsif ($field eq 'id') {
10832: $names{$field} = $uid;
10833: }
10834: }
10835: }
10836: }
1.388 www 10837: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10838: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10839: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10840: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10841: if ($email) {
10842: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10843: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10844: }
1.899 raeburn 10845: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10846: if (defined($inststatus)) {
10847: $names{'inststatus'} = '';
10848: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10849: if (ref($usertypes) eq 'HASH') {
10850: my @okstatuses;
10851: foreach my $item (split(/:/,$inststatus)) {
10852: if (defined($usertypes->{$item})) {
10853: push(@okstatuses,$item);
10854: }
10855: }
10856: if (@okstatuses) {
10857: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10858: }
10859: }
10860: }
1.1075 raeburn 10861: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10862: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10863: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10864: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10865: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10866: } else {
10867: $logmsg .= ' during self creation';
10868: }
1.1075 raeburn 10869: my $changed;
10870: if ($newuser) {
10871: $changed = 1;
10872: } else {
10873: foreach my $field (@fields) {
10874: if ($names{$field} ne $oldnames{$field}) {
10875: $changed = 1;
10876: last;
10877: }
10878: }
10879: }
10880: unless ($changed) {
10881: $logmsg = 'No changes in user information needed for: '.$logmsg;
10882: &logthis($logmsg);
10883: return 'ok';
10884: }
10885: my $reply = &put('environment', \%names, $udom,$uname);
10886: if ($reply ne 'ok') {
10887: return 'error: '.$reply;
10888: }
1.1087 raeburn 10889: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10890: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10891: }
1.1075 raeburn 10892: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10893: &devalidate_cache_new('namescache',$uname.':'.$udom);
10894: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10895: &logthis($logmsg);
1.134 albertel 10896: return 'ok';
1.80 www 10897: }
10898:
1.81 www 10899: # -------------------------------------------------------------- Modify student
1.80 www 10900:
1.81 www 10901: sub modifystudent {
10902: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10903: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10904: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10905: if (!$cid) {
1.620 albertel 10906: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10907: return 'not_in_class';
10908: }
1.80 www 10909: }
10910: # --------------------------------------------------------------- Make the user
1.81 www 10911: my $reply=&modifyuser
1.209 matthew 10912: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10913: $desiredhome,$email,$inststatus);
1.80 www 10914: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10915: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10916: # student's environment
1.297 matthew 10917: $uid = undef if (!$forceid);
1.455 albertel 10918: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10919: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10920: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10921: return $reply;
10922: }
10923:
10924: sub modify_student_enrollment {
1.1172.2.23 raeburn 10925: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10926: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10927: my ($cdom,$cnum,$chome);
10928: if (!$cid) {
1.620 albertel 10929: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10930: return 'not_in_class';
10931: }
1.620 albertel 10932: $cdom=$env{'course.'.$cid.'.domain'};
10933: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10934: } else {
10935: ($cdom,$cnum)=split(/_/,$cid);
10936: }
1.620 albertel 10937: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10938: if (!$chome) {
1.457 raeburn 10939: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10940: }
1.455 albertel 10941: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10942: # Make sure the user exists
1.81 www 10943: my $uhome=&homeserver($uname,$udom);
10944: if (($uhome eq '') || ($uhome eq 'no_host')) {
10945: return 'error: no such user';
10946: }
1.297 matthew 10947: # Get student data if we were not given enough information
10948: if (!defined($first) || $first eq '' ||
10949: !defined($last) || $last eq '' ||
10950: !defined($uid) || $uid eq '' ||
10951: !defined($middle) || $middle eq '' ||
10952: !defined($gene) || $gene eq '') {
1.294 matthew 10953: # They did not supply us with enough data to enroll the student, so
10954: # we need to pick up more information.
1.297 matthew 10955: my %tmp = &get('environment',
1.294 matthew 10956: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10957: ,$udom,$uname);
10958:
1.800 albertel 10959: #foreach my $key (keys(%tmp)) {
10960: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10961: #}
1.294 matthew 10962: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10963: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10964: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10965: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10966: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10967: }
1.556 albertel 10968: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10969: my $user = "$uname:$udom";
10970: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10971: my $reply=cput('classlist',
1.1148 raeburn 10972: {$user =>
1.1172.2.76 raeburn 10973: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10974: $cdom,$cnum);
1.1148 raeburn 10975: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10976: &devalidate_getsection_cache($udom,$uname,$cid);
10977: } else {
1.81 www 10978: return 'error: '.$reply;
10979: }
1.297 matthew 10980: # Add student role to user
1.83 www 10981: my $uurl='/'.$cid;
1.81 www 10982: $uurl=~s/\_/\//g;
10983: if ($usec) {
10984: $uurl.='/'.$usec;
10985: }
1.1148 raeburn 10986: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10987: $selfenroll,$context);
10988: if ($result ne 'ok') {
10989: if ($old_entry{$user} ne '') {
10990: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10991: } else {
10992: $reply = &del('classlist',[$user],$cdom,$cnum);
10993: }
10994: }
10995: return $result;
1.21 www 10996: }
10997:
1.556 albertel 10998: sub format_name {
10999: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11000: my $name;
11001: if ($first ne 'lastname') {
11002: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11003: } else {
11004: if ($lastname=~/\S/) {
11005: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11006: $name=~s/\s+,/,/;
11007: } else {
11008: $name.= $firstname.' '.$middlename.' '.$generation;
11009: }
11010: }
11011: $name=~s/^\s+//;
11012: $name=~s/\s+$//;
11013: $name=~s/\s+/ /g;
11014: return $name;
11015: }
11016:
1.84 www 11017: # ------------------------------------------------- Write to course preferences
11018:
11019: sub writecoursepref {
11020: my ($courseid,%prefs)=@_;
11021: $courseid=~s/^\///;
11022: $courseid=~s/\_/\//g;
11023: my ($cdomain,$cnum)=split(/\//,$courseid);
11024: my $chome=homeserver($cnum,$cdomain);
11025: if (($chome eq '') || ($chome eq 'no_host')) {
11026: return 'error: no such course';
11027: }
11028: my $cstring='';
1.800 albertel 11029: foreach my $pref (keys(%prefs)) {
11030: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11031: }
1.84 www 11032: $cstring=~s/\&$//;
11033: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11034: }
11035:
11036: # ---------------------------------------------------------- Make/modify course
11037:
11038: sub createcourse {
1.741 raeburn 11039: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146. .1(raebu 11040:22): $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11041: $url=&declutter($url);
11042: my $cid='';
1.1028 raeburn 11043: if ($context eq 'requestcourses') {
11044: my $can_create = 0;
11045: my ($ownername,$ownerdom) = split(':',$course_owner);
11046: if ($udom eq $ownerdom) {
1.1172.2.146. .1(raebu 11047:22): my $reload;
11048:22): if (($callercontext eq 'auto') &&
11049:22): ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11050:22): $reload = 'reload';
11051:22): }
11052:22): if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11053: $context)) {
11054: $can_create = 1;
11055: }
11056: } else {
11057: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11058: $category);
11059: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11060: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11061: if (@curr > 0) {
11062: my @options = qw(approval validate autolimit);
11063: my $optregex = join('|',@options);
11064: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11065: $can_create = 1;
11066: }
11067: }
11068: }
11069: }
11070: if ($can_create) {
11071: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11072: unless (&allowed('ccc',$udom)) {
11073: return 'refused';
11074: }
1.1017 raeburn 11075: }
11076: } else {
11077: return 'refused';
11078: }
1.1028 raeburn 11079: } elsif (!&allowed('ccc',$udom)) {
11080: return 'refused';
1.84 www 11081: }
1.1011 raeburn 11082: # --------------------------------------------------------------- Get Unique ID
11083: my $uname;
11084: if ($cnum =~ /^$match_courseid$/) {
11085: my $chome=&homeserver($cnum,$udom,'true');
11086: if (($chome eq '') || ($chome eq 'no_host')) {
11087: $uname = $cnum;
11088: } else {
1.1038 raeburn 11089: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11090: }
11091: } else {
1.1038 raeburn 11092: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11093: }
11094: return $uname if ($uname =~ /^error/);
11095: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11096: if (!defined($course_server)) {
11097: if (defined(&domain($udom,'primary'))) {
11098: $course_server = &domain($udom,'primary');
11099: } else {
11100: $course_server = $env{'user.home'};
11101: }
11102: }
11103: my %host_servers =
11104: &Apache::lonnet::get_servers($udom,'library');
11105: unless ($host_servers{$course_server}) {
11106: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11107: }
1.84 www 11108: # ------------------------------------------------------------- Make the course
11109: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11110: $course_server);
1.84 www 11111: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11112: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11113: if (($uhome eq '') || ($uhome eq 'no_host')) {
11114: return 'error: no such course';
11115: }
1.271 www 11116: # ----------------------------------------------------------------- Course made
1.516 raeburn 11117: # log existence
1.1029 raeburn 11118: my $now = time;
1.918 raeburn 11119: my $newcourse = {
11120: $udom.'_'.$uname => {
1.921 raeburn 11121: description => $description,
11122: inst_code => $inst_code,
11123: owner => $course_owner,
11124: type => $crstype,
1.1029 raeburn 11125: creator => $env{'user.name'}.':'.
11126: $env{'user.domain'},
11127: created => $now,
11128: context => $context,
1.918 raeburn 11129: },
11130: };
1.921 raeburn 11131: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11132: # set toplevel url
1.271 www 11133: my $topurl=$url;
11134: unless ($nonstandard) {
11135: # ------------------------------------------ For standard courses, make top url
11136: my $mapurl=&clutter($url);
1.278 www 11137: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11138: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11139: <map>
11140: <resource id="1" type="start"></resource>
11141: <resource id="2" src="$mapurl"></resource>
11142: <resource id="3" type="finish"></resource>
11143: <link index="1" from="1" to="2"></link>
11144: <link index="2" from="2" to="3"></link>
11145: </map>
11146: ENDINITMAP
11147: $topurl=&declutter(
1.638 albertel 11148: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11149: );
11150: }
11151: # ----------------------------------------------------------- Write preferences
1.84 www 11152: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11153: ('description' => $description,
11154: 'url' => $topurl,
11155: 'internal.creator' => $env{'user.name'}.':'.
11156: $env{'user.domain'},
11157: 'internal.created' => $now,
11158: 'internal.creationcontext' => $context)
11159: );
1.84 www 11160: return '/'.$udom.'/'.$uname;
11161: }
11162:
1.1011 raeburn 11163: # ------------------------------------------------------------------- Create ID
11164: sub generate_coursenum {
1.1038 raeburn 11165: my ($udom,$crstype) = @_;
1.1011 raeburn 11166: my $domdesc = &domain($udom);
11167: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11168: my $first;
11169: if ($crstype eq 'Community') {
11170: $first = '0';
11171: } else {
11172: $first = int(1+rand(9));
11173: }
11174: my $uname=$first.
1.1011 raeburn 11175: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11176: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11177: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11178: # ----------------------------------------------- Make sure that does not exist
11179: my $uhome=&homeserver($uname,$udom,'true');
11180: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11181: if ($crstype eq 'Community') {
11182: $first = '0';
11183: } else {
11184: $first = int(1+rand(9));
11185: }
11186: $uname=$first.
1.1011 raeburn 11187: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11188: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11189: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11190: $uhome=&homeserver($uname,$udom,'true');
11191: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11192: return 'error: unable to generate unique course-ID';
11193: }
11194: }
11195: return $uname;
11196: }
11197:
1.813 albertel 11198: sub is_course {
1.1167 droeschl 11199: my ($cdom, $cnum) = scalar(@_) == 1 ?
11200: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 11201: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11202: my $uhome=&homeserver($cnum,$cdom);
11203: my $iscourse;
11204: if (grep { $_ eq $uhome } current_machine_ids()) {
11205: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11206: } else {
11207: my $hashid = $cdom.':'.$cnum;
11208: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11209: unless (defined($cached)) {
11210: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11211: $cnum,undef,undef,'.');
11212: $iscourse = 0;
11213: if (exists($courses{$cdom.'_'.$cnum})) {
11214: $iscourse = 1;
11215: }
11216: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11217: }
11218: }
11219: return unless($iscourse);
1.1167 droeschl 11220: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11221: }
11222:
1.1015 raeburn 11223: sub store_userdata {
11224: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11225: my $result;
1.1016 raeburn 11226: if ($datakey ne '') {
1.1013 raeburn 11227: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11228: if ($udom eq '' || $uname eq '') {
11229: $udom = $env{'user.domain'};
11230: $uname = $env{'user.name'};
11231: }
11232: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11233: if (($uhome eq '') || ($uhome eq 'no_host')) {
11234: $result = 'error: no_host';
11235: } else {
1.1172.2.138 raeburn 11236: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11237: $storehash->{'host'} = $perlvar{'lonHostID'};
11238:
11239: my $namevalue='';
11240: foreach my $key (keys(%{$storehash})) {
11241: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11242: }
11243: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 11244: unless ($namespace eq 'courserequests') {
11245: $datakey = &escape($datakey);
11246: }
1.1105 raeburn 11247: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11248: $namevalue,$uhome);
1.1013 raeburn 11249: }
11250: } else {
11251: $result = 'error: data to store was not a hash reference';
11252: }
11253: } else {
11254: $result= 'error: invalid requestkey';
11255: }
11256: return $result;
11257: }
11258:
1.21 www 11259: # ---------------------------------------------------------- Assign Custom Role
11260:
11261: sub assigncustomrole {
1.957 raeburn 11262: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11263: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11264: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11265: }
11266:
11267: # ----------------------------------------------------------------- Revoke Role
11268:
11269: sub revokerole {
1.957 raeburn 11270: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11271: my $now=time;
1.965 raeburn 11272: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11273: }
11274:
11275: # ---------------------------------------------------------- Revoke Custom Role
11276:
11277: sub revokecustomrole {
1.957 raeburn 11278: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11279: my $now=time;
1.357 www 11280: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11281: $deleteflag,$selfenroll,$context);
1.17 www 11282: }
11283:
1.533 banghart 11284: # ------------------------------------------------------------ Disk usage
1.535 albertel 11285: sub diskusage {
1.955 raeburn 11286: my ($udom,$uname,$directorypath,$getpropath)=@_;
11287: $directorypath =~ s/\/$//;
11288: my $listing=&reply('du2:'.&escape($directorypath).':'
11289: .&escape($getpropath).':'.&escape($uname).':'
11290: .&escape($udom),homeserver($uname,$udom));
11291: if ($listing eq 'unknown_cmd') {
11292: if ($getpropath) {
11293: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11294: }
11295: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11296: }
1.514 albertel 11297: return $listing;
1.512 banghart 11298: }
11299:
1.566 banghart 11300: sub is_locked {
1.1096 raeburn 11301: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11302: my @check;
11303: my $is_locked;
1.1093 raeburn 11304: push (@check,$file_name);
1.613 albertel 11305: my %locked = &get('file_permissions',\@check,
1.620 albertel 11306: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11307: my ($tmp)=keys(%locked);
11308: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11309:
1.566 banghart 11310: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11311: $is_locked = 'false';
11312: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11313: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11314: $is_locked = 'true';
1.1096 raeburn 11315: if (ref($which) eq 'ARRAY') {
11316: push(@{$which},$entry);
11317: } else {
11318: last;
11319: }
1.745 raeburn 11320: }
11321: }
1.566 banghart 11322: } else {
11323: $is_locked = 'false';
11324: }
1.1093 raeburn 11325: return $is_locked;
1.566 banghart 11326: }
11327:
1.759 albertel 11328: sub declutter_portfile {
11329: my ($file) = @_;
1.833 albertel 11330: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11331: return $file;
11332: }
11333:
1.559 banghart 11334: # ------------------------------------------------------------- Mark as Read Only
11335:
11336: sub mark_as_readonly {
11337: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11338: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11339: my ($tmp)=keys(%current_permissions);
11340: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11341: foreach my $file (@{$files}) {
1.759 albertel 11342: $file = &declutter_portfile($file);
1.561 banghart 11343: push(@{$current_permissions{$file}},$what);
1.559 banghart 11344: }
1.613 albertel 11345: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11346: return;
11347: }
11348:
1.572 banghart 11349: # ------------------------------------------------------------Save Selected Files
11350:
11351: sub save_selected_files {
11352: my ($user, $path, @files) = @_;
11353: my $filename = $user."savedfiles";
1.573 banghart 11354: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 11355: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11356: foreach my $file (@files) {
1.620 albertel 11357: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11358: }
11359: foreach my $file (@other_files) {
1.574 banghart 11360: print (OUT $file."\n");
1.572 banghart 11361: }
1.574 banghart 11362: close (OUT);
1.572 banghart 11363: return 'ok';
11364: }
11365:
1.574 banghart 11366: sub clear_selected_files {
11367: my ($user) = @_;
11368: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 11369: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11370: print (OUT undef);
11371: close (OUT);
11372: return ("ok");
11373: }
11374:
1.572 banghart 11375: sub files_in_path {
11376: my ($user, $path) = @_;
11377: my $filename = $user."savedfiles";
11378: my %return_files;
1.1172.2.96 raeburn 11379: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11380: while (my $line_in = <IN>) {
1.574 banghart 11381: chomp ($line_in);
11382: my @paths_and_file = split (m!/!, $line_in);
11383: my $file_part = pop (@paths_and_file);
11384: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11385: $path_part.='/';
11386: my $path_and_file = $path_part.$file_part;
11387: if ($path_part eq $path) {
11388: $return_files{$file_part}= 'selected';
11389: }
11390: }
1.574 banghart 11391: close (IN);
11392: return (\%return_files);
1.572 banghart 11393: }
11394:
11395: # called in portfolio select mode, to show files selected NOT in current directory
11396: sub files_not_in_path {
11397: my ($user, $path) = @_;
11398: my $filename = $user."savedfiles";
11399: my @return_files;
11400: my $path_part;
1.1172.2.96 raeburn 11401: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11402: while (my $line = <IN>) {
1.572 banghart 11403: #ok, I know it's clunky, but I want it to work
1.800 albertel 11404: my @paths_and_file = split(m|/|, $line);
11405: my $file_part = pop(@paths_and_file);
11406: chomp($file_part);
11407: my $path_part = join('/', @paths_and_file);
1.572 banghart 11408: $path_part .= '/';
11409: my $path_and_file = $path_part.$file_part;
11410: if ($path_part ne $path) {
1.800 albertel 11411: push(@return_files, ($path_and_file));
1.572 banghart 11412: }
11413: }
1.800 albertel 11414: close(OUT);
1.574 banghart 11415: return (@return_files);
1.572 banghart 11416: }
11417:
1.745 raeburn 11418: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11419:
1.745 raeburn 11420: sub get_portfile_permissions {
11421: my ($domain,$user) = @_;
1.613 albertel 11422: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11423: my ($tmp)=keys(%current_permissions);
11424: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11425: return \%current_permissions;
11426: }
11427:
11428: #---------------------------------------------Get portfolio file access controls
11429:
1.749 raeburn 11430: sub get_access_controls {
1.745 raeburn 11431: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11432: my %access;
11433: my $real_file = $file;
11434: $file =~ s/\.meta$//;
1.745 raeburn 11435: if (defined($file)) {
1.749 raeburn 11436: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11437: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11438: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11439: }
11440: }
1.745 raeburn 11441: } else {
1.749 raeburn 11442: foreach my $key (keys(%{$current_permissions})) {
11443: if ($key =~ /\0accesscontrol$/) {
11444: if (defined($group)) {
11445: if ($key !~ m-^\Q$group\E/-) {
11446: next;
11447: }
11448: }
11449: my ($fullpath) = split(/\0/,$key);
11450: if (ref($$current_permissions{$key}) eq 'HASH') {
11451: foreach my $control (keys(%{$$current_permissions{$key}})) {
11452: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11453: }
11454: }
11455: }
11456: }
11457: }
11458: return %access;
11459: }
11460:
11461: sub modify_access_controls {
11462: my ($file_name,$changes,$domain,$user)=@_;
11463: my ($outcome,$deloutcome);
11464: my %store_permissions;
11465: my %new_values;
11466: my %new_control;
11467: my %translation;
11468: my @deletions = ();
11469: my $now = time;
11470: if (exists($$changes{'activate'})) {
11471: if (ref($$changes{'activate'}) eq 'HASH') {
11472: my @newitems = sort(keys(%{$$changes{'activate'}}));
11473: my $numnew = scalar(@newitems);
11474: for (my $i=0; $i<$numnew; $i++) {
11475: my $newkey = $newitems[$i];
11476: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11477: if ($newkey =~ /^\d+:/) {
11478: $newkey =~ s/^(\d+)/$newid/;
11479: $translation{$1} = $newid;
11480: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11481: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11482: $translation{$1} = $newid;
11483: }
1.749 raeburn 11484: $new_values{$file_name."\0".$newkey} =
11485: $$changes{'activate'}{$newitems[$i]};
11486: $new_control{$newkey} = $now;
11487: }
11488: }
11489: }
11490: my %todelete;
11491: my %changed_items;
11492: foreach my $action ('delete','update') {
11493: if (exists($$changes{$action})) {
11494: if (ref($$changes{$action}) eq 'HASH') {
11495: foreach my $key (keys(%{$$changes{$action}})) {
11496: my ($itemnum) = ($key =~ /^([^:]+):/);
11497: if ($action eq 'delete') {
11498: $todelete{$itemnum} = 1;
11499: } else {
11500: $changed_items{$itemnum} = $key;
11501: }
11502: }
1.745 raeburn 11503: }
11504: }
1.749 raeburn 11505: }
11506: # get lock on access controls for file.
11507: my $lockhash = {
11508: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11509: ':'.$env{'user.domain'},
11510: };
11511: my $tries = 0;
11512: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11513:
1.1172.2.79 raeburn 11514: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11515: $tries ++;
1.1172.2.79 raeburn 11516: sleep(0.1);
1.749 raeburn 11517: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11518: }
11519: if ($gotlock eq 'ok') {
11520: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11521: my ($tmp)=keys(%curr_permissions);
11522: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11523: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11524: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11525: if (ref($curr_controls) eq 'HASH') {
11526: foreach my $control_item (keys(%{$curr_controls})) {
11527: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11528: if (defined($todelete{$itemnum})) {
11529: push(@deletions,$file_name."\0".$control_item);
11530: } else {
11531: if (defined($changed_items{$itemnum})) {
11532: $new_control{$changed_items{$itemnum}} = $now;
11533: push(@deletions,$file_name."\0".$control_item);
11534: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11535: } else {
11536: $new_control{$control_item} = $$curr_controls{$control_item};
11537: }
11538: }
1.745 raeburn 11539: }
11540: }
11541: }
1.970 raeburn 11542: my ($group);
11543: if (&is_course($domain,$user)) {
11544: ($group,my $file) = split(/\//,$file_name,2);
11545: }
1.749 raeburn 11546: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11547: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11548: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11549: # remove lock
11550: my @del_lock = ($file_name."\0".'locked_access_records');
11551: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11552: my $sqlresult =
1.970 raeburn 11553: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11554: $group);
1.749 raeburn 11555: } else {
11556: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11557: }
1.749 raeburn 11558: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11559: }
11560:
1.827 raeburn 11561: sub make_public_indefinitely {
11562: my ($requrl) = @_;
11563: my $now = time;
11564: my $action = 'activate';
11565: my $aclnum = 0;
11566: if (&is_portfolio_url($requrl)) {
11567: my (undef,$udom,$unum,$file_name,$group) =
11568: &parse_portfolio_url($requrl);
11569: my $current_perms = &get_portfile_permissions($udom,$unum);
11570: my %access_controls = &get_access_controls($current_perms,
11571: $group,$file_name);
11572: foreach my $key (keys(%{$access_controls{$file_name}})) {
11573: my ($num,$scope,$end,$start) =
11574: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11575: if ($scope eq 'public') {
11576: if ($start <= $now && $end == 0) {
11577: $action = 'none';
11578: } else {
11579: $action = 'update';
11580: $aclnum = $num;
11581: }
11582: last;
11583: }
11584: }
11585: if ($action eq 'none') {
11586: return 'ok';
11587: } else {
11588: my %changes;
11589: my $newend = 0;
11590: my $newstart = $now;
11591: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11592: $changes{$action}{$newkey} = {
11593: type => 'public',
11594: time => {
11595: start => $newstart,
11596: end => $newend,
11597: },
11598: };
11599: my ($outcome,$deloutcome,$new_values,$translation) =
11600: &modify_access_controls($file_name,\%changes,$udom,$unum);
11601: return $outcome;
11602: }
11603: } else {
11604: return 'invalid';
11605: }
11606: }
11607:
1.745 raeburn 11608: #------------------------------------------------------Get Marked as Read Only
11609:
11610: sub get_marked_as_readonly {
11611: my ($domain,$user,$what,$group) = @_;
11612: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11613: my @readonly_files;
1.629 banghart 11614: my $cmp1=$what;
11615: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11616: while (my ($file_name,$value) = each(%{$current_permissions})) {
11617: if (defined($group)) {
11618: if ($file_name !~ m-^\Q$group\E/-) {
11619: next;
11620: }
11621: }
1.561 banghart 11622: if (ref($value) eq "ARRAY"){
11623: foreach my $stored_what (@{$value}) {
1.629 banghart 11624: my $cmp2=$stored_what;
1.759 albertel 11625: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11626: $cmp2=join('',@{$stored_what});
1.745 raeburn 11627: }
1.629 banghart 11628: if ($cmp1 eq $cmp2) {
1.561 banghart 11629: push(@readonly_files, $file_name);
1.745 raeburn 11630: last;
1.563 banghart 11631: } elsif (!defined($what)) {
11632: push(@readonly_files, $file_name);
1.745 raeburn 11633: last;
1.561 banghart 11634: }
11635: }
1.745 raeburn 11636: }
1.561 banghart 11637: }
11638: return @readonly_files;
11639: }
1.577 banghart 11640: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11641:
1.577 banghart 11642: sub get_marked_as_readonly_hash {
1.745 raeburn 11643: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11644: my %readonly_files;
1.745 raeburn 11645: while (my ($file_name,$value) = each(%{$current_permissions})) {
11646: if (defined($group)) {
11647: if ($file_name !~ m-^\Q$group\E/-) {
11648: next;
11649: }
11650: }
1.577 banghart 11651: if (ref($value) eq "ARRAY"){
11652: foreach my $stored_what (@{$value}) {
1.745 raeburn 11653: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11654: foreach my $lock_descriptor(@{$stored_what}) {
11655: if ($lock_descriptor eq 'graded') {
11656: $readonly_files{$file_name} = 'graded';
11657: } elsif ($lock_descriptor eq 'handback') {
11658: $readonly_files{$file_name} = 'handback';
11659: } else {
11660: if (!exists($readonly_files{$file_name})) {
11661: $readonly_files{$file_name} = 'locked';
11662: }
11663: }
1.745 raeburn 11664: }
1.750 banghart 11665: }
1.577 banghart 11666: }
11667: }
11668: }
11669: return %readonly_files;
11670: }
1.559 banghart 11671: # ------------------------------------------------------------ Unmark as Read Only
11672:
11673: sub unmark_as_readonly {
1.629 banghart 11674: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11675: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11676: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11677: $file_name = &declutter_portfile($file_name);
1.634 albertel 11678: my $symb_crs = $what;
11679: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11680: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11681: my ($tmp)=keys(%current_permissions);
11682: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11683: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11684: foreach my $file (@readonly_files) {
1.759 albertel 11685: my $clean_file = &declutter_portfile($file);
11686: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11687: my $current_locks = $current_permissions{$file};
1.563 banghart 11688: my @new_locks;
11689: my @del_keys;
11690: if (ref($current_locks) eq "ARRAY"){
11691: foreach my $locker (@{$current_locks}) {
1.632 albertel 11692: my $compare=$locker;
1.749 raeburn 11693: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11694: $compare=join('',@{$locker});
1.746 raeburn 11695: if ($compare ne $symb_crs) {
11696: push(@new_locks, $locker);
11697: }
1.563 banghart 11698: }
11699: }
1.650 albertel 11700: if (scalar(@new_locks) > 0) {
1.563 banghart 11701: $current_permissions{$file} = \@new_locks;
11702: } else {
11703: push(@del_keys, $file);
1.613 albertel 11704: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11705: delete($current_permissions{$file});
1.563 banghart 11706: }
11707: }
1.561 banghart 11708: }
1.613 albertel 11709: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11710: return;
11711: }
1.512 banghart 11712:
1.17 www 11713: # ------------------------------------------------------------ Directory lister
11714:
11715: sub dirlist {
1.955 raeburn 11716: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11717: $uri=~s/^\///;
11718: $uri=~s/\/$//;
1.253 stredwic 11719: my ($udom, $uname);
1.955 raeburn 11720: if ($getuserdir) {
1.253 stredwic 11721: $udom = $userdomain;
11722: $uname = $username;
1.955 raeburn 11723: } else {
11724: (undef,$udom,$uname)=split(/\//,$uri);
11725: if(defined($userdomain)) {
11726: $udom = $userdomain;
11727: }
11728: if(defined($username)) {
11729: $uname = $username;
11730: }
1.253 stredwic 11731: }
1.955 raeburn 11732: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11733:
1.955 raeburn 11734: $dirRoot = $perlvar{'lonDocRoot'};
11735: if (defined($getpropath)) {
11736: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11737: $dirRoot =~ s/\/$//;
1.955 raeburn 11738: } elsif (defined($getuserdir)) {
11739: my $subdir=$uname.'__';
11740: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11741: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11742: ."/$udom/$subdir/$uname";
11743: } elsif (defined($alternateRoot)) {
11744: $dirRoot = $alternateRoot;
1.751 banghart 11745: }
1.253 stredwic 11746:
11747: if($udom) {
11748: if($uname) {
1.1135 raeburn 11749: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11750: if ($uhome eq 'no_host') {
11751: return ([],'no_host');
11752: }
1.955 raeburn 11753: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11754: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11755: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11756: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11757: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11758: } else {
11759: @listing_results = map { &unescape($_); } split(/:/,$listing);
11760: }
1.605 matthew 11761: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11762: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11763: @listing_results = split(/:/,$listing);
11764: } else {
11765: @listing_results = map { &unescape($_); } split(/:/,$listing);
11766: }
1.1135 raeburn 11767: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11768: ($listing eq 'rejected') || ($listing eq 'refused') ||
11769: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11770: return ([],$listing);
11771: } else {
11772: return (\@listing_results);
1.1135 raeburn 11773: }
1.955 raeburn 11774: } elsif(!$alternateRoot) {
1.1136 raeburn 11775: my (%allusers,%listerror);
1.841 albertel 11776: my %servers = &get_servers($udom,'library');
1.955 raeburn 11777: foreach my $tryserver (keys(%servers)) {
11778: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11779: &escape($udom),$tryserver);
11780: if ($listing eq 'unknown_cmd') {
11781: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11782: $udom, $tryserver);
11783: } else {
11784: @listing_results = map { &unescape($_); } split(/:/,$listing);
11785: }
1.841 albertel 11786: if ($listing eq 'unknown_cmd') {
11787: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11788: $udom, $tryserver);
11789: @listing_results = split(/:/,$listing);
11790: } else {
11791: @listing_results =
11792: map { &unescape($_); } split(/:/,$listing);
11793: }
1.1136 raeburn 11794: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11795: ($listing eq 'rejected') || ($listing eq 'refused') ||
11796: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11797: $listerror{$tryserver} = $listing;
11798: } else {
1.841 albertel 11799: foreach my $line (@listing_results) {
11800: my ($entry) = split(/&/,$line,2);
11801: $allusers{$entry} = 1;
11802: }
11803: }
1.253 stredwic 11804: }
1.1136 raeburn 11805: my @alluserslist=();
1.800 albertel 11806: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11807: push(@alluserslist,$user.'&user');
1.253 stredwic 11808: }
1.1172.2.80 raeburn 11809: if (!%listerror) {
11810: # no errors
11811: return (\@alluserslist);
11812: } elsif (scalar(keys(%servers)) == 1) {
11813: # one library server, one error
11814: my ($key) = keys(%listerror);
11815: return (\@alluserslist, $listerror{$key});
11816: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11817: # con_lost indicates that we might miss data from at least one
11818: # library server
11819: return (\@alluserslist, 'con_lost');
11820: } else {
11821: # multiple library servers and no con_lost -> data should be
11822: # complete.
11823: return (\@alluserslist);
11824: }
11825:
1.253 stredwic 11826: } else {
1.1136 raeburn 11827: return ([],'missing username');
1.253 stredwic 11828: }
1.955 raeburn 11829: } elsif(!defined($getpropath)) {
1.1136 raeburn 11830: my $path = $perlvar{'lonDocRoot'}.'/res/';
11831: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11832: return (\@all_domains);
1.955 raeburn 11833: } else {
1.1136 raeburn 11834: return ([],'missing domain');
1.275 stredwic 11835: }
11836: }
11837:
11838: # --------------------------------------------- GetFileTimestamp
11839: # This function utilizes dirlist and returns the date stamp for
11840: # when it was last modified. It will also return an error of -1
11841: # if an error occurs
11842:
11843: sub GetFileTimestamp {
1.955 raeburn 11844: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11845: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11846: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11847: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11848: undef,$getuserdir);
11849: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11850: return -1;
11851: }
11852: if (ref($fileref) eq 'ARRAY') {
11853: my @stats = split('&',$fileref->[0]);
1.375 matthew 11854: # @stats contains first the filename, then the stat output
11855: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11856: } else {
11857: return -1;
1.253 stredwic 11858: }
1.26 www 11859: }
11860:
1.712 albertel 11861: sub stat_file {
11862: my ($uri) = @_;
1.787 albertel 11863: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11864:
1.955 raeburn 11865: my ($udom,$uname,$file);
1.712 albertel 11866: if ($uri =~ m-^/(uploaded|editupload)/-) {
11867: ($udom,$uname,$file) =
1.811 albertel 11868: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11869: $file = 'userfiles/'.$file;
11870: }
11871: if ($uri =~ m-^/res/-) {
11872: ($udom,$uname) =
1.807 albertel 11873: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11874: $file = $uri;
11875: }
11876:
11877: if (!$udom || !$uname || !$file) {
11878: # unable to handle the uri
11879: return ();
11880: }
1.956 raeburn 11881: my $getpropath;
11882: if ($file =~ /^userfiles\//) {
11883: $getpropath = 1;
11884: }
1.1136 raeburn 11885: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11886: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11887: return ();
11888: } else {
11889: if (ref($listref) eq 'ARRAY') {
11890: my @stats = split('&',$listref->[0]);
11891: shift(@stats); #filename is first
11892: return @stats;
11893: }
1.712 albertel 11894: }
11895: return ();
11896: }
11897:
1.26 www 11898: # -------------------------------------------------------- Value of a Condition
11899:
1.713 albertel 11900: # gets the value of a specific preevaluated condition
11901: # stored in the string $env{user.state.<cid>}
11902: # or looks up a condition reference in the bighash and if if hasn't
11903: # already been evaluated recurses into docondval to get the value of
11904: # the condition, then memoizing it to
11905: # $env{user.state.<cid>.<condition>}
1.40 www 11906: sub directcondval {
11907: my $number=shift;
1.620 albertel 11908: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11909: &Apache::lonuserstate::evalstate();
11910: }
1.713 albertel 11911: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11912: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11913: } elsif ($number =~ /^_/) {
11914: my $sub_condition;
11915: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11916: &GDBM_READER(),0640)) {
11917: $sub_condition=$bighash{'conditions'.$number};
11918: untie(%bighash);
11919: }
11920: my $value = &docondval($sub_condition);
1.949 raeburn 11921: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11922: return $value;
11923: }
1.620 albertel 11924: if ($env{'user.state.'.$env{'request.course.id'}}) {
11925: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11926: } else {
11927: return 2;
11928: }
11929: }
11930:
1.713 albertel 11931: # get the collection of conditions for this resource
1.26 www 11932: sub condval {
11933: my $condidx=shift;
1.54 www 11934: my $allpathcond='';
1.713 albertel 11935: foreach my $cond (split(/\|/,$condidx)) {
11936: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11937: $allpathcond.=
11938: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11939: }
1.191 harris41 11940: }
1.54 www 11941: $allpathcond=~s/\|$//;
1.713 albertel 11942: return &docondval($allpathcond);
11943: }
11944:
11945: #evaluates an expression of conditions
11946: sub docondval {
11947: my ($allpathcond) = @_;
11948: my $result=0;
11949: if ($env{'request.course.id'}
11950: && defined($allpathcond)) {
11951: my $operand='|';
11952: my @stack;
11953: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11954: if ($chunk eq '(') {
11955: push @stack,($operand,$result);
11956: } elsif ($chunk eq ')') {
11957: my $before=pop @stack;
11958: if (pop @stack eq '&') {
11959: $result=$result>$before?$before:$result;
11960: } else {
11961: $result=$result>$before?$result:$before;
11962: }
11963: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11964: $operand=$chunk;
11965: } else {
11966: my $new=directcondval($chunk);
11967: if ($operand eq '&') {
11968: $result=$result>$new?$new:$result;
11969: } else {
11970: $result=$result>$new?$result:$new;
11971: }
11972: }
11973: }
1.26 www 11974: }
11975: return $result;
1.421 albertel 11976: }
11977:
11978: # ---------------------------------------------------- Devalidate courseresdata
11979:
11980: sub devalidatecourseresdata {
11981: my ($coursenum,$coursedomain)=@_;
11982: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11983: &devalidate_cache_new('courseres',$hashid);
1.28 www 11984: }
11985:
1.763 www 11986:
1.200 www 11987: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11988: #
11989: # Parameters:
11990: # $coursenum - Number of the course.
11991: # $coursedomain - Domain at which the course was created.
11992: # Returns:
11993: # A hash of the course parameters along (I think) with timestamps
11994: # and version info.
1.877 foxr 11995:
1.624 albertel 11996: sub get_courseresdata {
11997: my ($coursenum,$coursedomain)=@_;
1.200 www 11998: my $coursehom=&homeserver($coursenum,$coursedomain);
11999: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12000: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12001: my %dumpreply;
1.417 albertel 12002: unless (defined($cached)) {
1.624 albertel 12003: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12004: $result=\%dumpreply;
1.251 albertel 12005: my ($tmp) = keys(%dumpreply);
12006: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12007: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12008: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12009: return $tmp;
1.416 albertel 12010: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12011: $result=undef;
1.599 albertel 12012: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12013: }
12014: }
1.624 albertel 12015: return $result;
12016: }
12017:
1.633 albertel 12018: sub devalidateuserresdata {
12019: my ($uname,$udom)=@_;
12020: my $hashid="$udom:$uname";
12021: &devalidate_cache_new('userres',$hashid);
12022: }
12023:
1.624 albertel 12024: sub get_userresdata {
12025: my ($uname,$udom)=@_;
12026: #most student don\'t have any data set, check if there is some data
12027: if (&EXT_cache_status($udom,$uname)) { return undef; }
12028:
12029: my $hashid="$udom:$uname";
12030: my ($result,$cached)=&is_cached_new('userres',$hashid);
12031: if (!defined($cached)) {
12032: my %resourcedata=&dump('resourcedata',$udom,$uname);
12033: $result=\%resourcedata;
12034: &do_cache_new('userres',$hashid,$result,600);
12035: }
12036: my ($tmp)=keys(%$result);
12037: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12038: return $result;
12039: }
12040: #error 2 occurs when the .db doesn't exist
12041: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 12042: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12043: &logthis("<font color=\"blue\">WARNING:".
12044: " Trying to get resource data for ".
12045: $uname." at ".$udom.": ".
12046: $tmp."</font>");
12047: }
1.624 albertel 12048: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12049: #&EXT_cache_set($udom,$uname);
12050: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12051: undef($tmp); # not really an error so don't send it back
1.624 albertel 12052: }
12053: return $tmp;
12054: }
1.879 foxr 12055: #----------------------------------------------- resdata - return resource data
12056: # Purpose:
12057: # Return resource data for either users or for a course.
12058: # Parameters:
12059: # $name - Course/user name.
12060: # $domain - Name of the domain the user/course is registered on.
12061: # $type - Type of thing $name is (must be 'course' or 'user'
12062: # @which - Array of names of resources desired.
12063: # Returns:
12064: # The value of the first reasource in @which that is found in the
12065: # resource hash.
12066: # Exceptional Conditions:
12067: # If the $type passed in is not valid (not the string 'course' or
12068: # 'user', an undefined reference is returned.
12069: # If none of the resources are found, an undef is returned
1.624 albertel 12070: sub resdata {
12071: my ($name,$domain,$type,@which)=@_;
12072: my $result;
12073: if ($type eq 'course') {
12074: $result=&get_courseresdata($name,$domain);
12075: } elsif ($type eq 'user') {
12076: $result=&get_userresdata($name,$domain);
12077: }
12078: if (!ref($result)) { return $result; }
1.251 albertel 12079: foreach my $item (@which) {
1.927 albertel 12080: if (defined($result->{$item->[0]})) {
12081: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12082: }
1.250 albertel 12083: }
1.291 albertel 12084: return undef;
1.200 www 12085: }
12086:
1.1172.2.146. .1(raebu 12087:22): sub get_domain_lti {
12088:22): my ($cdom,$context) = @_;
.4(raebu 12089:22): my ($name,$cachename,%lti);
.1(raebu 12090:22): if ($context eq 'consumer') {
12091:22): $name = 'ltitools';
12092:22): } elsif ($context eq 'provider') {
12093:22): $name = 'lti';
.4(raebu 12094:22): } elsif ($context eq 'linkprot') {
12095:22): $name = 'ltisec';
.1(raebu 12096:22): } else {
12097:22): return %lti;
12098:22): }
.4(raebu 12099:22): if ($context eq 'linkprot') {
12100:22): $cachename = $context;
12101:22): } else {
12102:22): $cachename = $name;
12103:22): }
12104:22): my ($result,$cached)=&is_cached_new($cachename,$cdom);
.1(raebu 12105:22): if (defined($cached)) {
12106:22): if (ref($result) eq 'HASH') {
12107:22): %lti = %{$result};
12108:22): }
12109:22): } else {
12110:22): my %domconfig = &get_dom('configuration',[$name],$cdom);
12111:22): if (ref($domconfig{$name}) eq 'HASH') {
.4(raebu 12112:22): if ($context eq 'linkprot') {
12113:22): if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12114:22): %lti = %{$domconfig{$name}{'linkprot'}};
12115:22): }
12116:22): } else {
12117:22): %lti = %{$domconfig{$name}};
12118:22): }
.1(raebu 12119:22): }
12120:22): my $cachetime = 24*60*60;
.4(raebu 12121:22): &do_cache_new($cachename,$cdom,\%lti,$cachetime);
.1(raebu 12122:22): }
12123:22): return %lti;
12124:22): }
12125:22):
12126:22): sub get_course_lti {
.13(raeb 12127:-23): my ($cnum,$cdom,$context) = @_;
12128:-23): my ($name,$cachename,%lti);
12129:-23): if ($context eq 'consumer') {
12130:-23): $name = 'ltitools';
12131:-23): $cachename = 'courseltitools';
12132:-23): } elsif ($context eq 'provider') {
12133:-23): $name = 'lti';
12134:-23): $cachename = 'courselti';
12135:-23): } else {
12136:-23): return %lti;
12137:-23): }
.1(raebu 12138:22): my $hashid=$cdom.'_'.$cnum;
.13(raeb 12139:-23): my ($result,$cached)=&is_cached_new($cachename,$hashid);
.1(raebu 12140:22): if (defined($cached)) {
12141:22): if (ref($result) eq 'HASH') {
.13(raeb 12142:-23): %lti = %{$result};
.1(raebu 12143:22): }
12144:22): } else {
.13(raeb 12145:-23): %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
.1(raebu 12146:22): my $cachetime = 24*60*60;
.13(raeb 12147:-23): &do_cache_new($cachename,$hashid,\%lti,$cachetime);
.1(raebu 12148:22): }
.13(raeb 12149:-23): return %lti;
.1(raebu 12150:22): }
12151:22):
.3(raebu 12152:22): sub courselti_itemid {
12153:22): my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12154:22): my ($chome,$itemid);
12155:22): $chome = &homeserver($cnum,$cdom);
12156:22): return if ($chome eq 'no_host');
12157:22): if (ref($params) eq 'HASH') {
12158:22): my $rep;
12159:22): if (grep { $_ eq $chome } current_machine_ids()) {
12160:22): $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12161:22): } else {
12162:22): my $escurl = &escape($url);
12163:22): my $escmethod = &escape($method);
12164:22): my $items = &freeze_escape($params);
12165:22): $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12166:22): }
12167:22): unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12168:22): ($rep eq 'unknown_cmd')) {
12169:22): $itemid = $rep;
12170:22): }
12171:22): }
12172:22): return $itemid;
12173:22): }
12174:22):
12175:22): sub domainlti_itemid {
12176:22): my ($cdom,$url,$method,$params,$context) = @_;
12177:22): my ($primary_id,$itemid);
12178:22): $primary_id = &domain($cdom,'primary');
12179:22): return if ($primary_id eq '');
12180:22): if (ref($params) eq 'HASH') {
12181:22): my $rep;
12182:22): if (grep { $_ eq $primary_id } current_machine_ids()) {
12183:22): $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12184:22): } else {
12185:22): my $cnum = '';
12186:22): my $escurl = &escape($url);
12187:22): my $escmethod = &escape($method);
12188:22): my $items = &freeze_escape($params);
12189:22): $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12190:22): }
12191:22): unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12192:22): ($rep eq 'unknown_cmd')) {
12193:22): $itemid = $rep;
12194:22): }
12195:22): }
12196:22): return $itemid;
12197:22): }
12198:22):
.15(raeb 12199:-23): sub get_ltitools_id {
12200:-23): my ($context,$cdom,$cnum,$title) = @_;
12201:-23): my ($lockhash,$tries,$gotlock,$id,$error);
12202:-23):
12203:-23): # get lock on ltitools db
12204:-23): $lockhash = {
12205:-23): lock => $env{'user.name'}.
12206:-23): ':'.$env{'user.domain'},
12207:-23): };
12208:-23): $tries = 0;
12209:-23): if ($context eq 'domain') {
12210:-23): $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12211:-23): } else {
12212:-23): $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12213:-23): }
12214:-23): while (($gotlock ne 'ok') && ($tries<10)) {
12215:-23): $tries ++;
12216:-23): sleep (0.1);
12217:-23): if ($context eq 'domain') {
12218:-23): $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12219:-23): } else {
12220:-23): $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12221:-23): }
12222:-23): }
12223:-23): if ($gotlock eq 'ok') {
12224:-23): my %currids;
12225:-23): if ($context eq 'domain') {
12226:-23): %currids = &dump_dom('ltitools',$cdom);
12227:-23): } else {
12228:-23): %currids = &dump('ltitools',$cdom,$cnum);
12229:-23): }
12230:-23): if ($currids{'lock'}) {
12231:-23): delete($currids{'lock'});
12232:-23): if (keys(%currids)) {
12233:-23): my @curr = sort { $a <=> $b } keys(%currids);
12234:-23): if ($curr[-1] =~ /^\d+$/) {
12235:-23): $id = 1 + $curr[-1];
12236:-23): }
12237:-23): } else {
12238:-23): $id = 1;
12239:-23): }
12240:-23): if ($id) {
12241:-23): if ($context eq 'domain') {
12242:-23): unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12243:-23): $error = 'nostore';
12244:-23): }
12245:-23): } else {
12246:-23): unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12247:-23): $error = 'nostore';
12248:-23): }
12249:-23): }
12250:-23): } else {
12251:-23): $error = 'nonumber';
12252:-23): }
12253:-23): }
12254:-23): my $dellockoutcome;
12255:-23): if ($context eq 'domain') {
12256:-23): $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12257:-23): } else {
12258:-23): $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12259:-23): }
12260:-23): } else {
12261:-23): $error = 'nolock';
12262:-23): }
12263:-23): return ($id,$error);
12264:-23): }
12265:-23):
.9(raebu 12266:23): sub count_supptools {
12267:23): my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31 raeburn 12268: my $hashid=$cnum.':'.$cdom;
1.1172.2.146. .9(raebu 12269:23): my ($numexttools,$cached);
1.1172.2.31 raeburn 12270: unless ($ignorecache) {
1.1172.2.146. .9(raebu 12271:23): ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31 raeburn 12272: }
12273: unless (defined($cached)) {
12274: my $chome=&homeserver($cnum,$cdom);
1.1172.2.146. .9(raebu 12275:23): $numexttools = 0;
1.1172.2.31 raeburn 12276: unless ($chome eq 'no_host') {
1.1172.2.146. .9(raebu 12277:23): my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12278:23): if (ref($supplemental) eq 'HASH') {
12279:23): if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12280:23): foreach my $key (keys(%{$supplemental->{'ids'}})) {
12281:23): if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12282:23): $numexttools ++;
12283:23): }
12284:23): }
12285:23): }
12286:23): }
1.1172.2.31 raeburn 12287: }
1.1172.2.146. .9(raebu 12288:23): &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31 raeburn 12289: }
1.1172.2.146. .9(raebu 12290:23): return $numexttools;
12291:23): }
12292:23):
12293:23): sub has_unhidden_suppfiles {
12294:23): my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12295:23): my $hashid=$cnum.':'.$cdom;
12296:23): my ($showsupp,$cached);
12297:23): unless ($ignorecache) {
12298:23): ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12299:23): }
12300:23): unless (defined($cached)) {
12301:23): my $chome=&homeserver($cnum,$cdom);
12302:23): unless ($chome eq 'no_host') {
12303:23): my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12304:23): if (ref($supplemental) eq 'HASH') {
12305:23): if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12306:23): foreach my $key (keys(%{$supplemental->{'ids'}})) {
12307:23): next if ($key =~ /\.sequence$/);
12308:23): if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12309:23): foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12310:23): unless ($supplemental->{'hidden'}->{$id}) {
12311:23): $showsupp = 1;
12312:23): last;
12313:23): }
12314:23): }
12315:23): }
12316:23): last if ($showsupp);
12317:23): }
12318:23): }
12319:23): }
12320:23): }
12321:23): &do_cache_new('showsupp',$hashid,$showsupp,600);
12322:23): }
12323:23): return $showsupp;
1.1172.2.31 raeburn 12324: }
12325:
1.379 matthew 12326: #
12327: # EXT resource caching routines
12328: #
12329:
1.1172.2.146. .1(raebu 12330:22): {
12331:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12332:22): #
12333:22): # The course for which we cache
12334:22): my $cachedmapkey='';
12335:22): # The cached recursive maps for this course
12336:22): my %cachedmaps=();
12337:22): # When this was last done
12338:22): my $cachedmaptime='';
12339:22):
1.379 matthew 12340: sub clear_EXT_cache_status {
1.383 albertel 12341: &delenv('cache.EXT.');
1.379 matthew 12342: }
12343:
12344: sub EXT_cache_status {
12345: my ($target_domain,$target_user) = @_;
1.383 albertel 12346: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12347: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12348: # We know already the user has no data
12349: return 1;
12350: } else {
12351: return 0;
12352: }
12353: }
12354:
12355: sub EXT_cache_set {
12356: my ($target_domain,$target_user) = @_;
1.383 albertel 12357: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12358: #&appenv({$cachename => time});
1.379 matthew 12359: }
12360:
1.28 www 12361: # --------------------------------------------------------- Value of a Variable
1.58 www 12362: sub EXT {
1.715 albertel 12363:
1.1172.2.28 raeburn 12364: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12365: unless ($varname) { return ''; }
1.218 albertel 12366: #get real user name/domain, courseid and symb
12367: my $courseid;
1.359 albertel 12368: my $publicuser;
1.427 www 12369: if ($symbparm) {
12370: $symbparm=&get_symb_from_alias($symbparm);
12371: }
1.218 albertel 12372: if (!($uname && $udom)) {
1.790 albertel 12373: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12374: if (!$symbparm) { $symbparm=$cursymb; }
12375: } else {
1.620 albertel 12376: $courseid=$env{'request.course.id'};
1.218 albertel 12377: }
1.48 www 12378: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12379: my $rest;
1.320 albertel 12380: if (defined($therest[0])) {
1.48 www 12381: $rest=join('.',@therest);
12382: } else {
12383: $rest='';
12384: }
1.320 albertel 12385:
1.57 www 12386: my $qualifierrest=$qualifier;
12387: if ($rest) { $qualifierrest.='.'.$rest; }
12388: my $spacequalifierrest=$space;
12389: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12390: if ($realm eq 'user') {
1.48 www 12391: # --------------------------------------------------------------- user.resource
12392: if ($space eq 'resource') {
1.651 albertel 12393: if ( (defined($Apache::lonhomework::parsing_a_problem)
12394: || defined($Apache::lonhomework::parsing_a_task))
12395: &&
1.1172.2.142 raeburn 12396: ($symbparm eq &symbread()) ) {
1.744 albertel 12397: # if we are in the middle of processing the resource the
12398: # get the value we are planning on committing
12399: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12400: return $Apache::lonhomework::results{$qualifierrest};
12401: } else {
12402: return $Apache::lonhomework::history{$qualifierrest};
12403: }
1.335 albertel 12404: } else {
1.359 albertel 12405: my %restored;
1.620 albertel 12406: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12407: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12408: } else {
12409: %restored=&restore($symbparm,$courseid,$udom,$uname);
12410: }
1.335 albertel 12411: return $restored{$qualifierrest};
12412: }
1.48 www 12413: # ----------------------------------------------------------------- user.access
12414: } elsif ($space eq 'access') {
1.218 albertel 12415: # FIXME - not supporting calls for a specific user
1.48 www 12416: return &allowed($qualifier,$rest);
12417: # ------------------------------------------ user.preferences, user.environment
12418: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12419: if (($uname eq $env{'user.name'}) &&
12420: ($udom eq $env{'user.domain'})) {
12421: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12422: } else {
1.359 albertel 12423: my %returnhash;
12424: if (!$publicuser) {
12425: %returnhash=&userenvironment($udom,$uname,
12426: $qualifierrest);
12427: }
1.218 albertel 12428: return $returnhash{$qualifierrest};
12429: }
1.48 www 12430: # ----------------------------------------------------------------- user.course
12431: } elsif ($space eq 'course') {
1.218 albertel 12432: # FIXME - not supporting calls for a specific user
1.620 albertel 12433: return $env{join('.',('request.course',$qualifier))};
1.48 www 12434: # ------------------------------------------------------------------- user.role
12435: } elsif ($space eq 'role') {
1.218 albertel 12436: # FIXME - not supporting calls for a specific user
1.620 albertel 12437: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12438: if ($qualifier eq 'value') {
12439: return $role;
12440: } elsif ($qualifier eq 'extent') {
12441: return $where;
12442: }
12443: # ----------------------------------------------------------------- user.domain
12444: } elsif ($space eq 'domain') {
1.218 albertel 12445: return $udom;
1.48 www 12446: # ------------------------------------------------------------------- user.name
12447: } elsif ($space eq 'name') {
1.218 albertel 12448: return $uname;
1.48 www 12449: # ---------------------------------------------------- Any other user namespace
1.29 www 12450: } else {
1.359 albertel 12451: my %reply;
12452: if (!$publicuser) {
12453: %reply=&get($space,[$qualifierrest],$udom,$uname);
12454: }
12455: return $reply{$qualifierrest};
1.48 www 12456: }
1.236 www 12457: } elsif ($realm eq 'query') {
12458: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12459: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12460: [$spacequalifierrest]);
1.620 albertel 12461: return $env{'form.'.$spacequalifierrest};
1.236 www 12462: } elsif ($realm eq 'request') {
1.48 www 12463: # ------------------------------------------------------------- request.browser
12464: if ($space eq 'browser') {
1.1145 bisitz 12465: return $env{'browser.'.$qualifier};
1.57 www 12466: # ------------------------------------------------------------ request.filename
12467: } else {
1.620 albertel 12468: return $env{'request.'.$spacequalifierrest};
1.29 www 12469: }
1.28 www 12470: } elsif ($realm eq 'course') {
1.48 www 12471: # ---------------------------------------------------------- course.description
1.620 albertel 12472: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12473: } elsif ($realm eq 'resource') {
1.165 www 12474:
1.620 albertel 12475: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12476: if (!$symbparm) { $symbparm=&symbread(); }
12477: }
1.693 albertel 12478:
1.1172.2.30 raeburn 12479: if ($qualifier eq '') {
12480: if ($space eq 'title') {
12481: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12482: return &gettitle($symbparm);
12483: }
1.693 albertel 12484:
1.1172.2.30 raeburn 12485: if ($space eq 'map') {
12486: my ($map) = &decode_symb($symbparm);
12487: return &symbread($map);
12488: }
12489: if ($space eq 'maptitle') {
12490: my ($map) = &decode_symb($symbparm);
12491: return &gettitle($map);
12492: }
12493: if ($space eq 'filename') {
12494: if ($symbparm) {
12495: return &clutter((&decode_symb($symbparm))[2]);
12496: }
12497: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12498: }
1.1172.2.30 raeburn 12499:
12500: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12501: if ($space eq 'visibleparts') {
12502: my $navmap = Apache::lonnavmaps::navmap->new();
12503: my $item;
12504: if (ref($navmap)) {
12505: my $res = $navmap->getBySymb($symbparm);
12506: my $parts = $res->parts();
12507: if (ref($parts) eq 'ARRAY') {
12508: $item = join(',',@{$parts});
12509: }
12510: undef($navmap);
12511: }
12512: return $item;
12513: }
12514: }
12515: }
1.693 albertel 12516:
12517: my ($section, $group, @groups);
1.593 albertel 12518: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 12519: if (($courseid eq '') && ($cid)) {
12520: $courseid = $cid;
12521: }
12522: if (($symbparm && $courseid) &&
12523: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12524:
1.218 albertel 12525: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12526:
1.60 www 12527: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12528: my $symbp=$symbparm;
1.735 albertel 12529: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12530:
12531: my $symbparm=$symbp.'.'.$spacequalifierrest;
12532: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12533:
1.620 albertel 12534: if (($env{'user.name'} eq $uname) &&
12535: ($env{'user.domain'} eq $udom)) {
12536: $section=$env{'request.course.sec'};
1.733 raeburn 12537: @groups = split(/:/,$env{'request.course.groups'});
12538: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12539: } else {
1.539 albertel 12540: if (! defined($usection)) {
1.551 albertel 12541: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12542: } else {
12543: $section = $usection;
12544: }
1.733 raeburn 12545: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12546: }
12547:
12548: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12549: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12550: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12551:
1.593 albertel 12552: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12553: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 12554: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12555:
1.60 www 12556: # ----------------------------------------------------------- first, check user
1.624 albertel 12557:
12558: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 12559: ([$courselevelr,'resource'],
12560: [$courselevelm,'map' ],
12561: [$courselevel, 'course' ]));
1.931 albertel 12562: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12563:
1.594 albertel 12564: # ------------------------------------------------ second, check some of course
1.684 raeburn 12565: my $coursereply;
1.691 raeburn 12566: if (@groups > 0) {
12567: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12568: $mapparm,$spacequalifierrest);
1.927 albertel 12569: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12570: }
1.96 www 12571:
1.684 raeburn 12572: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12573: $env{'course.'.$courseid.'.domain'},
12574: 'course',
12575: ([$seclevelr, 'resource'],
12576: [$seclevelm, 'map' ],
12577: [$seclevel, 'course' ],
12578: [$courselevelr,'resource']));
12579: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12580:
1.60 www 12581: # ------------------------------------------------------ third, check map parms
1.218 albertel 12582: my %parmhash=();
12583: my $thisparm='';
12584: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12585: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12586: &GDBM_READER(),0640)) {
1.218 albertel 12587: $thisparm=$parmhash{$symbparm};
12588: untie(%parmhash);
12589: }
1.927 albertel 12590: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12591: }
1.594 albertel 12592: # ------------------------------------------ fourth, look in resource metadata
1.71 www 12593:
1.1172.2.146. .13(raeb 12594:-23): my $what = $spacequalifierrest;
12595:-23): $what=~s/\./\_/;
12596:-23): my $filename;
1.282 albertel 12597: if (!$symbparm) { $symbparm=&symbread(); }
12598: if ($symbparm) {
1.409 www 12599: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12600: } else {
1.620 albertel 12601: $filename=$env{'request.filename'};
1.282 albertel 12602: }
1.1172.2.146. .13(raeb 12603:-23): my $toolsymb;
12604:-23): if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12605:-23): $toolsymb = $symbparm;
12606:-23): }
12607:-23): my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12608: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146. .13(raeb 12609:-23): $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12610: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12611:
1.1172.2.146. .13(raeb 12612:-23): # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12613: if ($symbparm && defined($courseid) &&
1.620 albertel 12614: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12615: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12616: $env{'course.'.$courseid.'.domain'},
12617: 'course',
1.927 albertel 12618: ([$courselevelm,'map' ],
12619: [$courselevel, 'course']));
12620: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12621: }
1.145 www 12622: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12623: unless ($space eq '0') {
1.336 albertel 12624: my @parts=split(/_/,$space);
12625: my $id=pop(@parts);
12626: my $part=join('_',@parts);
12627: if ($part eq '') { $part='0'; }
1.927 albertel 12628: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12629: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12630: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12631: }
1.395 albertel 12632: if ($recurse) { return undef; }
1.1172.2.146. .13(raeb 12633:-23): my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12634: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12635: # ---------------------------------------------------- Any other user namespace
12636: } elsif ($realm eq 'environment') {
12637: # ----------------------------------------------------------------- environment
1.620 albertel 12638: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12639: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12640: } else {
1.770 albertel 12641: if ($uname eq 'anonymous' && $udom eq '') {
12642: return '';
12643: }
1.219 albertel 12644: my %returnhash=&userenvironment($udom,$uname,
12645: $spacequalifierrest);
12646: return $returnhash{$spacequalifierrest};
12647: }
1.28 www 12648: } elsif ($realm eq 'system') {
1.48 www 12649: # ----------------------------------------------------------------- system.time
12650: if ($space eq 'time') {
12651: return time;
12652: }
1.696 albertel 12653: } elsif ($realm eq 'server') {
12654: # ----------------------------------------------------------------- system.time
12655: if ($space eq 'name') {
12656: return $ENV{'SERVER_NAME'};
12657: }
1.1172.2.146. .1(raebu 12658:22): } elsif ($realm eq 'client') {
12659:22): if ($space eq 'remote_addr') {
12660:22): return &get_requestor_ip();
12661:22): }
1.28 www 12662: }
1.48 www 12663: return '';
1.61 www 12664: }
12665:
1.927 albertel 12666: sub get_reply {
12667: my ($reply_value) = @_;
1.940 raeburn 12668: if (ref($reply_value) eq 'ARRAY') {
12669: if (wantarray) {
12670: return @$reply_value;
12671: }
12672: return $reply_value->[0];
12673: } else {
12674: return $reply_value;
1.927 albertel 12675: }
12676: }
12677:
1.691 raeburn 12678: sub check_group_parms {
12679: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
12680: my @groupitems = ();
12681: my $resultitem;
1.927 albertel 12682: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 12683: foreach my $group (@{$groups}) {
12684: foreach my $level (@levels) {
1.927 albertel 12685: my $item = $courseid.'.['.$group.'].'.$level->[0];
12686: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12687: }
12688: }
12689: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12690: $env{'course.'.$courseid.'.domain'},
12691: 'course',@groupitems);
12692: return $coursereply;
12693: }
12694:
1.1172.2.146. .1(raebu 12695:22): sub get_map_hierarchy {
12696:22): my ($mapname,$courseid) = @_;
12697:22): my @recurseup = ();
12698:22): if ($mapname) {
12699:22): if (($cachedmapkey eq $courseid) &&
12700:22): (abs($cachedmaptime-time)<5)) {
12701:22): if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12702:22): return @{$cachedmaps{$mapname}};
12703:22): }
12704:22): }
12705:22): my $navmap = Apache::lonnavmaps::navmap->new();
12706:22): if (ref($navmap)) {
12707:22): @recurseup = $navmap->recurseup_maps($mapname);
12708:22): undef($navmap);
12709:22): $cachedmaps{$mapname} = \@recurseup;
12710:22): $cachedmaptime=time;
12711:22): $cachedmapkey=$courseid;
12712:22): }
12713:22): }
12714:22): return @recurseup;
12715:22): }
12716:22):
.2(raebu 12717:22): }
.1(raebu 12718:22):
1.691 raeburn 12719: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12720: my ($courseid,@groups) = @_;
12721: @groups = sort(@groups);
1.691 raeburn 12722: return @groups;
12723: }
12724:
1.395 albertel 12725: sub packages_tab_default {
1.1172.2.146. .13(raeb 12726:-23): my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12727: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12728:
12729: my (@extension,@specifics,$do_default);
1.1172.2.146. .13(raeb 12730:-23): foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12731: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12732: if ($pack_type eq 'default') {
12733: $do_default=1;
12734: } elsif ($pack_type eq 'extension') {
12735: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12736: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12737: # only look at packages defaults for packages that this id is
1.738 albertel 12738: push(@specifics,[$package,$pack_type,$pack_part]);
12739: }
12740: }
12741: # first look for a package that matches the requested part id
12742: foreach my $package (@specifics) {
12743: my (undef,$pack_type,$pack_part)=@{$package};
12744: next if ($pack_part ne $part);
12745: if (defined($packagetab{"$pack_type&$name&default"})) {
12746: return $packagetab{"$pack_type&$name&default"};
12747: }
12748: }
12749: # look for any possible matching non extension_ package
12750: foreach my $package (@specifics) {
12751: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12752: if (defined($packagetab{"$pack_type&$name&default"})) {
12753: return $packagetab{"$pack_type&$name&default"};
12754: }
1.585 albertel 12755: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12756: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12757: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12758: }
12759: }
1.738 albertel 12760: # look for any posible extension_ match
12761: foreach my $package (@extension) {
12762: my ($package,$pack_type)=@{$package};
12763: if (defined($packagetab{"$pack_type&$name&default"})) {
12764: return $packagetab{"$pack_type&$name&default"};
12765: }
12766: if (defined($packagetab{$package."&$name&default"})) {
12767: return $packagetab{$package."&$name&default"};
12768: }
12769: }
12770: # look for a global default setting
12771: if ($do_default && defined($packagetab{"default&$name&default"})) {
12772: return $packagetab{"default&$name&default"};
12773: }
1.395 albertel 12774: return undef;
12775: }
12776:
1.334 albertel 12777: sub add_prefix_and_part {
12778: my ($prefix,$part)=@_;
12779: my $keyroot;
12780: if (defined($prefix) && $prefix !~ /^__/) {
12781: # prefix that has a part already
12782: $keyroot=$prefix;
12783: } elsif (defined($prefix)) {
12784: # prefix that is missing a part
12785: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12786: } else {
12787: # no prefix at all
12788: if (defined($part)) { $keyroot='_'.$part; }
12789: }
12790: return $keyroot;
12791: }
12792:
1.71 www 12793: # ---------------------------------------------------------------- Get metadata
12794:
1.599 albertel 12795: my %metaentry;
1.1070 www 12796: my %importedpartids;
1.1172.2.99 raeburn 12797: my %importedrespids;
1.71 www 12798: sub metadata {
1.1172.2.146. .13(raeb 12799:-23): my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12800: $uri=&declutter($uri);
1.288 albertel 12801: # if it is a non metadata possible uri return quickly
1.529 albertel 12802: if (($uri eq '') ||
12803: (($uri =~ m|^/*adm/|) &&
1.1172.2.146. .1(raebu 12804:22): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12805: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12806: return undef;
12807: }
1.1172.2.49 raeburn 12808: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12809: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12810: return undef;
1.288 albertel 12811: }
1.73 www 12812: my $filename=$uri;
12813: $uri=~s/\.meta$//;
1.172 www 12814: #
12815: # Is the metadata already cached?
1.177 www 12816: # Look at timestamp of caching
1.172 www 12817: # Everything is cached by the main uri, libraries are never directly cached
12818: #
1.428 albertel 12819: if (!defined($liburi)) {
1.599 albertel 12820: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12821: if (defined($cached)) { return $result->{':'.$what}; }
12822: }
1.1172.2.146. .13(raeb 12823:-23):
12824:-23): #
12825:-23): # If the uri is for an external tool the file from
12826:-23): # which metadata should be retrieved depends on whether
12827:-23): # the tool had been configured to be gradable (set in the Course
12828:-23): # Editor or Resource Editor).
12829:-23): #
12830:-23): # If a valid symb has been included as the third arg in the call
12831:-23): # to &metadata() that can be used to retrieve the value of
12832:-23): # parameter_0_gradable set for the resource, and included in the
12833:-23): # uploaded map containing the tool. The value is retrieved via
12834:-23): # &EXT(), if a valid symb is available. Otherwise the value of
12835:-23): # gradable in the exttool_$marker.db file for the tool instance
12836:-23): # is retrieved via &get().
12837:-23): #
12838:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
12839:-23): # hiddenresource and encrypturl (during course initialization)
12840:-23): # the map-level parameter for resource.0.gradable included in the
12841:-23): # uploaded map containing the tool will not yet have been stored
12842:-23): # in the user_course_parms.db file for the user's session, so in
12843:-23): # this case fall back to retrieving gradable status from the
12844:-23): # exttool_$marker.db file.
12845:-23): #
12846:-23): # In order to avoid an infinite loop, &metadata() will return
12847:-23): # before a call to &EXT(), if the uri is for an external tool
12848:-23): # and the $what for which metadata is being requested is
12849:-23): # parameter_0_gradable or 0_gradable.
12850:-23): #
12851:-23):
12852:-23): if ($uri =~ /ext\.tool$/) {
12853:-23): if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12854:-23): return;
12855:-23): } else {
12856:-23): my ($checked,$use_passback);
12857:-23): if ($toolsymb ne '') {
12858:-23): (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12859:-23): if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12860:-23): $checked = 1;
12861:-23): if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12862:-23): $use_passback = 1;
12863:-23): }
12864:-23): }
12865:-23): }
12866:-23): unless ($checked) {
12867:-23): my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12868:-23): $marker=~s/\D//g;
12869:-23): if ($marker) {
12870:-23): my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12871:-23): $use_passback = $toolsettings{'gradable'};
12872:-23): }
12873:-23): }
12874:-23): if ($use_passback) {
12875:-23): $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12876:-23): } else {
12877:-23): $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12878:-23): }
12879:-23): }
12880:-23): }
12881:-23):
1.428 albertel 12882: {
1.1069 www 12883: # Imported parts would go here
1.1172.2.99 raeburn 12884: my @origfiletagids=();
1.1069 www 12885: my $importedparts=0;
1.1172.2.99 raeburn 12886:
12887: # Imported responseids would go here
12888: my $importedresponses=0;
1.172 www 12889: #
12890: # Is this a recursive call for a library?
12891: #
1.599 albertel 12892: # if (! exists($metacache{$uri})) {
12893: # $metacache{$uri}={};
12894: # }
1.924 albertel 12895: my $cachetime = 60*60;
1.171 www 12896: if ($liburi) {
12897: $liburi=&declutter($liburi);
12898: $filename=$liburi;
1.401 bowersj2 12899: } else {
1.599 albertel 12900: &devalidate_cache_new('meta',$uri);
12901: undef(%metaentry);
1.401 bowersj2 12902: }
1.140 www 12903: my %metathesekeys=();
1.73 www 12904: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12905: my $metastring;
1.1140 www 12906: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12907: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12908: $metastring =
1.929 albertel 12909: &Apache::lonnet::ssi_body($which,
1.924 albertel 12910: ('grade_target' => 'meta'));
12911: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12912: } elsif (($uri !~ m -^(editupload)/-) &&
12913: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12914: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12915: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12916: $metastring=&getfile($file);
1.489 albertel 12917: }
1.208 albertel 12918: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12919: my $token;
1.140 www 12920: undef %metathesekeys;
1.71 www 12921: while ($token=$parser->get_token) {
1.339 albertel 12922: if ($token->[0] eq 'S') {
12923: if (defined($token->[2]->{'package'})) {
1.172 www 12924: #
12925: # This is a package - get package info
12926: #
1.339 albertel 12927: my $package=$token->[2]->{'package'};
12928: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12929: if (defined($token->[2]->{'id'})) {
12930: $keyroot.='_'.$token->[2]->{'id'};
12931: }
1.599 albertel 12932: if ($metaentry{':packages'}) {
12933: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12934: } else {
1.599 albertel 12935: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12936: }
1.736 albertel 12937: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12938: my $part=$keyroot;
12939: $part=~s/^\_//;
1.736 albertel 12940: if ($pack_entry=~/^\Q$package\E\&/ ||
12941: $pack_entry=~/^\Q$package\E_0\&/) {
12942: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12943: # ignore package.tab specified default values
12944: # here &package_tab_default() will fetch those
12945: if ($subp eq 'default') { next; }
1.736 albertel 12946: my $value=$packagetab{$pack_entry};
1.432 albertel 12947: my $unikey;
12948: if ($pack =~ /_0$/) {
12949: $unikey='parameter_0_'.$name;
12950: $part=0;
12951: } else {
12952: $unikey='parameter'.$keyroot.'_'.$name;
12953: }
1.339 albertel 12954: if ($subp eq 'display') {
12955: $value.=' [Part: '.$part.']';
12956: }
1.599 albertel 12957: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12958: $metathesekeys{$unikey}=1;
1.599 albertel 12959: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12960: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12961: }
1.599 albertel 12962: if (defined($metaentry{':'.$unikey.'.default'})) {
12963: $metaentry{':'.$unikey}=
12964: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12965: }
1.339 albertel 12966: }
12967: }
12968: } else {
1.172 www 12969: #
12970: # This is not a package - some other kind of start tag
1.339 albertel 12971: #
12972: my $entry=$token->[1];
1.1068 www 12973: my $unikey='';
1.175 www 12974:
1.339 albertel 12975: if ($entry eq 'import') {
1.175 www 12976: #
12977: # Importing a library here
1.339 albertel 12978: #
1.1067 www 12979: my $location=$parser->get_text('/import');
12980: my $dir=$filename;
12981: $dir=~s|[^/]*$||;
12982: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12983:
12984: my $importid=$token->[2]->{'id'};
1.1068 www 12985: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12986: #
12987: # Check metadata for imported file to
12988: # see if it contained response items
12989: #
12990: my %currmetaentry = %metaentry;
12991: my $libresponseorder = &metadata($location,'responseorder');
12992: my $origfile;
12993: if ($libresponseorder ne '') {
12994: if ($#origfiletagids<0) {
12995: undef(%importedrespids);
12996: undef(%importedpartids);
12997: }
12998: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12999: if (@{$importedrespids{$importid}} > 0) {
13000: $importedresponses = 1;
13001: # We need to get the original file and the imported file to get the response order correct
13002: # Load and inspect original file
13003: if ($#origfiletagids<0) {
13004: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13005: $origfile=&getfile($origfilelocation);
13006: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13007: }
13008: }
13009: }
13010: # Do not overwrite contents of %metaentry hash for resource itself with
13011: # hash populated for imported library file
13012: %metaentry = %currmetaentry;
13013: undef(%currmetaentry);
1.1068 www 13014: if ($importmode eq 'problem') {
1.1069 www 13015: # Import as problem/response
1.1068 www 13016: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13017: } elsif ($importmode eq 'part') {
13018: # Import as part(s)
1.1069 www 13019: $importedparts=1;
13020: # We need to get the original file and the imported file to get the part order correct
13021: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 13022: # Load and inspect original file if we didn't do that already
13023: if ($#origfiletagids<0) {
13024: undef(%importedrespids);
13025: undef(%importedpartids);
13026: if ($origfile eq '') {
13027: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13028: $origfile=&getfile($origfilelocation);
13029: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13030: }
1.1070 www 13031: }
13032:
1.1069 www 13033: # Load and inspect imported file
13034: my $impfile=&getfile($location);
13035: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13036: if ($#impfilepartids>=0) {
13037: # This problem had parts
1.1070 www 13038: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13039: } else {
13040: # Importing by turning a single problem into a problem part
13041: # It gets the import-tags ID as part-ID
13042: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13043: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13044: }
1.1068 www 13045: } else {
13046: # Normal import
13047: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13048: if (defined($token->[2]->{'id'})) {
13049: $unikey.='_'.$token->[2]->{'id'};
13050: }
1.1067 www 13051: }
13052:
1.339 albertel 13053: if ($depthcount<20) {
1.736 albertel 13054: my $metadata =
1.1172.2.146. .13(raeb 13055:-23): &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13056: $depthcount+1);
13057: foreach my $meta (split(',',$metadata)) {
13058: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13059: $metathesekeys{$meta}=1;
1.339 albertel 13060: }
1.1068 www 13061:
13062: }
1.1067 www 13063: } else {
13064: #
13065: # Not importing, some other kind of non-package, non-library start tag
13066: #
13067: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13068: if (defined($token->[2]->{'id'})) {
13069: $unikey.='_'.$token->[2]->{'id'};
13070: }
1.339 albertel 13071: if (defined($token->[2]->{'name'})) {
13072: $unikey.='_'.$token->[2]->{'name'};
13073: }
13074: $metathesekeys{$unikey}=1;
1.736 albertel 13075: foreach my $param (@{$token->[3]}) {
13076: $metaentry{':'.$unikey.'.'.$param} =
13077: $token->[2]->{$param};
1.339 albertel 13078: }
13079: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13080: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13081: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13082: # only ws inside the tag, and not in default, so use default
13083: # as value
1.599 albertel 13084: $metaentry{':'.$unikey}=$default;
1.908 albertel 13085: } elsif ( $internaltext =~ /\S/ ) {
13086: # something interesting inside the tag
13087: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13088: } else {
1.908 albertel 13089: # no interesting values, don't set a default
1.339 albertel 13090: }
1.172 www 13091: # end of not-a-package not-a-library import
1.339 albertel 13092: }
1.172 www 13093: # end of not-a-package start tag
1.339 albertel 13094: }
1.172 www 13095: # the next is the end of "start tag"
1.339 albertel 13096: }
13097: }
1.483 albertel 13098: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13099: $extension = lc($extension);
13100: if ($extension eq 'htm') { $extension='html'; }
13101:
1.737 albertel 13102: foreach my $key (keys(%packagetab)) {
1.483 albertel 13103: #no specific packages #how's our extension
13104: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13105: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13106: \%metathesekeys);
13107: }
1.883 albertel 13108:
13109: if (!exists($metaentry{':packages'})
13110: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13111: foreach my $key (keys(%packagetab)) {
1.483 albertel 13112: #no specific packages well let's get default then
13113: if ($key!~/^default&/) { next; }
1.488 albertel 13114: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13115: \%metathesekeys);
13116: }
13117: }
1.338 www 13118: # are there custom rights to evaluate
1.599 albertel 13119: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13120:
1.338 www 13121: #
13122: # Importing a rights file here
1.339 albertel 13123: #
13124: unless ($depthcount) {
1.599 albertel 13125: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13126: my $dir=$filename;
13127: $dir=~s|[^/]*$||;
13128: $location=&filelocation($dir,$location);
1.736 albertel 13129: my $rights_metadata =
1.1172.2.146. .13(raeb 13130:-23): &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13131: $depthcount+1);
13132: foreach my $rights (split(',',$rights_metadata)) {
13133: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13134: $metathesekeys{$rights}=1;
1.339 albertel 13135: }
13136: }
13137: }
1.737 albertel 13138: # uniqifiy package listing
13139: my %seen;
13140: my @uniq_packages =
13141: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13142: $metaentry{':packages'} = join(',',@uniq_packages);
13143:
1.1172.2.99 raeburn 13144: if (($importedresponses) || ($importedparts)) {
13145: if ($importedparts) {
1.1070 www 13146: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 13147: $metaentry{':partorder'}='';
13148: $metathesekeys{'partorder'}=1;
13149: }
13150: if ($importedresponses) {
13151: # We had imported responses and need to rebuild responseorder
13152: $metaentry{':responseorder'}='';
13153: $metathesekeys{'responseorder'}=1;
13154: }
13155: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13156: my $origid = $origfiletagids[$index+1];
13157: if ($origfiletagids[$index] eq 'part') {
13158: # Original part, part of the problem
13159: if ($importedparts) {
13160: $metaentry{':partorder'}.=','.$origid;
13161: }
13162: } elsif ($origfiletagids[$index] eq 'import') {
13163: if ($importedparts) {
13164: # We have imported parts at this position
13165: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13166: }
13167: if ($importedresponses) {
13168: # We have imported responses at this position
13169: if (ref($importedrespids{$origid}) eq 'ARRAY') {
13170: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
13171: }
13172: }
13173: } else {
13174: # Original response item, part of the problem
13175: if ($importedresponses) {
13176: $metaentry{':responseorder'}.=','.$origid;
13177: }
13178: }
13179: }
13180: if ($importedparts) {
13181: $metaentry{':partorder'}=~s/^\,//;
13182: }
13183: if ($importedresponses) {
13184: $metaentry{':responseorder'}=~s/^\,//;
13185: }
1.1070 www 13186: }
13187:
1.737 albertel 13188: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13189: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 13190: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 13191: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 13192: # this is the end of "was not already recently cached
1.71 www 13193: }
1.599 albertel 13194: return $metaentry{':'.$what};
1.261 albertel 13195: }
13196:
1.488 albertel 13197: sub metadata_create_package_def {
1.483 albertel 13198: my ($uri,$key,$package,$metathesekeys)=@_;
13199: my ($pack,$name,$subp)=split(/\&/,$key);
13200: if ($subp eq 'default') { next; }
13201:
1.599 albertel 13202: if (defined($metaentry{':packages'})) {
13203: $metaentry{':packages'}.=','.$package;
1.483 albertel 13204: } else {
1.599 albertel 13205: $metaentry{':packages'}=$package;
1.483 albertel 13206: }
13207: my $value=$packagetab{$key};
13208: my $unikey;
13209: $unikey='parameter_0_'.$name;
1.599 albertel 13210: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13211: $$metathesekeys{$unikey}=1;
1.599 albertel 13212: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13213: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13214: }
1.599 albertel 13215: if (defined($metaentry{':'.$unikey.'.default'})) {
13216: $metaentry{':'.$unikey}=
13217: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13218: }
13219: }
13220:
1.261 albertel 13221: sub metadata_generate_part0 {
13222: my ($metadata,$metacache,$uri) = @_;
13223: my %allnames;
1.737 albertel 13224: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13225: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13226: my $part=$$metacache{':'.$metakey.'.part'};
13227: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13228: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13229: $allnames{$name}=$part;
13230: }
13231: }
13232: }
13233: foreach my $name (keys(%allnames)) {
13234: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13235: my $key=":parameter_0_$name";
1.261 albertel 13236: $$metacache{"$key.part"}='0';
13237: $$metacache{"$key.name"}=$name;
1.428 albertel 13238: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13239: $allnames{$name}.'_'.$name.
13240: '.type'};
1.428 albertel 13241: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13242: '.display'};
1.644 www 13243: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13244: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13245: $$metacache{"$key.display"}=$olddis;
13246: }
1.71 www 13247: }
13248:
1.764 albertel 13249: # ------------------------------------------------------ Devalidate title cache
13250:
13251: sub devalidate_title_cache {
13252: my ($url)=@_;
13253: if (!$env{'request.course.id'}) { return; }
13254: my $symb=&symbread($url);
13255: if (!$symb) { return; }
13256: my $key=$env{'request.course.id'}."\0".$symb;
13257: &devalidate_cache_new('title',$key);
13258: }
13259:
1.1014 droeschl 13260: # ------------------------------------------------- Get the title of a course
13261:
13262: sub current_course_title {
13263: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13264: }
1.301 www 13265: # ------------------------------------------------- Get the title of a resource
13266:
13267: sub gettitle {
13268: my $urlsymb=shift;
13269: my $symb=&symbread($urlsymb);
1.534 albertel 13270: if ($symb) {
1.620 albertel 13271: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13272: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13273: if (defined($cached)) {
13274: return $result;
13275: }
1.534 albertel 13276: my ($map,$resid,$url)=&decode_symb($symb);
13277: my $title='';
1.907 albertel 13278: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13279: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13280: } else {
13281: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13282: &GDBM_READER(),0640)) {
13283: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13284: $title=$bighash{'title_'.$mapid.'.'.$resid};
13285: untie(%bighash);
13286: }
1.534 albertel 13287: }
13288: $title=~s/\&colon\;/\:/gs;
13289: if ($title) {
1.1159 www 13290: # Remember both $symb and $title for dynamic metadata
13291: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13292: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13293: # Cache this title and then return it
1.599 albertel 13294: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13295: }
13296: $urlsymb=$url;
13297: }
13298: my $title=&metadata($urlsymb,'title');
13299: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13300: return $title;
1.301 www 13301: }
1.613 albertel 13302:
1.614 albertel 13303: sub get_slot {
13304: my ($which,$cnum,$cdom)=@_;
13305: if (!$cnum || !$cdom) {
1.790 albertel 13306: (undef,my $courseid)=&whichuser();
1.620 albertel 13307: $cdom=$env{'course.'.$courseid.'.domain'};
13308: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13309: }
1.703 albertel 13310: my $key=join("\0",'slots',$cdom,$cnum,$which);
13311: my %slotinfo;
13312: if (exists($remembered{$key})) {
13313: $slotinfo{$which} = $remembered{$key};
13314: } else {
13315: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13316: &Apache::lonhomework::showhash(%slotinfo);
13317: my ($tmp)=keys(%slotinfo);
13318: if ($tmp=~/^error:/) { return (); }
13319: $remembered{$key} = $slotinfo{$which};
13320: }
1.616 albertel 13321: if (ref($slotinfo{$which}) eq 'HASH') {
13322: return %{$slotinfo{$which}};
13323: }
13324: return $slotinfo{$which};
1.614 albertel 13325: }
1.1150 raeburn 13326:
13327: sub get_reservable_slots {
13328: my ($cnum,$cdom,$uname,$udom) = @_;
13329: my $now = time;
13330: my $reservable_info;
13331: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13332: if (exists($remembered{$key})) {
13333: $reservable_info = $remembered{$key};
13334: } else {
13335: my %resv;
13336: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13337: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13338: $reservable_info = \%resv;
13339: $remembered{$key} = $reservable_info;
13340: }
13341: return $reservable_info;
13342: }
13343:
13344: sub get_course_slots {
13345: my ($cnum,$cdom) = @_;
13346: my $hashid=$cnum.':'.$cdom;
13347: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13348: if (defined($cached)) {
13349: if (ref($result) eq 'HASH') {
13350: return %{$result};
13351: }
13352: } else {
13353: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13354: my ($tmp) = keys(%slots);
13355: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 13356: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13357: return %slots;
13358: }
13359: }
13360: return;
13361: }
13362:
13363: sub devalidate_slots_cache {
13364: my ($cnum,$cdom)=@_;
13365: my $hashid=$cnum.':'.$cdom;
13366: &devalidate_cache_new('allslots',$hashid);
13367: }
13368:
1.1172.2.8 raeburn 13369: sub get_coursechange {
13370: my ($cdom,$cnum) = @_;
13371: if ($cdom eq '' || $cnum eq '') {
13372: return unless ($env{'request.course.id'});
13373: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13374: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13375: }
13376: my $hashid=$cdom.'_'.$cnum;
13377: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13378: if ((defined($cached)) && ($change ne '')) {
13379: return $change;
13380: } else {
13381: my %crshash;
13382: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13383: if ($crshash{'internal.contentchange'} eq '') {
13384: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13385: if ($change eq '') {
13386: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13387: $change = $crshash{'internal.created'};
13388: }
13389: } else {
13390: $change = $crshash{'internal.contentchange'};
13391: }
13392: my $cachetime = 600;
13393: &do_cache_new('crschange',$hashid,$change,$cachetime);
13394: }
13395: return $change;
13396: }
13397:
13398: sub devalidate_coursechange_cache {
1.1172.2.146. .9(raebu 13399:23): my ($cdom,$cnum)=@_;
13400:23): my $hashid=$cdom.'_'.$cnum;
1.1172.2.8 raeburn 13401: &devalidate_cache_new('crschange',$hashid);
13402: }
13403:
1.1172.2.146. .9(raebu 13404:23): sub get_suppchange {
13405:23): my ($cdom,$cnum) = @_;
13406:23): if ($cdom eq '' || $cnum eq '') {
13407:23): return unless ($env{'request.course.id'});
13408:23): $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13409:23): $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13410:23): }
13411:23): my $hashid=$cdom.'_'.$cnum;
13412:23): my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13413:23): if ((defined($cached)) && ($change ne '')) {
13414:23): return $change;
13415:23): } else {
13416:23): my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13417:23): if ($crshash{'internal.supplementalchange'} eq '') {
13418:23): $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13419:23): if ($change eq '') {
13420:23): %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13421:23): $change = $crshash{'internal.created'};
13422:23): }
13423:23): } else {
13424:23): $change = $crshash{'internal.supplementalchange'};
13425:23): }
13426:23): my $cachetime = 600;
13427:23): &do_cache_new('suppchange',$hashid,$change,$cachetime);
13428:23): }
13429:23): return $change;
13430:23): }
13431:23):
13432:23): sub devalidate_suppchange_cache {
13433:23): my ($cdom,$cnum)=@_;
13434:23): my $hashid=$cdom.'_'.$cnum;
13435:23): &devalidate_cache_new('suppchange',$hashid);
13436:23): }
13437:23):
13438:23): sub update_supp_caches {
13439:23): my ($cdom,$cnum) = @_;
13440:23): my %servers = &internet_dom_servers($cdom);
13441:23): my @ids=¤t_machine_ids();
13442:23): foreach my $server (keys(%servers)) {
13443:23): next if (grep(/^\Q$server\E$/,@ids));
13444:23): my $hashid=$cnum.':'.$cdom;
13445:23): my $cachekey = &escape('showsupp').':'.&escape($hashid);
13446:23): &remote_devalidate_cache($server,[$cachekey]);
13447:23): }
13448:23): &has_unhidden_suppfiles($cnum,$cdom,1,1);
13449:23): &count_supptools($cnum,$cdom,1);
13450:23): my $now = time;
13451:23): if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13452:23): &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13453:23): }
13454:23): &put('environment',{'internal.supplementalchange' => $now},
13455:23): $cdom,$cnum);
13456:23): &Apache::lonnet::appenv(
13457:23): {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13458:23): &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13459:23): }
13460:23):
1.31 www 13461: # ------------------------------------------------- Update symbolic store links
13462:
13463: sub symblist {
13464: my ($mapname,%newhash)=@_;
1.438 www 13465: $mapname=&deversion(&declutter($mapname));
1.31 www 13466: my %hash;
1.620 albertel 13467: if (($env{'request.course.fn'}) && (%newhash)) {
13468: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13469: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13470: foreach my $url (keys(%newhash)) {
1.711 albertel 13471: next if ($url eq 'last_known'
13472: && $env{'form.no_update_last_known'});
13473: $hash{declutter($url)}=&encode_symb($mapname,
13474: $newhash{$url}->[1],
13475: $newhash{$url}->[0]);
1.191 harris41 13476: }
1.31 www 13477: if (untie(%hash)) {
13478: return 'ok';
13479: }
13480: }
13481: }
13482: return 'error';
1.212 www 13483: }
13484:
13485: # --------------------------------------------------------------- Verify a symb
13486:
13487: sub symbverify {
1.1172.2.11 raeburn 13488: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13489: my $thisfn=$thisurl;
1.439 www 13490: $thisfn=&declutter($thisfn);
1.215 www 13491: # direct jump to resource in page or to a sequence - will construct own symbs
13492: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13493: # check URL part
1.409 www 13494: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13495:
1.431 www 13496: unless ($url eq $thisfn) { return 0; }
1.213 www 13497:
1.216 www 13498: $symb=&symbclean($symb);
1.510 www 13499: $thisurl=&deversion($thisurl);
1.439 www 13500: $thisfn=&deversion($thisfn);
1.213 www 13501:
13502: my %bighash;
13503: my $okay=0;
1.431 www 13504:
1.620 albertel 13505: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13506: &GDBM_READER(),0640)) {
1.1032 raeburn 13507: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13508: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 13509: if ($map =~ m{^uploaded/.+\.page$}) {
13510: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13511: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13512: }
13513: }
13514: my $ids;
1.1172.2.122 raeburn 13515: if ($map =~ m{^uploaded/.+\.page$}) {
13516: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 13517: } else {
13518: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13519: }
1.1102 raeburn 13520: unless ($ids) {
1.1172.2.13 raeburn 13521: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 13522: $ids=$bighash{$idkey};
1.216 www 13523: }
13524: if ($ids) {
13525: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 13526: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13527: $symb =~ s/\?.+$//;
13528: }
1.800 albertel 13529: foreach my $id (split(/\,/,$ids)) {
13530: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13531: if (
13532: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 13533: eq $symb) {
1.1172.2.11 raeburn 13534: if (ref($encstate)) {
13535: $$encstate = $bighash{'encrypted_'.$id};
13536: }
1.1172.2.13 raeburn 13537: if (($env{'request.role.adv'}) ||
13538: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 13539: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 13540: $okay=1;
13541: last;
13542: }
13543: }
13544: }
1.216 www 13545: }
1.213 www 13546: untie(%bighash);
13547: }
13548: return $okay;
1.31 www 13549: }
13550:
1.210 www 13551: # --------------------------------------------------------------- Clean-up symb
13552:
13553: sub symbclean {
13554: my $symb=shift;
1.568 albertel 13555: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13556: # remove version from map
13557: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13558:
1.210 www 13559: # remove version from URL
13560: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13561:
1.507 www 13562: # remove wrapper
13563:
1.510 www 13564: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13565: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13566: return $symb;
1.409 www 13567: }
13568:
13569: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13570:
13571: sub encode_symb {
13572: my ($map,$resid,$url)=@_;
13573: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13574: }
1.409 www 13575:
13576: sub decode_symb {
1.568 albertel 13577: my $symb=shift;
13578: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13579: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13580: return (&fixversion($map),$resid,&fixversion($url));
13581: }
13582:
13583: sub fixversion {
13584: my $fn=shift;
1.609 banghart 13585: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13586: my %bighash;
13587: my $uri=&clutter($fn);
1.620 albertel 13588: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13589: # is this cached?
1.599 albertel 13590: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13591: if (defined($cached)) { return $result; }
13592: # unfortunately not cached, or expired
1.620 albertel 13593: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13594: &GDBM_READER(),0640)) {
13595: if ($bighash{'version_'.$uri}) {
13596: my $version=$bighash{'version_'.$uri};
1.444 www 13597: unless (($version eq 'mostrecent') ||
13598: ($version==&getversion($uri))) {
1.440 www 13599: $uri=~s/\.(\w+)$/\.$version\.$1/;
13600: }
13601: }
13602: untie %bighash;
1.413 www 13603: }
1.599 albertel 13604: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13605: }
13606:
13607: sub deversion {
13608: my $url=shift;
13609: $url=~s/\.\d+\.(\w+)$/\.$1/;
13610: return $url;
1.210 www 13611: }
13612:
1.31 www 13613: # ------------------------------------------------------ Return symb list entry
13614:
13615: sub symbread {
1.1172.2.126 raeburn 13616: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 13617: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 13618: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 13619: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 13620: unless (ref($possibles) eq 'HASH') {
13621: if ($ignorecachednull) {
13622: return $env{$cache_str} unless ($env{$cache_str} eq '');
13623: } else {
13624: return $env{$cache_str};
13625: }
1.1172.2.66 raeburn 13626: }
13627: }
1.242 www 13628: # no filename provided? try from environment
1.1172.2.54 raeburn 13629: unless ($thisfn) {
1.620 albertel 13630: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 13631: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 13632: }
13633: $thisfn=$env{'request.filename'};
1.44 www 13634: }
1.569 albertel 13635: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13636: # is that filename actually a symb? Verify, clean, and return
13637: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13638: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 13639: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13640: }
1.242 www 13641: }
1.44 www 13642: $thisfn=declutter($thisfn);
1.31 www 13643: my %hash;
1.37 www 13644: my %bighash;
13645: my $syval='';
1.620 albertel 13646: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128 raeburn 13647: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 13648: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13649: &GDBM_READER(),0640)) {
1.1172.2.146. .7(raebu 13650:22): $syval=$hash{$thisfn};
1.1172.2.126 raeburn 13651: untie(%hash);
13652: }
1.1172.2.128 raeburn 13653: if ($syval && $checkforblock) {
13654: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 13655: if (@blockers) {
13656: $syval='';
13657: }
13658: }
1.37 www 13659: }
13660: # ---------------------------------------------------------- There was an entry
13661: if ($syval) {
1.601 albertel 13662: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13663: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13664: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13665: #return $env{$cache_str}='';
1.601 albertel 13666: #}
13667: #$syval.=$1;
13668: #}
1.37 www 13669: } else {
13670: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13671: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13672: &GDBM_READER(),0640)) {
1.37 www 13673: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13674: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13675: unless ($ids) {
13676: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13677: }
13678: unless ($ids) {
13679: # alias?
13680: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13681: }
1.37 www 13682: if ($ids) {
13683: # ------------------------------------------------------------------- Has ID(s)
13684: my @possibilities=split(/\,/,$ids);
1.39 www 13685: if ($#possibilities==0) {
13686: # ----------------------------------------------- There is only one possibility
1.37 www 13687: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13688: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13689: $resid,$thisfn);
1.1172.2.66 raeburn 13690: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 13691: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13692: $possibles->{$syval} = 1;
13693: }
1.1172.2.66 raeburn 13694: }
13695: if ($checkforblock) {
1.1172.2.126 raeburn 13696: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 13697: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 13698: if (@blockers) {
13699: $syval = '';
13700: untie(%bighash);
13701: return $env{$cache_str}='';
13702: }
1.1172.2.66 raeburn 13703: }
13704: }
13705: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13706: # ------------------------------------------ There is more than one possibility
13707: my $realpossible=0;
1.800 albertel 13708: foreach my $id (@possibilities) {
13709: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 13710: my $canaccess;
13711: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13712: $canaccess = 1;
13713: } else {
13714: $canaccess = &allowed('bre',$file);
13715: }
13716: if ($canaccess) {
13717: my ($mapid,$resid)=split(/\./,$id);
13718: if ($bighash{'map_type_'.$mapid} ne 'page') {
13719: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13720: $resid,$thisfn);
1.1172.2.126 raeburn 13721: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 13722: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 13723: if ($checkforblock) {
1.1172.2.127 raeburn 13724: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 13725: if (@blockers > 0) {
13726: $syval = '';
13727: } else {
1.1172.2.66 raeburn 13728: $syval = $poss_syval;
13729: $realpossible++;
13730: }
13731: } else {
13732: $syval = $poss_syval;
13733: $realpossible++;
13734: }
1.1172.2.126 raeburn 13735: if ($syval) {
13736: if (ref($possibles) eq 'HASH') {
13737: $possibles->{$syval} = 1;
13738: }
13739: }
1.1172.2.66 raeburn 13740: }
1.39 www 13741: }
1.191 harris41 13742: }
1.39 www 13743: if ($realpossible!=1) { $syval=''; }
1.249 www 13744: } else {
13745: $syval='';
1.37 www 13746: }
13747: }
1.1172.2.66 raeburn 13748: untie(%bighash);
1.481 raeburn 13749: }
1.31 www 13750: }
1.62 www 13751: if ($syval) {
1.1172.2.128 raeburn 13752: return $env{$cache_str}=$syval;
1.62 www 13753: }
1.31 www 13754: }
1.949 raeburn 13755: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13756: return $env{$cache_str}='';
1.31 www 13757: }
13758:
13759: # ---------------------------------------------------------- Return random seed
13760:
1.32 www 13761: sub numval {
13762: my $txt=shift;
13763: $txt=~tr/A-J/0-9/;
13764: $txt=~tr/a-j/0-9/;
13765: $txt=~tr/K-T/0-9/;
13766: $txt=~tr/k-t/0-9/;
13767: $txt=~tr/U-Z/0-5/;
13768: $txt=~tr/u-z/0-5/;
13769: $txt=~s/\D//g;
1.564 albertel 13770: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13771: return int($txt);
1.368 albertel 13772: }
13773:
1.484 albertel 13774: sub numval2 {
13775: my $txt=shift;
13776: $txt=~tr/A-J/0-9/;
13777: $txt=~tr/a-j/0-9/;
13778: $txt=~tr/K-T/0-9/;
13779: $txt=~tr/k-t/0-9/;
13780: $txt=~tr/U-Z/0-5/;
13781: $txt=~tr/u-z/0-5/;
13782: $txt=~s/\D//g;
13783: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13784: my $total;
13785: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13786: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13787: return int($total);
13788: }
13789:
1.575 albertel 13790: sub numval3 {
13791: use integer;
13792: my $txt=shift;
13793: $txt=~tr/A-J/0-9/;
13794: $txt=~tr/a-j/0-9/;
13795: $txt=~tr/K-T/0-9/;
13796: $txt=~tr/k-t/0-9/;
13797: $txt=~tr/U-Z/0-5/;
13798: $txt=~tr/u-z/0-5/;
13799: $txt=~s/\D//g;
13800: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13801: my $total;
13802: foreach my $val (@txts) { $total+=$val; }
13803: if ($_64bit) { $total=(($total<<32)>>32); }
13804: return $total;
13805: }
13806:
1.675 albertel 13807: sub digest {
13808: my ($data)=@_;
13809: my $digest=&Digest::MD5::md5($data);
13810: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13811: my ($e,$f);
13812: {
13813: use integer;
13814: $e=($a+$b);
13815: $f=($c+$d);
13816: if ($_64bit) {
13817: $e=(($e<<32)>>32);
13818: $f=(($f<<32)>>32);
13819: }
13820: }
13821: if (wantarray) {
13822: return ($e,$f);
13823: } else {
13824: my $g;
13825: {
13826: use integer;
13827: $g=($e+$f);
13828: if ($_64bit) {
13829: $g=(($g<<32)>>32);
13830: }
13831: }
13832: return $g;
13833: }
13834: }
13835:
1.368 albertel 13836: sub latest_rnd_algorithm_id {
1.675 albertel 13837: return '64bit5';
1.366 albertel 13838: }
1.32 www 13839:
1.503 albertel 13840: sub get_rand_alg {
13841: my ($courseid)=@_;
1.790 albertel 13842: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13843: if ($courseid) {
1.620 albertel 13844: return $env{"course.$courseid.rndseed"};
1.503 albertel 13845: }
13846: return &latest_rnd_algorithm_id();
13847: }
13848:
1.562 albertel 13849: sub validCODE {
13850: my ($CODE)=@_;
13851: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13852: return 0;
13853: }
13854:
1.491 albertel 13855: sub getCODE {
1.620 albertel 13856: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13857: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13858: defined($Apache::lonhomework::parsing_a_task) ) &&
13859: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13860: return $Apache::lonhomework::history{'resource.CODE'};
13861: }
13862: return undef;
13863: }
1.1133 foxr 13864: #
13865: # Determines the random seed for a specific context:
13866: #
13867: # parameters:
13868: # symb - in course context the symb for the seed.
13869: # course_id - The course id of the form domain_coursenum.
13870: # domain - Domain for the user.
13871: # course - Course for the user.
13872: # cenv - environment of the course.
13873: #
13874: # NOTE:
13875: # All parameters are picked out of the environment if missing
13876: # or not defined.
13877: # If a symb cannot be determined the current time is used instead.
13878: #
13879: # For a given well defined symb, courside, domain, username,
13880: # and course environment, the seed is reproducible.
13881: #
1.31 www 13882: sub rndseed {
1.1133 foxr 13883: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13884: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13885: if (!defined($symb)) {
1.366 albertel 13886: unless ($symb=$wsymb) { return time; }
13887: }
1.1146 foxr 13888: if (!defined $courseid) {
13889: $courseid=$wcourseid;
13890: }
13891: if (!defined $domain) { $domain=$wdomain; }
13892: if (!defined $username) { $username=$wusername }
1.1133 foxr 13893:
13894: my $which;
13895: if (defined($cenv->{'rndseed'})) {
13896: $which = $cenv->{'rndseed'};
13897: } else {
13898: $which =&get_rand_alg($courseid);
13899: }
1.491 albertel 13900: if (defined(&getCODE())) {
1.675 albertel 13901: if ($which eq '64bit5') {
13902: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13903: } elsif ($which eq '64bit4') {
1.575 albertel 13904: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13905: } else {
13906: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13907: }
1.675 albertel 13908: } elsif ($which eq '64bit5') {
13909: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13910: } elsif ($which eq '64bit4') {
13911: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13912: } elsif ($which eq '64bit3') {
13913: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13914: } elsif ($which eq '64bit2') {
13915: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13916: } elsif ($which eq '64bit') {
13917: return &rndseed_64bit($symb,$courseid,$domain,$username);
13918: }
13919: return &rndseed_32bit($symb,$courseid,$domain,$username);
13920: }
13921:
13922: sub rndseed_32bit {
13923: my ($symb,$courseid,$domain,$username)=@_;
13924: {
13925: use integer;
13926: my $symbchck=unpack("%32C*",$symb) << 27;
13927: my $symbseed=numval($symb) << 22;
13928: my $namechck=unpack("%32C*",$username) << 17;
13929: my $nameseed=numval($username) << 12;
13930: my $domainseed=unpack("%32C*",$domain) << 7;
13931: my $courseseed=unpack("%32C*",$courseid);
13932: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13933: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13934: #&logthis("rndseed :$num:$symb");
1.564 albertel 13935: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13936: return $num;
13937: }
13938: }
13939:
13940: sub rndseed_64bit {
13941: my ($symb,$courseid,$domain,$username)=@_;
13942: {
13943: use integer;
13944: my $symbchck=unpack("%32S*",$symb) << 21;
13945: my $symbseed=numval($symb) << 10;
13946: my $namechck=unpack("%32S*",$username);
13947:
13948: my $nameseed=numval($username) << 21;
13949: my $domainseed=unpack("%32S*",$domain) << 10;
13950: my $courseseed=unpack("%32S*",$courseid);
13951:
13952: my $num1=$symbchck+$symbseed+$namechck;
13953: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13954: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13955: #&logthis("rndseed :$num:$symb");
1.564 albertel 13956: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13957: return "$num1,$num2";
1.155 albertel 13958: }
1.366 albertel 13959: }
13960:
1.443 albertel 13961: sub rndseed_64bit2 {
13962: my ($symb,$courseid,$domain,$username)=@_;
13963: {
13964: use integer;
13965: # strings need to be an even # of cahracters long, it it is odd the
13966: # last characters gets thrown away
13967: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13968: my $symbseed=numval($symb) << 10;
13969: my $namechck=unpack("%32S*",$username.' ');
13970:
13971: my $nameseed=numval($username) << 21;
1.501 albertel 13972: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13973: my $courseseed=unpack("%32S*",$courseid.' ');
13974:
13975: my $num1=$symbchck+$symbseed+$namechck;
13976: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13977: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13978: #&logthis("rndseed :$num:$symb");
1.803 albertel 13979: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13980: return "$num1,$num2";
13981: }
13982: }
13983:
13984: sub rndseed_64bit3 {
13985: my ($symb,$courseid,$domain,$username)=@_;
13986: {
13987: use integer;
13988: # strings need to be an even # of cahracters long, it it is odd the
13989: # last characters gets thrown away
13990: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13991: my $symbseed=numval2($symb) << 10;
13992: my $namechck=unpack("%32S*",$username.' ');
13993:
13994: my $nameseed=numval2($username) << 21;
1.443 albertel 13995: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13996: my $courseseed=unpack("%32S*",$courseid.' ');
13997:
13998: my $num1=$symbchck+$symbseed+$namechck;
13999: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14000: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14001: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14002: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14003:
1.503 albertel 14004: return "$num1:$num2";
1.443 albertel 14005: }
14006: }
14007:
1.575 albertel 14008: sub rndseed_64bit4 {
14009: my ($symb,$courseid,$domain,$username)=@_;
14010: {
14011: use integer;
14012: # strings need to be an even # of cahracters long, it it is odd the
14013: # last characters gets thrown away
14014: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14015: my $symbseed=numval3($symb) << 10;
14016: my $namechck=unpack("%32S*",$username.' ');
14017:
14018: my $nameseed=numval3($username) << 21;
14019: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14020: my $courseseed=unpack("%32S*",$courseid.' ');
14021:
14022: my $num1=$symbchck+$symbseed+$namechck;
14023: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14024: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14025: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14026: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14027:
1.575 albertel 14028: return "$num1:$num2";
14029: }
14030: }
14031:
1.675 albertel 14032: sub rndseed_64bit5 {
14033: my ($symb,$courseid,$domain,$username)=@_;
14034: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14035: return "$num1:$num2";
14036: }
14037:
1.366 albertel 14038: sub rndseed_CODE_64bit {
14039: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14040: {
1.366 albertel 14041: use integer;
1.443 albertel 14042: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14043: my $symbseed=numval2($symb);
1.491 albertel 14044: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14045: my $CODEseed=numval(&getCODE());
1.443 albertel 14046: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14047: my $num1=$symbseed+$CODEchck;
14048: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14049: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14050: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14051: if ($_64bit) { $num1=(($num1<<32)>>32); }
14052: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14053: return "$num1:$num2";
1.366 albertel 14054: }
14055: }
14056:
1.575 albertel 14057: sub rndseed_CODE_64bit4 {
14058: my ($symb,$courseid,$domain,$username)=@_;
14059: {
14060: use integer;
14061: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14062: my $symbseed=numval3($symb);
14063: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14064: my $CODEseed=numval3(&getCODE());
14065: my $courseseed=unpack("%32S*",$courseid.' ');
14066: my $num1=$symbseed+$CODEchck;
14067: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14068: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14069: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14070: if ($_64bit) { $num1=(($num1<<32)>>32); }
14071: if ($_64bit) { $num2=(($num2<<32)>>32); }
14072: return "$num1:$num2";
14073: }
14074: }
14075:
1.675 albertel 14076: sub rndseed_CODE_64bit5 {
14077: my ($symb,$courseid,$domain,$username)=@_;
14078: my $code = &getCODE();
14079: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14080: return "$num1:$num2";
14081: }
14082:
1.366 albertel 14083: sub setup_random_from_rndseed {
14084: my ($rndseed)=@_;
1.503 albertel 14085: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 14086: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14087: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14088: &Math::Random::random_set_seed_from_phrase($rndseed);
14089: } else {
14090: &Math::Random::random_set_seed($num1,$num2);
14091: }
1.366 albertel 14092: } else {
14093: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14094: }
1.36 albertel 14095: }
14096:
1.474 albertel 14097: sub latest_receipt_algorithm_id {
1.835 albertel 14098: return 'receipt3';
1.474 albertel 14099: }
14100:
1.480 www 14101: sub recunique {
14102: my $fucourseid=shift;
14103: my $unique;
1.835 albertel 14104: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14105: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14106: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14107: } else {
14108: $unique=$perlvar{'lonReceipt'};
14109: }
14110: return unpack("%32C*",$unique);
14111: }
14112:
14113: sub recprefix {
14114: my $fucourseid=shift;
14115: my $prefix;
1.835 albertel 14116: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14117: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14118: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14119: } else {
14120: $prefix=$perlvar{'lonHostID'};
14121: }
14122: return unpack("%32C*",$prefix);
14123: }
14124:
1.76 www 14125: sub ireceipt {
1.474 albertel 14126: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14127:
14128: my $return =&recprefix($fucourseid).'-';
14129:
14130: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14131: $env{'request.state'} eq 'construct') {
14132: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14133: return $return;
14134: }
14135:
1.76 www 14136: my $cuname=unpack("%32C*",$funame);
14137: my $cudom=unpack("%32C*",$fudom);
14138: my $cucourseid=unpack("%32C*",$fucourseid);
14139: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14140: my $cunique=&recunique($fucourseid);
1.474 albertel 14141: my $cpart=unpack("%32S*",$part);
1.835 albertel 14142: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14143:
1.790 albertel 14144: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14145:
14146: $return.= ($cunique%$cuname+
14147: $cunique%$cudom+
14148: $cusymb%$cuname+
14149: $cusymb%$cudom+
14150: $cucourseid%$cuname+
14151: $cucourseid%$cudom+
14152: $cpart%$cuname+
14153: $cpart%$cudom);
14154: } else {
14155: $return.= ($cunique%$cuname+
14156: $cunique%$cudom+
14157: $cusymb%$cuname+
14158: $cusymb%$cudom+
14159: $cucourseid%$cuname+
14160: $cucourseid%$cudom);
14161: }
14162: return $return;
1.76 www 14163: }
14164:
14165: sub receipt {
1.474 albertel 14166: my ($part)=@_;
1.790 albertel 14167: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14168: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14169: }
1.260 ng 14170:
1.790 albertel 14171: sub whichuser {
14172: my ($passedsymb)=@_;
14173: my ($symb,$courseid,$domain,$name,$publicuser);
14174: if (defined($env{'form.grade_symb'})) {
14175: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14176: my $allowed=&allowed('vgr',$tmp_courseid);
14177: if (!$allowed &&
14178: exists($env{'request.course.sec'}) &&
14179: $env{'request.course.sec'} !~ /^\s*$/) {
14180: $allowed=&allowed('vgr',$tmp_courseid.
14181: '/'.$env{'request.course.sec'});
14182: }
14183: if ($allowed) {
14184: ($symb)=&get_env_multiple('form.grade_symb');
14185: $courseid=$tmp_courseid;
14186: ($domain)=&get_env_multiple('form.grade_domain');
14187: ($name)=&get_env_multiple('form.grade_username');
14188: return ($symb,$courseid,$domain,$name,$publicuser);
14189: }
14190: }
14191: if (!$passedsymb) {
14192: $symb=&symbread();
14193: } else {
14194: $symb=$passedsymb;
14195: }
14196: $courseid=$env{'request.course.id'};
14197: $domain=$env{'user.domain'};
14198: $name=$env{'user.name'};
14199: if ($name eq 'public' && $domain eq 'public') {
14200: if (!defined($env{'form.username'})) {
14201: $env{'form.username'}.=time.rand(10000000);
14202: }
14203: $name.=$env{'form.username'};
14204: }
14205: return ($symb,$courseid,$domain,$name,$publicuser);
14206:
14207: }
14208:
1.36 albertel 14209: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14210: # returns either the contents of the file or
14211: # -1 if the file doesn't exist
1.481 raeburn 14212: #
14213: # if the target is a file that was uploaded via DOCS,
14214: # a check will be made to see if a current copy exists on the local server,
14215: # if it does this will be served, otherwise a copy will be retrieved from
14216: # the home server for the course and stored in /home/httpd/html/userfiles on
14217: # the local server.
1.472 albertel 14218:
1.36 albertel 14219: sub getfile {
1.538 albertel 14220: my ($file) = @_;
1.609 banghart 14221: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14222: &repcopy($file);
14223: return &readfile($file);
14224: }
14225:
14226: sub repcopy_userfile {
14227: my ($file)=@_;
1.1142 raeburn 14228: my $londocroot = $perlvar{'lonDocRoot'};
14229: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14230: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14231: my ($cdom,$cnum,$filename) =
1.811 albertel 14232: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14233: my $uri="/uploaded/$cdom/$cnum/$filename";
14234: if (-e "$file") {
1.828 www 14235: # we already have a local copy, check it out
1.538 albertel 14236: my @fileinfo = stat($file);
1.828 www 14237: my $rtncode;
14238: my $info;
1.538 albertel 14239: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14240: if ($lwpresp ne 'ok') {
1.828 www 14241: # there is no such file anymore, even though we had a local copy
1.482 albertel 14242: if ($rtncode eq '404') {
1.538 albertel 14243: unlink($file);
1.482 albertel 14244: }
14245: return -1;
14246: }
14247: if ($info < $fileinfo[9]) {
1.828 www 14248: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14249: return 'ok';
1.828 www 14250: } else {
14251: # the file is outdated, get rid of it
14252: unlink($file);
1.482 albertel 14253: }
1.828 www 14254: }
14255: # one way or the other, at this point, we don't have the file
14256: # construct the correct path for the file
14257: my @parts = ($cdom,$cnum);
14258: if ($filename =~ m|^(.+)/[^/]+$|) {
14259: push @parts, split(/\//,$1);
14260: }
14261: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14262: foreach my $part (@parts) {
14263: $path .= '/'.$part;
14264: if (!-e $path) {
14265: mkdir($path,0770);
1.482 albertel 14266: }
14267: }
1.828 www 14268: # now the path exists for sure
14269: # get a user agent
14270: my $ua=new LWP::UserAgent;
14271: my $transferfile=$file.'.in.transfer';
14272: # FIXME: this should flock
14273: if (-e $transferfile) { return 'ok'; }
14274: my $request;
14275: $uri=~s/^\///;
1.980 raeburn 14276: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 14277: my $hostname = &hostname($homeserver);
1.980 raeburn 14278: my $protocol = $protocol{$homeserver};
14279: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14280: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 14281: my $response=$ua->request($request,$transferfile);
14282: # did it work?
14283: if ($response->is_error()) {
14284: unlink($transferfile);
14285: &logthis("Userfile repcopy failed for $uri");
14286: return -1;
14287: }
14288: # worked, rename the transfer file
14289: rename($transferfile,$file);
1.607 raeburn 14290: return 'ok';
1.481 raeburn 14291: }
14292:
1.517 albertel 14293: sub tokenwrapper {
14294: my $uri=shift;
1.980 raeburn 14295: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14296: $uri=~s|^/||;
1.620 albertel 14297: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14298: my $token=$1;
1.552 albertel 14299: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14300: if ($udom && $uname && $file) {
14301: $file=~s|(\?\.*)*$||;
1.949 raeburn 14302: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14303: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 14304: my $hostname = &hostname($homeserver);
1.980 raeburn 14305: my $protocol = $protocol{$homeserver};
14306: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14307: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14308: (($uri=~/\?/)?'&':'?').'token='.$token.
14309: '&tokenissued='.$perlvar{'lonHostID'};
14310: } else {
14311: return '/adm/notfound.html';
14312: }
14313: }
14314:
1.828 www 14315: # call with reqtype HEAD: get last modification time
14316: # call with reqtype GET: get the file contents
14317: # Do not call this with reqtype GET for large files! It loads everything into memory
14318: #
1.481 raeburn 14319: sub getuploaded {
14320: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14321: $uri=~s/^\///;
1.980 raeburn 14322: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 14323: my $hostname = &hostname($homeserver);
1.980 raeburn 14324: my $protocol = $protocol{$homeserver};
14325: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14326: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14327: my $ua=new LWP::UserAgent;
14328: my $request=new HTTP::Request($reqtype,$uri);
14329: my $response=$ua->request($request);
14330: $$rtncode = $response->code;
1.482 albertel 14331: if (! $response->is_success()) {
14332: return 'failed';
14333: }
14334: if ($reqtype eq 'HEAD') {
1.486 www 14335: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14336: } elsif ($reqtype eq 'GET') {
14337: $$info = $response->content;
1.472 albertel 14338: }
1.482 albertel 14339: return 'ok';
1.36 albertel 14340: }
14341:
1.481 raeburn 14342: sub readfile {
14343: my $file = shift;
14344: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14345: my $fh;
1.1172.2.96 raeburn 14346: open($fh,"<",$file);
1.481 raeburn 14347: my $a='';
1.800 albertel 14348: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14349: return $a;
14350: }
14351:
1.36 albertel 14352: sub filelocation {
1.590 banghart 14353: my ($dir,$file) = @_;
14354: my $location;
14355: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14356:
14357: if ($file =~ m-^/adm/-) {
14358: $file=~s-^/adm/wrapper/-/-;
14359: $file=~s-^/adm/coursedocs/showdoc/-/-;
14360: }
1.882 albertel 14361:
1.1139 www 14362: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14363: $location = $file;
1.609 banghart 14364: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14365: my ($udom,$uname,$filename)=
1.811 albertel 14366: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14367: my $home=&homeserver($uname,$udom);
14368: my $is_me=0;
14369: my @ids=¤t_machine_ids();
14370: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14371: if ($is_me) {
1.1117 foxr 14372: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14373: } else {
14374: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14375: $udom.'/'.$uname.'/'.$filename;
14376: }
1.882 albertel 14377: } elsif ($file =~ m-^/adm/-) {
14378: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14379: } else {
14380: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14381: $file=~s:^/(res|priv)/:/:;
14382: my $space=$1;
1.590 banghart 14383: if ( !( $file =~ m:^/:) ) {
14384: $location = $dir. '/'.$file;
14385: } else {
1.1142 raeburn 14386: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14387: }
1.59 albertel 14388: }
1.590 banghart 14389: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14390: while ($location=~m{/\.\./}) {
14391: if ($location =~ m{/[^/]+/\.\./}) {
14392: $location=~ s{/[^/]+/\.\./}{/}g;
14393: } else {
14394: $location=~ s{/\.\./}{/}g;
14395: }
14396: } #remove dir/..
1.590 banghart 14397: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14398: return $location;
1.46 www 14399: }
1.36 albertel 14400:
1.46 www 14401: sub hreflocation {
14402: my ($dir,$file)=@_;
1.980 raeburn 14403: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14404: $file=filelocation($dir,$file);
1.700 albertel 14405: } elsif ($file=~m-^/adm/-) {
14406: $file=~s-^/adm/wrapper/-/-;
14407: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14408: }
14409: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14410: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14411: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14412: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14413: {/uploaded/$1/$2/}x;
1.46 www 14414: }
1.913 albertel 14415: if ($file=~ m{^/userfiles/}) {
14416: $file =~ s{^/userfiles/}{/uploaded/};
14417: }
1.462 albertel 14418: return $file;
1.465 albertel 14419: }
14420:
1.1139 www 14421:
14422:
14423:
14424:
1.465 albertel 14425: sub current_machine_domains {
1.853 albertel 14426: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14427: }
14428:
14429: sub machine_domains {
14430: my ($hostname) = @_;
1.465 albertel 14431: my @domains;
1.838 albertel 14432: my %hostname = &all_hostnames();
1.465 albertel 14433: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14434: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14435: if ($hostname eq $name) {
1.844 albertel 14436: push(@domains,&host_domain($id));
1.465 albertel 14437: }
14438: }
14439: return @domains;
14440: }
14441:
14442: sub current_machine_ids {
1.853 albertel 14443: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14444: }
14445:
14446: sub machine_ids {
14447: my ($hostname) = @_;
14448: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14449: my @ids;
1.888 albertel 14450: my %name_to_host = &all_names();
1.889 albertel 14451: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14452: return @{ $name_to_host{$hostname} };
14453: }
14454: return;
1.31 www 14455: }
14456:
1.824 raeburn 14457: sub additional_machine_domains {
14458: my @domains;
1.1172.2.142 raeburn 14459: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14460: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14461: while( my $line = <$fh>) {
14462: chomp($line);
14463: $line =~ s/\s//g;
14464: push(@domains,$line);
14465: }
14466: close($fh);
14467: }
1.824 raeburn 14468: }
14469: return @domains;
14470: }
14471:
14472: sub default_login_domain {
14473: my $domain = $perlvar{'lonDefDomain'};
14474: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14475: foreach my $posdom (¤t_machine_domains(),
14476: &additional_machine_domains()) {
14477: if (lc($posdom) eq lc($testdomain)) {
14478: $domain=$posdom;
14479: last;
14480: }
14481: }
14482: return $domain;
14483: }
14484:
1.1172.2.106 raeburn 14485: sub shared_institution {
1.1172.2.136 raeburn 14486: my ($dom,$lonhost) = @_;
14487: if ($lonhost eq '') {
14488: $lonhost = $perlvar{'lonHostID'};
14489: }
1.1172.2.106 raeburn 14490: my $same_intdom;
1.1172.2.136 raeburn 14491: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 14492: if ($hostintdom ne '') {
14493: my %iphost = &get_iphost();
14494: my $primary_id = &domain($dom,'primary');
14495: my $primary_ip = &get_host_ip($primary_id);
14496: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14497: foreach my $id (@{$iphost{$primary_ip}}) {
14498: my $intdom = &internet_dom($id);
14499: if ($intdom eq $hostintdom) {
14500: $same_intdom = 1;
14501: last;
14502: }
14503: }
14504: }
14505: }
14506: return $same_intdom;
14507: }
14508:
1.1172.2.120 raeburn 14509: sub uses_sts {
14510: my ($ignore_cache) = @_;
14511: my $lonhost = $perlvar{'lonHostID'};
14512: my $hostname = &hostname($lonhost);
14513: my $sts_on;
14514: if ($protocol{$lonhost} eq 'https') {
14515: my $cachetime = 12*3600;
14516: if (!$ignore_cache) {
14517: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14518: if (defined($cached)) {
14519: return $sts_on;
14520: }
14521: }
1.1172.2.121 raeburn 14522: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 14523: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14524: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 14525: my $response=$ua->request($request);
1.1172.2.120 raeburn 14526: if ($response->is_success) {
14527: my $has_sts = $response->header('Strict-Transport-Security');
14528: if ($has_sts eq '') {
14529: $sts_on = 0;
14530: } else {
14531: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14532: my $maxage = $1;
14533: if ($maxage) {
14534: $sts_on = 1;
14535: } else {
14536: $sts_on = 0;
14537: }
14538: } else {
14539: $sts_on = 0;
14540: }
14541: }
14542: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14543: }
14544: }
14545: return;
14546: }
14547:
1.1172.2.142 raeburn 14548: sub waf_allssl {
14549: my ($host_name) = @_;
14550: my $alias = &get_proxy_alias();
14551: if ($host_name eq '') {
14552: $host_name = $ENV{'SERVER_NAME'};
14553: }
14554: if (($host_name ne '') && ($alias eq $host_name)) {
14555: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14556: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14557: if ($defdomdefaults{'waf_sslopt'}) {
14558: return $defdomdefaults{'waf_sslopt'};
14559: }
14560: }
14561: return;
14562: }
14563:
1.1172.2.134 raeburn 14564: sub get_requestor_ip {
14565: my ($r,$nolookup,$noproxy) = @_;
14566: my $from_ip;
14567: if (ref($r)) {
1.1172.2.142 raeburn 14568: if ($r->can('useragent_ip')) {
14569: if ($noproxy && $r->can('client_ip')) {
14570: $from_ip = $r->client_ip();
14571: } else {
14572: $from_ip = $r->useragent_ip();
14573: }
14574: } elsif ($r->connection->can('remote_ip')) {
14575: $from_ip = $r->connection->remote_ip();
14576: } else {
14577: $from_ip = $r->get_remote_host($nolookup);
14578: }
1.1172.2.134 raeburn 14579: } else {
14580: $from_ip = $ENV{'REMOTE_ADDR'};
14581: }
1.1172.2.142 raeburn 14582: return $from_ip if ($noproxy);
14583: # Who controls proxy settings for server
14584: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14585: my $proxyinfo = &get_proxy_settings($dom_in_use);
14586: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14587: if ($proxyinfo->{'vpnint'}) {
14588: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14589: return $from_ip;
14590: }
14591: }
14592: if ($proxyinfo->{'trusted'}) {
14593: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14594: my $ipheader = $proxyinfo->{'ipheader'};
14595: my ($ip,$xfor);
14596: if (ref($r)) {
14597: if ($ipheader) {
14598: $ip = $r->headers_in->{$ipheader};
14599: }
14600: $xfor = $r->headers_in->{'X-Forwarded-For'};
14601: } else {
14602: if ($ipheader) {
14603: $ip = $ENV{'HTTP_'.uc($ipheader)};
14604: }
14605: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14606: }
14607: if (($ip eq '') && ($xfor ne '')) {
14608: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14609: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14610: $ip = $poss_ip;
14611: last;
14612: }
14613: }
14614: }
14615: if ($ip ne '') {
14616: return $ip;
14617: }
14618: }
14619: }
14620: }
1.1172.2.134 raeburn 14621: return $from_ip;
14622: }
14623:
1.1172.2.142 raeburn 14624: sub get_proxy_settings {
14625: my ($dom_in_use) = @_;
14626: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14627: my $proxyinfo = {
14628: ipheader => $domdefaults{'waf_ipheader'},
14629: trusted => $domdefaults{'waf_trusted'},
14630: vpnint => $domdefaults{'waf_vpnint'},
14631: vpnext => $domdefaults{'waf_vpnext'},
14632: sslopt => $domdefaults{'waf_sslopt'},
14633: };
14634: return $proxyinfo;
14635: }
14636:
14637: sub ip_match {
14638: my ($ip,$pattern_str) = @_;
14639: $ip=Net::CIDR::cidrvalidate($ip);
14640: if ($ip) {
14641: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14642: }
14643: return;
14644: }
14645:
14646: sub get_proxy_alias {
14647: my ($lonid) = @_;
14648: if ($lonid eq '') {
14649: $lonid = $perlvar{'lonHostID'};
14650: }
14651: if (!defined(&hostname($lonid))) {
14652: return;
14653: }
14654: if ($lonid ne '') {
14655: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14656: if ($cached) {
14657: return $alias;
14658: }
14659: my $dom = &Apache::lonnet::host_domain($lonid);
14660: if ($dom ne '') {
14661: my $cachetime = 60*60*24;
14662: my %domconfig =
14663: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14664: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14665: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14666: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14667: }
14668: }
14669: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14670: }
14671: }
14672: return;
14673: }
14674:
14675: sub use_proxy_alias {
14676: my ($r,$lonid) = @_;
14677: my $alias = &get_proxy_alias($lonid);
14678: if ($alias) {
14679: my $dom = &host_domain($lonid);
14680: if ($dom ne '') {
14681: my $proxyinfo = &get_proxy_settings($dom);
14682: my ($vpnint,$remote_ip);
14683: if (ref($proxyinfo) eq 'HASH') {
14684: $vpnint = $proxyinfo->{'vpnint'};
14685: if ($vpnint) {
14686: $remote_ip = &get_requestor_ip($r,1,1);
14687: }
14688: }
14689: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14690: return $alias;
14691: }
14692: }
14693: }
14694: return;
14695: }
14696:
14697: sub alias_sso {
14698: my ($lonid) = @_;
14699: if ($lonid eq '') {
14700: $lonid = $perlvar{'lonHostID'};
14701: }
14702: if (!defined(&hostname($lonid))) {
14703: return;
14704: }
14705: if ($lonid ne '') {
14706: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14707: if ($cached) {
14708: return $use_alias;
14709: }
14710: my $dom = &Apache::lonnet::host_domain($lonid);
14711: if ($dom ne '') {
14712: my $cachetime = 60*60*24;
14713: my %domconfig =
14714: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14715: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14716: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14717: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14718: }
14719: }
14720: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14721: }
14722: }
14723: return;
14724: }
14725:
14726: sub get_saml_landing {
14727: my ($lonid) = @_;
14728: if ($lonid eq '') {
14729: my $defdom = &default_login_domain();
14730: my @hosts = ¤t_machine_ids();
14731: if (@hosts > 1) {
14732: foreach my $hostid (@hosts) {
14733: if (&host_domain($hostid) eq $defdom) {
14734: $lonid = $hostid;
14735: last;
14736: }
14737: }
14738: } else {
14739: $lonid = $perlvar{'lonHostID'};
14740: }
14741: if ($lonid) {
14742: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14743: return;
14744: }
14745: } else {
14746: return;
14747: }
14748: } elsif (!defined(&hostname($lonid))) {
14749: return;
14750: }
14751: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14752: if ($cached) {
14753: return $landing;
14754: }
14755: my $dom = &Apache::lonnet::host_domain($lonid);
14756: if ($dom ne '') {
14757: my $cachetime = 60*60*24;
14758: my %domconfig =
14759: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14760: if (ref($domconfig{'login'}) eq 'HASH') {
14761: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14762: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14763: $landing = 1;
14764: }
14765: }
14766: }
14767: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14768: }
14769: return;
14770: }
14771:
1.31 www 14772: # ------------------------------------------------------------- Declutters URLs
14773:
14774: sub declutter {
14775: my $thisfn=shift;
1.569 albertel 14776: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 14777: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14778: $thisfn=~s{^/home/httpd/html}{};
14779: }
1.31 www 14780: $thisfn=~s/^\///;
1.697 albertel 14781: $thisfn=~s|^adm/wrapper/||;
14782: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14783: $thisfn=~s/^res\///;
1.1172 bisitz 14784: $thisfn=~s/^priv\///;
1.1032 raeburn 14785: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14786: $thisfn=~s/\?.+$//;
14787: }
1.268 www 14788: return $thisfn;
14789: }
14790:
14791: # ------------------------------------------------------------- Clutter up URLs
14792:
14793: sub clutter {
14794: my $thisfn='/'.&declutter(shift);
1.887 albertel 14795: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14796: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14797: $thisfn='/res'.$thisfn;
14798: }
1.1031 raeburn 14799: if ($thisfn !~m|^/adm|) {
14800: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14801: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14802: } else {
14803: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14804: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14805: if ($embstyle eq 'ssi'
14806: || ($embstyle eq 'hdn')
14807: || ($embstyle eq 'rat')
14808: || ($embstyle eq 'prv')
14809: || ($embstyle eq 'ign')) {
14810: #do nothing with these
14811: } elsif (($embstyle eq 'img')
1.695 albertel 14812: || ($embstyle eq 'emb')
14813: || ($embstyle eq 'wrp')) {
14814: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14815: } elsif ($embstyle eq 'unk'
14816: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14817: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14818: } else {
1.718 www 14819: # &logthis("Got a blank emb style");
1.695 albertel 14820: }
1.694 albertel 14821: }
1.1172.2.146. .1(raebu 14822:22): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14823:22): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14824: }
1.31 www 14825: return $thisfn;
1.12 www 14826: }
14827:
1.787 albertel 14828: sub clutter_with_no_wrapper {
14829: my $uri = &clutter(shift);
14830: if ($uri =~ m-^/adm/-) {
14831: $uri =~ s-^/adm/wrapper/-/-;
14832: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14833: }
14834: return $uri;
14835: }
14836:
1.557 albertel 14837: sub freeze_escape {
14838: my ($value)=@_;
14839: if (ref($value)) {
14840: $value=&nfreeze($value);
14841: return '__FROZEN__'.&escape($value);
14842: }
14843: return &escape($value);
14844: }
14845:
1.11 www 14846:
1.557 albertel 14847: sub thaw_unescape {
14848: my ($value)=@_;
14849: if ($value =~ /^__FROZEN__/) {
14850: substr($value,0,10,undef);
14851: $value=&unescape($value);
14852: return &thaw($value);
14853: }
14854: return &unescape($value);
14855: }
14856:
1.436 albertel 14857: sub correct_line_ends {
14858: my ($result)=@_;
14859: $$result =~s/\r\n/\n/mg;
14860: $$result =~s/\r/\n/mg;
1.415 albertel 14861: }
1.1 albertel 14862: # ================================================================ Main Program
14863:
1.184 www 14864: sub goodbye {
1.204 albertel 14865: &logthis("Starting Shut down");
1.443 albertel 14866: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14867: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14868: #converted
1.599 albertel 14869: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14870: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14871: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14872: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14873: #1.1 only
1.870 albertel 14874: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14875: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14876: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14877: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14878: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14879: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14880: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14881: &flushcourselogs();
14882: &logthis("Shutting down");
14883: }
14884:
1.852 albertel 14885: sub get_dns {
1.1172.2.17 raeburn 14886: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14887: if (!$ignore_cache) {
14888: my ($content,$cached)=
14889: &Apache::lonnet::is_cached_new('dns',$url);
14890: if ($cached) {
1.1172.2.17 raeburn 14891: &$func($content,$hashref);
1.869 albertel 14892: return;
14893: }
14894: }
14895:
14896: my %alldns;
1.1172.2.96 raeburn 14897: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14898: foreach my $dns (<$config>) {
14899: next if ($dns !~ /^\^(\S*)/x);
14900: my $line = $1;
14901: my ($host,$protocol) = split(/:/,$line);
14902: if ($protocol ne 'https') {
14903: $protocol = 'http';
14904: }
14905: $alldns{$host} = $protocol;
1.979 raeburn 14906: }
1.1172.2.96 raeburn 14907: close($config);
1.869 albertel 14908: }
14909: while (%alldns) {
1.1172.2.52 raeburn 14910: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 14911: my @content;
14912: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14913: my $command = (split('/',$url))[3];
14914: my ($dir,$file) = &parse_getdns_url($command,$url);
14915: delete($alldns{$dns});
14916: next if (($dir eq '') || ($file eq ''));
14917: if (open(my $config,'<',"$dir/$file")) {
14918: @content = <$config>;
14919: close($config);
14920: }
14921: } else {
14922: my $ua=new LWP::UserAgent;
14923: $ua->timeout(30);
14924: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14925: my $response=$ua->request($request);
14926: delete($alldns{$dns});
14927: next if ($response->is_error());
14928: @content = split("\n",$response->content);
14929: }
1.1172.2.17 raeburn 14930: unless ($nocache) {
1.1172.2.23 raeburn 14931: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 14932: }
14933: &$func(\@content,$hashref);
1.869 albertel 14934: return;
1.852 albertel 14935: }
1.871 albertel 14936: my $which = (split('/',$url))[3];
14937: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14938: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14939: my @content = <$config>;
14940: &$func(\@content,$hashref);
14941: }
1.1172.2.17 raeburn 14942: return;
14943: }
14944:
14945: # ------------------------------------------------------Get DNS checksums file
14946: sub parse_dns_checksums_tab {
14947: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14948: my $lonhost = $perlvar{'lonHostID'};
14949: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14950: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14951: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14952: my $webconfdir = '/etc/httpd/conf';
14953: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14954: $webconfdir = '/etc/apache2';
14955: } elsif ($distro =~ /^sles(\d+)$/) {
14956: if ($1 >= 10) {
14957: $webconfdir = '/etc/apache2';
14958: }
14959: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14960: if ($1 >= 10.0) {
14961: $webconfdir = '/etc/apache2';
14962: }
14963: }
1.1172.2.17 raeburn 14964: my ($release,$timestamp) = split(/\-/,$loncaparev);
14965: my (%chksum,%revnum);
14966: if (ref($lines) eq 'ARRAY') {
14967: chomp(@{$lines});
1.1172.2.34 raeburn 14968: my $version = shift(@{$lines});
14969: if ($version eq $release) {
1.1172.2.17 raeburn 14970: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14971: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14972: if ($file =~ m{^/etc/httpd/conf}) {
14973: if ($webconfdir eq '/etc/apache2') {
14974: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14975: }
14976: }
1.1172.2.34 raeburn 14977: $chksum{$file} = $shasum;
14978: $revnum{$file} = $version;
1.1172.2.17 raeburn 14979: }
14980: if (ref($hashref) eq 'HASH') {
14981: %{$hashref} = (
14982: sums => \%chksum,
14983: versions => \%revnum,
14984: );
14985: }
14986: }
14987: }
1.869 albertel 14988: return;
1.852 albertel 14989: }
1.1172.2.17 raeburn 14990:
14991: sub fetch_dns_checksums {
14992: my %checksums;
1.1172.2.34 raeburn 14993: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14994: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14995: my ($release,$timestamp) = split(/\-/,$loncaparev);
14996: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14997: \%checksums);
14998: return \%checksums;
14999: }
15000:
1.1172.2.142 raeburn 15001: sub parse_getdns_url {
15002: my ($command,$url) = @_;
15003: my $dir = $perlvar{'lonTabDir'};
15004: my $file;
15005: if ($command eq 'hosts') {
15006: $file = 'dns_hosts.tab';
15007: } elsif ($command eq 'domain') {
15008: $file = 'dns_domain.tab';
15009: } elsif ($command eq 'checksums') {
15010: my $version = (split('/',$url))[4];
15011: $file = "dns_checksums/$version.tab",
15012: }
15013: return ($dir,$file);
15014: }
15015:
1.327 albertel 15016: # ------------------------------------------------------------ Read domain file
15017: {
1.852 albertel 15018: my $loaded;
1.846 albertel 15019: my %domain;
15020:
1.852 albertel 15021: sub parse_domain_tab {
15022: my ($lines) = @_;
15023: foreach my $line (@$lines) {
15024: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15025:
1.846 albertel 15026: chomp($line);
1.852 albertel 15027: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15028: my %this_domain;
15029: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15030: 'lang_def', 'city', 'longi', 'lati',
15031: 'primary') {
15032: $this_domain{$field} = shift(@elements);
15033: }
15034: $domain{$name} = \%this_domain;
1.852 albertel 15035: }
15036: }
1.864 albertel 15037:
15038: sub reset_domain_info {
15039: undef($loaded);
15040: undef(%domain);
15041: }
15042:
1.852 albertel 15043: sub load_domain_tab {
1.1172.2.70 raeburn 15044: my ($ignore_cache,$nocache) = @_;
15045: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15046: my $fh;
1.1172.2.96 raeburn 15047: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15048: my @lines = <$fh>;
15049: &parse_domain_tab(\@lines);
1.448 albertel 15050: }
1.852 albertel 15051: close($fh);
15052: $loaded = 1;
1.327 albertel 15053: }
1.846 albertel 15054:
15055: sub domain {
1.852 albertel 15056: &load_domain_tab() if (!$loaded);
15057:
1.846 albertel 15058: my ($name,$what) = @_;
15059: return if ( !exists($domain{$name}) );
15060:
15061: if (!$what) {
15062: return $domain{$name}{'description'};
15063: }
15064: return $domain{$name}{$what};
15065: }
1.974 raeburn 15066:
15067: sub domain_info {
15068: &load_domain_tab() if (!$loaded);
15069: return %domain;
15070: }
15071:
1.327 albertel 15072: }
15073:
15074:
1.1 albertel 15075: # ------------------------------------------------------------- Read hosts file
15076: {
1.838 albertel 15077: my %hostname;
1.844 albertel 15078: my %hostdom;
1.845 albertel 15079: my %libserv;
1.852 albertel 15080: my $loaded;
1.888 albertel 15081: my %name_to_host;
1.1074 raeburn 15082: my %internetdom;
1.1107 raeburn 15083: my %LC_dns_serv;
1.852 albertel 15084:
15085: sub parse_hosts_tab {
15086: my ($file) = @_;
15087: foreach my $configline (@$file) {
15088: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15089: chomp($configline);
15090: if ($configline =~ /^\^/) {
15091: if ($configline =~ /^\^([\w.\-]+)/) {
15092: $LC_dns_serv{$1} = 1;
15093: }
15094: next;
15095: }
1.1074 raeburn 15096: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15097: $name=~s/\s//g;
15098: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 15099: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15100: my $curr = $hostname{$id};
15101: my $skip;
15102: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15103: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15104: $skip = 1;
15105: } else {
15106: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15107: }
15108: }
15109: unless ($skip) {
15110: push(@{$name_to_host{$name}},$id);
15111: }
15112: } else {
15113: push(@{$name_to_host{$name}},$id);
15114: }
1.852 albertel 15115: $hostname{$id}=$name;
15116: $hostdom{$id}=$domain;
15117: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15118: if (defined($protocol)) {
15119: if ($protocol eq 'https') {
15120: $protocol{$id} = $protocol;
15121: } else {
15122: $protocol{$id} = 'http';
15123: }
1.968 raeburn 15124: } else {
1.969 raeburn 15125: $protocol{$id} = 'http';
1.968 raeburn 15126: }
1.1074 raeburn 15127: if (defined($intdom)) {
15128: $internetdom{$id} = $intdom;
15129: }
1.852 albertel 15130: }
15131: }
15132: }
1.864 albertel 15133:
15134: sub reset_hosts_info {
1.897 albertel 15135: &purge_remembered();
1.864 albertel 15136: &reset_domain_info();
15137: &reset_hosts_ip_info();
1.892 albertel 15138: undef(%name_to_host);
1.864 albertel 15139: undef(%hostname);
15140: undef(%hostdom);
15141: undef(%libserv);
15142: undef($loaded);
15143: }
1.1 albertel 15144:
1.852 albertel 15145: sub load_hosts_tab {
1.1172.2.70 raeburn 15146: my ($ignore_cache,$nocache) = @_;
15147: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 15148: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15149: my @config = <$config>;
15150: &parse_hosts_tab(\@config);
15151: close($config);
15152: $loaded=1;
1.1 albertel 15153: }
1.852 albertel 15154:
1.838 albertel 15155: sub hostname {
1.852 albertel 15156: &load_hosts_tab() if (!$loaded);
15157:
1.838 albertel 15158: my ($lonid) = @_;
15159: return $hostname{$lonid};
15160: }
1.845 albertel 15161:
1.838 albertel 15162: sub all_hostnames {
1.852 albertel 15163: &load_hosts_tab() if (!$loaded);
15164:
1.838 albertel 15165: return %hostname;
15166: }
1.845 albertel 15167:
1.888 albertel 15168: sub all_names {
1.1172.2.70 raeburn 15169: my ($ignore_cache,$nocache) = @_;
15170: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15171:
15172: return %name_to_host;
15173: }
15174:
1.974 raeburn 15175: sub all_host_domain {
15176: &load_hosts_tab() if (!$loaded);
15177: return %hostdom;
15178: }
15179:
1.845 albertel 15180: sub is_library {
1.852 albertel 15181: &load_hosts_tab() if (!$loaded);
15182:
1.845 albertel 15183: return exists($libserv{$_[0]});
15184: }
15185:
15186: sub all_library {
1.852 albertel 15187: &load_hosts_tab() if (!$loaded);
15188:
1.845 albertel 15189: return %libserv;
15190: }
15191:
1.1062 droeschl 15192: sub unique_library {
15193: #2x reverse removes all hostnames that appear more than once
15194: my %unique = reverse &all_library();
15195: return reverse %unique;
15196: }
15197:
1.841 albertel 15198: sub get_servers {
1.852 albertel 15199: &load_hosts_tab() if (!$loaded);
15200:
1.841 albertel 15201: my ($domain,$type) = @_;
15202: my %possible_hosts = ($type eq 'library') ? %libserv
15203: : %hostname;
15204: my %result;
1.842 albertel 15205: if (ref($domain) eq 'ARRAY') {
15206: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15207: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15208: $result{$host} = $hostname;
15209: }
15210: }
15211: } else {
15212: while ( my ($host,$hostname) = each(%possible_hosts)) {
15213: if ($hostdom{$host} eq $domain) {
15214: $result{$host} = $hostname;
15215: }
1.841 albertel 15216: }
15217: }
15218: return %result;
15219: }
1.845 albertel 15220:
1.1062 droeschl 15221: sub get_unique_servers {
15222: my %unique = reverse &get_servers(@_);
15223: return reverse %unique;
15224: }
15225:
1.844 albertel 15226: sub host_domain {
1.852 albertel 15227: &load_hosts_tab() if (!$loaded);
15228:
1.844 albertel 15229: my ($lonid) = @_;
15230: return $hostdom{$lonid};
15231: }
15232:
1.841 albertel 15233: sub all_domains {
1.852 albertel 15234: &load_hosts_tab() if (!$loaded);
15235:
1.841 albertel 15236: my %seen;
15237: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15238: return @uniq;
15239: }
1.1074 raeburn 15240:
15241: sub internet_dom {
15242: &load_hosts_tab() if (!$loaded);
15243:
15244: my ($lonid) = @_;
15245: return $internetdom{$lonid};
15246: }
1.1107 raeburn 15247:
15248: sub is_LC_dns {
15249: &load_hosts_tab() if (!$loaded);
15250:
15251: my ($hostname) = @_;
15252: return exists($LC_dns_serv{$hostname});
15253: }
15254:
1.1 albertel 15255: }
15256:
1.847 albertel 15257: {
15258: my %iphost;
1.856 albertel 15259: my %name_to_ip;
15260: my %lonid_to_ip;
1.869 albertel 15261:
1.847 albertel 15262: sub get_hosts_from_ip {
15263: my ($ip) = @_;
15264: my %iphosts = &get_iphost();
15265: if (ref($iphosts{$ip})) {
15266: return @{$iphosts{$ip}};
15267: }
15268: return;
1.839 albertel 15269: }
1.864 albertel 15270:
15271: sub reset_hosts_ip_info {
15272: undef(%iphost);
15273: undef(%name_to_ip);
15274: undef(%lonid_to_ip);
15275: }
1.856 albertel 15276:
15277: sub get_host_ip {
15278: my ($lonid) = @_;
15279: if (exists($lonid_to_ip{$lonid})) {
15280: return $lonid_to_ip{$lonid};
15281: }
15282: my $name=&hostname($lonid);
15283: my $ip = gethostbyname($name);
15284: return if (!$ip || length($ip) ne 4);
15285: $ip=inet_ntoa($ip);
15286: $name_to_ip{$name} = $ip;
15287: $lonid_to_ip{$lonid} = $ip;
15288: return $ip;
15289: }
1.847 albertel 15290:
15291: sub get_iphost {
1.1172.2.70 raeburn 15292: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15293:
1.869 albertel 15294: if (!$ignore_cache) {
15295: if (%iphost) {
15296: return %iphost;
15297: }
15298: my ($ip_info,$cached)=
15299: &Apache::lonnet::is_cached_new('iphost','iphost');
15300: if ($cached) {
15301: %iphost = %{$ip_info->[0]};
15302: %name_to_ip = %{$ip_info->[1]};
15303: %lonid_to_ip = %{$ip_info->[2]};
15304: return %iphost;
15305: }
15306: }
1.894 albertel 15307:
15308: # get yesterday's info for fallback
15309: my %old_name_to_ip;
15310: my ($ip_info,$cached)=
15311: &Apache::lonnet::is_cached_new('iphost','iphost');
15312: if ($cached) {
15313: %old_name_to_ip = %{$ip_info->[1]};
15314: }
15315:
1.1172.2.70 raeburn 15316: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15317: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15318: my $ip;
15319: if (!exists($name_to_ip{$name})) {
15320: $ip = gethostbyname($name);
15321: if (!$ip || length($ip) ne 4) {
1.894 albertel 15322: if (defined($old_name_to_ip{$name})) {
15323: $ip = $old_name_to_ip{$name};
15324: &logthis("Can't find $name defaulting to old $ip");
15325: } else {
15326: &logthis("Name $name no IP found");
15327: next;
15328: }
15329: } else {
15330: $ip=inet_ntoa($ip);
1.847 albertel 15331: }
15332: $name_to_ip{$name} = $ip;
15333: } else {
15334: $ip = $name_to_ip{$name};
1.653 albertel 15335: }
1.888 albertel 15336: foreach my $id (@{ $name_to_host{$name} }) {
15337: $lonid_to_ip{$id} = $ip;
15338: }
15339: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15340: }
1.1172.2.70 raeburn 15341: unless ($nocache) {
15342: &do_cache_new('iphost','iphost',
15343: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15344: 48*60*60);
15345: }
1.869 albertel 15346:
1.847 albertel 15347: return %iphost;
1.598 albertel 15348: }
15349:
1.992 raeburn 15350: #
15351: # Given a DNS returns the loncapa host name for that DNS
15352: #
15353: sub host_from_dns {
15354: my ($dns) = @_;
15355: my @hosts;
15356: my $ip;
15357:
1.993 raeburn 15358: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15359: $ip = $name_to_ip{$dns};
15360: }
15361: if (!$ip) {
15362: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15363: if (length($ip) == 4) {
15364: $ip = &IO::Socket::inet_ntoa($ip);
15365: }
15366: }
15367: if ($ip) {
15368: @hosts = get_hosts_from_ip($ip);
15369: return $hosts[0];
15370: }
15371: return undef;
1.986 foxr 15372: }
1.992 raeburn 15373:
1.1074 raeburn 15374: sub get_internet_names {
15375: my ($lonid) = @_;
15376: return if ($lonid eq '');
15377: my ($idnref,$cached)=
15378: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15379: if ($cached) {
15380: return $idnref;
15381: }
15382: my $ip = &get_host_ip($lonid);
15383: my @hosts = &get_hosts_from_ip($ip);
15384: my %iphost = &get_iphost();
15385: my (@idns,%seen);
15386: foreach my $id (@hosts) {
15387: my $dom = &host_domain($id);
15388: my $prim_id = &domain($dom,'primary');
15389: my $prim_ip = &get_host_ip($prim_id);
15390: next if ($seen{$prim_ip});
15391: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15392: foreach my $id (@{$iphost{$prim_ip}}) {
15393: my $intdom = &internet_dom($id);
15394: unless (grep(/^\Q$intdom\E$/,@idns)) {
15395: push(@idns,$intdom);
15396: }
15397: }
15398: }
15399: $seen{$prim_ip} = 1;
15400: }
1.1172.2.23 raeburn 15401: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15402: }
15403:
1.986 foxr 15404: }
15405:
1.1079 raeburn 15406: sub all_loncaparevs {
1.1172.2.39 raeburn 15407: 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 15408: }
15409:
1.1172.2.27 raeburn 15410: # ------------------------------------------------------- Read loncaparev table
15411: {
15412: sub load_loncaparevs {
15413: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 15414: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 15415: while (my $configline=<$config>) {
15416: chomp($configline);
15417: my ($hostid,$loncaparev)=split(/:/,$configline);
15418: $loncaparevs{$hostid}=$loncaparev;
15419: }
15420: close($config);
15421: }
15422: }
15423: }
15424: }
15425:
15426: # ----------------------------------------------------- Read serverhostID table
15427: {
15428: sub load_serverhomeIDs {
15429: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 15430: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 15431: while (my $configline=<$config>) {
15432: chomp($configline);
15433: my ($name,$id)=split(/:/,$configline);
15434: $serverhomeIDs{$name}=$id;
15435: }
15436: close($config);
15437: }
15438: }
15439: }
15440: }
15441:
15442:
1.862 albertel 15443: BEGIN {
15444:
15445: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15446: unless ($readit) {
15447: {
15448: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15449: %perlvar = (%perlvar,%{$configvars});
15450: }
15451:
15452:
1.1 albertel 15453: # ------------------------------------------------------ Read spare server file
15454: {
1.1172.2.96 raeburn 15455: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15456:
15457: while (my $configline=<$config>) {
15458: chomp($configline);
1.284 matthew 15459: if ($configline) {
1.784 albertel 15460: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15461: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15462: push(@{ $spareid{$type} }, $host);
1.1 albertel 15463: }
15464: }
1.448 albertel 15465: close($config);
1.1 albertel 15466: }
1.11 www 15467: # ------------------------------------------------------------ Read permissions
15468: {
1.1172.2.96 raeburn 15469: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15470:
15471: while (my $configline=<$config>) {
1.448 albertel 15472: chomp($configline);
15473: if ($configline) {
15474: my ($role,$perm)=split(/ /,$configline);
15475: if ($perm ne '') { $pr{$role}=$perm; }
15476: }
1.11 www 15477: }
1.448 albertel 15478: close($config);
1.11 www 15479: }
15480:
15481: # -------------------------------------------- Read plain texts for permissions
15482: {
1.1172.2.96 raeburn 15483: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15484:
15485: while (my $configline=<$config>) {
1.448 albertel 15486: chomp($configline);
15487: if ($configline) {
1.742 raeburn 15488: my ($short,@plain)=split(/:/,$configline);
15489: %{$prp{$short}} = ();
15490: if (@plain > 0) {
15491: $prp{$short}{'std'} = $plain[0];
15492: for (my $i=1; $i<@plain; $i++) {
15493: $prp{$short}{'alt'.$i} = $plain[$i];
15494: }
15495: }
1.448 albertel 15496: }
1.135 www 15497: }
1.448 albertel 15498: close($config);
1.135 www 15499: }
15500:
15501: # ---------------------------------------------------------- Read package table
15502: {
1.1172.2.96 raeburn 15503: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15504:
15505: while (my $configline=<$config>) {
1.483 albertel 15506: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15507: chomp($configline);
15508: my ($short,$plain)=split(/:/,$configline);
15509: my ($pack,$name)=split(/\&/,$short);
15510: if ($plain ne '') {
15511: $packagetab{$pack.'&'.$name.'&name'}=$name;
15512: $packagetab{$short}=$plain;
15513: }
1.11 www 15514: }
1.448 albertel 15515: close($config);
1.329 matthew 15516: }
15517:
1.1172.2.27 raeburn 15518: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 15519:
1.1172.2.27 raeburn 15520: &load_loncaparevs();
15521:
15522: # ------------------------------------------------------- Read serverhostID table
15523:
15524: &load_serverhomeIDs();
1.1074 raeburn 15525:
1.1172.2.27 raeburn 15526: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15527: {
15528: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15529: if (-e $file) {
15530: my $parser = HTML::LCParser->new($file);
15531: while (my $token = $parser->get_token()) {
15532: if ($token->[0] eq 'S') {
15533: my $item = $token->[1];
15534: my $name = $token->[2]{'name'};
15535: my $value = $token->[2]{'value'};
15536: if ($item ne '' && $name ne '' && $value ne '') {
15537: my $release = $parser->get_text();
15538: $release =~ s/(^\s*|\s*$ )//gx;
15539: $needsrelease{$item.':'.$name.':'.$value} = $release;
15540: }
15541: }
15542: }
15543: }
1.1073 raeburn 15544: }
15545:
1.1138 raeburn 15546: # ---------------------------------------------------------- Read managers table
15547: {
15548: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 15549: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15550: while (my $configline=<$config>) {
15551: chomp($configline);
15552: next if ($configline =~ /^\#/);
15553: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15554: $managerstab{$configline} = 1;
15555: }
15556: }
15557: close($config);
15558: }
15559: }
15560: }
15561:
1.329 matthew 15562: # ------------- set up temporary directory
15563: {
1.1117 foxr 15564: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15565:
1.11 www 15566: }
15567:
1.1172.2.104 raeburn 15568: # ------------- set default texengine (domain default overrides this)
15569: {
15570: $deftex = LONCAPA::texengine();
15571: }
15572:
1.1172.2.114 raeburn 15573: # ------------- set default minimum length for passwords for internal auth users
15574: {
15575: $passwdmin = LONCAPA::passwd_min();
15576: }
15577:
1.794 albertel 15578: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15579: 'compress_threshold'=> 20_000,
15580: });
1.185 www 15581:
1.281 www 15582: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15583: $dumpcount=0;
1.958 www 15584: $locknum=0;
1.22 www 15585:
1.163 harris41 15586: &logtouch();
1.672 albertel 15587: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15588: $readit=1;
1.564 albertel 15589: {
15590: use integer;
15591: my $test=(2**32)+1;
1.568 albertel 15592: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15593: &logthis(" Detected 64bit platform ($_64bit)");
15594: }
1.195 www 15595: }
1.1 albertel 15596: }
1.179 www 15597:
1.1 albertel 15598: 1;
1.191 harris41 15599: __END__
15600:
1.243 albertel 15601: =pod
15602:
1.191 harris41 15603: =head1 NAME
15604:
1.243 albertel 15605: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15606:
15607: =head1 SYNOPSIS
15608:
1.243 albertel 15609: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15610:
15611: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15612:
1.243 albertel 15613: Common parameters:
15614:
15615: =over 4
15616:
15617: =item *
15618:
15619: $uname : an internal username (if $cname expecting a course Id specifically)
15620:
15621: =item *
15622:
15623: $udom : a domain (if $cdom expecting a course's domain specifically)
15624:
15625: =item *
15626:
15627: $symb : a resource instance identifier
15628:
15629: =item *
15630:
15631: $namespace : the name of a .db file that contains the data needed or
15632: being set.
15633:
15634: =back
15635:
1.394 bowersj2 15636: =head1 OVERVIEW
1.191 harris41 15637:
1.394 bowersj2 15638: lonnet provides subroutines which interact with the
15639: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15640: about classes, users, and resources.
1.243 albertel 15641:
15642: For many of these objects you can also use this to store data about
15643: them or modify them in various ways.
1.191 harris41 15644:
1.394 bowersj2 15645: =head2 Symbs
1.191 harris41 15646:
1.394 bowersj2 15647: To identify a specific instance of a resource, LON-CAPA uses symbols
15648: or "symbs"X<symb>. These identifiers are built from the URL of the
15649: map, the resource number of the resource in the map, and the URL of
15650: the resource itself. The latter is somewhat redundant, but might help
15651: if maps change.
15652:
15653: An example is
15654:
15655: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15656:
15657: The respective map entry is
15658:
15659: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15660: title="Problem 2">
15661: </resource>
15662:
15663: Symbs are used by the random number generator, as well as to store and
15664: restore data specific to a certain instance of for example a problem.
15665:
15666: =head2 Storing And Retrieving Data
15667:
15668: X<store()>X<cstore()>X<restore()>Three of the most important functions
15669: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15670: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15671: is is the non-critical message twin of cstore. These functions are for
15672: handlers to store a perl hash to a user's permanent data space in an
15673: easy manner, and to retrieve it again on another call. It is expected
15674: that a handler would use this once at the beginning to retrieve data,
15675: and then again once at the end to send only the new data back.
15676:
15677: The data is stored in the user's data directory on the user's
15678: homeserver under the ID of the course.
15679:
15680: The hash that is returned by restore will have all of the previous
15681: value for all of the elements of the hash.
15682:
15683: Example:
15684:
15685: #creating a hash
15686: my %hash;
15687: $hash{'foo'}='bar';
15688:
15689: #storing it
15690: &Apache::lonnet::cstore(\%hash);
15691:
15692: #changing a value
15693: $hash{'foo'}='notbar';
15694:
15695: #adding a new value
15696: $hash{'bar'}='foo';
15697: &Apache::lonnet::cstore(\%hash);
15698:
15699: #retrieving the hash
15700: my %history=&Apache::lonnet::restore();
15701:
15702: #print the hash
15703: foreach my $key (sort(keys(%history))) {
15704: print("\%history{$key} = $history{$key}");
15705: }
15706:
15707: Will print out:
1.191 harris41 15708:
1.394 bowersj2 15709: %history{1:foo} = bar
15710: %history{1:keys} = foo:timestamp
15711: %history{1:timestamp} = 990455579
15712: %history{2:bar} = foo
15713: %history{2:foo} = notbar
15714: %history{2:keys} = foo:bar:timestamp
15715: %history{2:timestamp} = 990455580
15716: %history{bar} = foo
15717: %history{foo} = notbar
15718: %history{timestamp} = 990455580
15719: %history{version} = 2
15720:
15721: Note that the special hash entries C<keys>, C<version> and
15722: C<timestamp> were added to the hash. C<version> will be equal to the
15723: total number of versions of the data that have been stored. The
15724: C<timestamp> attribute will be the UNIX time the hash was
15725: stored. C<keys> is available in every historical section to list which
15726: keys were added or changed at a specific historical revision of a
15727: hash.
15728:
15729: B<Warning>: do not store the hash that restore returns directly. This
15730: will cause a mess since it will restore the historical keys as if the
15731: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15732:
1.394 bowersj2 15733: Calling convention:
1.191 harris41 15734:
1.1172.2.27 raeburn 15735: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 15736: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15737:
1.394 bowersj2 15738: For more detailed information, see lonnet specific documentation.
1.191 harris41 15739:
1.394 bowersj2 15740: =head1 RETURN MESSAGES
1.191 harris41 15741:
1.394 bowersj2 15742: =over 4
1.191 harris41 15743:
1.394 bowersj2 15744: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15745:
1.394 bowersj2 15746: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15747: when the connection is brought back up
1.191 harris41 15748:
1.394 bowersj2 15749: =item * B<con_failed>: unable to contact remote host and unable to save message
15750: for later delivery
1.191 harris41 15751:
1.967 bisitz 15752: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15753:
1.394 bowersj2 15754: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15755: that was requested
1.191 harris41 15756:
1.243 albertel 15757: =back
1.191 harris41 15758:
1.243 albertel 15759: =head1 PUBLIC SUBROUTINES
1.191 harris41 15760:
1.243 albertel 15761: =head2 Session Environment Functions
1.191 harris41 15762:
1.243 albertel 15763: =over 4
1.191 harris41 15764:
1.394 bowersj2 15765: =item *
15766: X<appenv()>
1.949 raeburn 15767: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15768: the user envirnoment file, and will be restored for each access this
1.620 albertel 15769: user makes during this session, also modifies the %env for the current
1.949 raeburn 15770: process. Optional rolesarrayref - if defined contains a reference to an array
15771: of roles which are exempt from the restriction on modifying user.role entries
15772: in the user's environment.db and in %env.
1.191 harris41 15773:
15774: =item *
1.394 bowersj2 15775: X<delenv()>
1.987 raeburn 15776: B<delenv($delthis,$regexp)>: removes all items from the session
15777: environment file that begin with $delthis. If the
15778: optional second arg - $regexp - is true, $delthis is treated as a
15779: regular expression, otherwise \Q$delthis\E is used.
15780: The values are also deleted from the current processes %env.
1.191 harris41 15781:
1.795 albertel 15782: =item * get_env_multiple($name)
15783:
15784: gets $name from the %env hash, it seemlessly handles the cases where multiple
15785: values may be defined and end up as an array ref.
15786:
15787: returns an array of values
15788:
1.243 albertel 15789: =back
15790:
15791: =head2 User Information
1.191 harris41 15792:
1.243 albertel 15793: =over 4
1.191 harris41 15794:
15795: =item *
1.394 bowersj2 15796: X<queryauthenticate()>
15797: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15798: authentication scheme
15799:
15800: =item *
1.394 bowersj2 15801: X<authenticate()>
1.1073 raeburn 15802: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15803: authenticate user from domain's lib servers (first use the current
15804: one). C<$upass> should be the users password.
1.1073 raeburn 15805: $checkdefauth is optional (value is 1 if a check should be made to
15806: authenticate user using default authentication method, and allow
15807: account creation if username does not have account in the domain).
15808: $clientcancheckhost is optional (value is 1 if checking whether the
15809: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15810:
15811: =item *
1.394 bowersj2 15812: X<homeserver()>
15813: B<homeserver($uname,$udom)>: find the server which has
15814: the user's directory and files (there must be only one), this caches
15815: the answer, and also caches if there is a borken connection.
1.191 harris41 15816:
15817: =item *
1.394 bowersj2 15818: X<idget()>
15819: B<idget($udom,@ids)>: find the usernames behind a list of IDs
15820: (IDs are a unique resource in a domain, there must be only 1 ID per
15821: username, and only 1 username per ID in a specific domain) (returns
15822: hash: id=>name,id=>name)
1.191 harris41 15823:
15824: =item *
1.394 bowersj2 15825: X<idrget()>
15826: B<idrget($udom,@unames)>: find the IDs behind a list of
15827: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15828:
15829: =item *
1.394 bowersj2 15830: X<idput()>
15831: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 15832:
15833: =item *
1.394 bowersj2 15834: X<rolesinit()>
1.1169 droeschl 15835: B<rolesinit($udom,$username)>: get user privileges.
15836: returns user role, first access and timer interval hashes
1.243 albertel 15837:
15838: =item *
1.1171 droeschl 15839: X<privileged()>
15840: B<privileged($username,$domain)>: returns a true if user has a
15841: privileged and active role (i.e. su or dc), false otherwise.
15842:
15843: =item *
1.551 albertel 15844: X<getsection()>
15845: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15846: course $cname, return section name/number or '' for "not in course"
15847: and '-1' for "no section"
15848:
15849: =item *
1.394 bowersj2 15850: X<userenvironment()>
15851: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15852: passed in @what from the requested user's environment, returns a hash
15853:
1.858 raeburn 15854: =item *
15855: X<userlog_query()>
1.859 albertel 15856: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15857: activity.log file. %filters defines filters applied when parsing the
15858: log file. These can be start or end timestamps, or the type of action
15859: - log to look for Login or Logout events, check for Checkin or
15860: Checkout, role for role selection. The response is in the form
15861: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15862: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15863:
1.243 albertel 15864: =back
15865:
15866: =head2 User Roles
15867:
15868: =over 4
15869:
15870: =item *
15871:
1.1172.2.65 raeburn 15872: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15873: returns codes for allowed actions.
15874:
15875: The first argument is required, all others are optional.
15876:
15877: $priv is the privilege being checked.
15878: $uri contains additional information about what is being checked for access (e.g.,
15879: URL, course ID etc.).
15880: $symb is the unique resource instance identifier in a course; if needed,
15881: but not provided, it will be retrieved via a call to &symbread().
15882: $role is the role for which a priv is being checked (only used if priv is evb).
15883: $clientip is the user's IP address (only used when checking for access to portfolio
15884: files).
15885: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15886: prevents recursive calls to &allowed.
15887:
1.243 albertel 15888: F: full access
15889: U,I,K: authentication modes (cxx only)
15890: '': forbidden
15891: 1: user needs to choose course
15892: 2: browse allowed
1.766 albertel 15893: A: passphrase authentication needed
1.1172.2.65 raeburn 15894: B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146. .1(raebu 15895:22): D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15896:
15897: =item *
15898:
1.1172.2.13 raeburn 15899: constructaccess($url,$setpriv) : check for access to construction space URL
15900:
15901: See if the owner domain and name in the URL match those in the
15902: expected environment. If so, return three element list
15903: ($ownername,$ownerdomain,$ownerhome).
15904:
15905: Otherwise return the null string.
15906:
15907: If second argument 'setpriv' is true, it assigns the privileges,
15908: and returns the same three element list, unless the owner has
15909: blocked "ad hoc" Domain Coordinator access to the Author Space,
15910: in which case the null string is returned.
15911:
15912: =item *
15913:
1.1172.2.84 raeburn 15914: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15915: define a custom role rolename set privileges in format of lonTabs/roles.tab
15916: for system, domain, and course level. $uname and $udom are optional (current
15917: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15918:
15919: =item *
15920:
1.988 raeburn 15921: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15922: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15923: $type is Course (default) or Community.
1.988 raeburn 15924: If $forcedefault evaluates to true, text returned will be default
15925: text for $type. Otherwise, if this is a course, the text returned
15926: will be a custom name for the role (if defined in the course's
15927: environment). If no custom name is defined the default is returned.
15928:
1.832 raeburn 15929: =item *
15930:
1.1172.2.23 raeburn 15931: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15932: All arguments are optional. Returns a hash of a roles, either for
15933: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15934: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15935: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15936: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15937: For each key, value is set to colon-separated start and end times for
15938: the role. If no username and domain are specified, will default to
1.934 raeburn 15939: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15940: of role statuses (active, future or previous), roles
15941: (e.g., cc,in, st etc.) and domains of the roles which can be used
15942: to restrict the list of roles reported. If no array ref is
15943: provided for types, will default to return only active roles.
1.834 albertel 15944:
1.1172.2.13 raeburn 15945: =item *
15946:
15947: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15948: user: $uname:$udom has a role in the course: $cdom_$cnum.
15949:
15950: Additional optional arguments are: $type (if role checking is to be restricted
15951: to certain user status types -- previous (expired roles), active (currently
15952: available roles) or future (roles available in the future), and
15953: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15954: have active Domain Coordinator role in course's domain or in additional
15955: domains (specified in 'Domains to check for privileged users' in course
15956: environment -- set via: Course Settings -> Classlists and staff listing).
15957:
15958: =item *
15959:
15960: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15961: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15962: $possdomains and $possroles are optional array refs -- to domains to check and
15963: roles to check. If $possdomains is not specified, a dump will be done of the
15964: users' roles.db to check for a dc or su role in any domain. This can be
15965: time consuming if &privileged is called repeatedly (e.g., when displaying a
15966: classlist), so in such cases, supplying a $possdomains array is preferred, as
15967: this then allows &privileged_by_domain() to be used, which caches the identity
15968: of privileged users, eliminating the need for repeated calls to &dump().
15969:
15970: =item *
15971:
15972: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15973: where the outer hash keys are domains specified in the $possdomains array ref,
15974: next inner hash keys are privileged roles specified in the $roles array ref,
15975: and the innermost hash contains key = value pairs for username:domain = end:start
15976: for active or future "privileged" users with that role in that domain. To avoid
15977: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15978: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15979:
1.243 albertel 15980: =back
15981:
15982: =head2 User Modification
15983:
15984: =over 4
15985:
15986: =item *
15987:
1.957 raeburn 15988: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15989: user for the level given by URL. Optional start and end dates (leave empty
15990: string or zero for "no date")
1.191 harris41 15991:
15992: =item *
15993:
1.243 albertel 15994: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15995: change a users, password, possible return values are: ok,
15996: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15997: refused
1.191 harris41 15998:
15999: =item *
16000:
1.243 albertel 16001: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16002:
16003: =item *
16004:
1.1058 raeburn 16005: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16006: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16007:
16008: will update user information (firstname,middlename,lastname,generation,
16009: permanentemail), and if forceid is true, student/employee ID also.
16010: A user's institutional affiliation(s) can also be updated.
16011: User information fields will not be overwritten with empty entries
16012: unless the field is included in the $candelete array reference.
16013: This array is included when a single user is modified via "Manage Users",
16014: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16015:
16016: =item *
16017:
1.286 matthew 16018: modifystudent
16019:
1.957 raeburn 16020: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 16021: The course id is resolved based on the current user's environment.
16022: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16023: associated with a course.
16024:
1.297 matthew 16025: This call is essentially a wrapper for lonnet::modifyuser and
16026: lonnet::modify_student_enrollment
1.286 matthew 16027:
16028: Inputs:
16029:
16030: =over 4
16031:
1.957 raeburn 16032: =item B<$udom> Student's loncapa domain
1.286 matthew 16033:
1.957 raeburn 16034: =item B<$uname> Student's loncapa login name
1.286 matthew 16035:
1.964 bisitz 16036: =item B<$uid> Student/Employee ID
1.286 matthew 16037:
1.957 raeburn 16038: =item B<$umode> Student's authentication mode
1.286 matthew 16039:
1.957 raeburn 16040: =item B<$upass> Student's password
1.286 matthew 16041:
1.957 raeburn 16042: =item B<$first> Student's first name
1.286 matthew 16043:
1.957 raeburn 16044: =item B<$middle> Student's middle name
1.286 matthew 16045:
1.957 raeburn 16046: =item B<$last> Student's last name
1.286 matthew 16047:
1.957 raeburn 16048: =item B<$gene> Student's generation
1.286 matthew 16049:
1.957 raeburn 16050: =item B<$usec> Student's section in course
1.286 matthew 16051:
16052: =item B<$end> Unix time of the roles expiration
16053:
16054: =item B<$start> Unix time of the roles start date
16055:
16056: =item B<$forceid> If defined, allow $uid to be changed
16057:
16058: =item B<$desiredhome> server to use as home server for student
16059:
1.957 raeburn 16060: =item B<$email> Student's permanent e-mail address
16061:
16062: =item B<$type> Type of enrollment (auto or manual)
16063:
1.963 raeburn 16064: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16065:
16066: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16067:
1.963 raeburn 16068: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16069:
1.963 raeburn 16070: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16071:
1.1172.2.19 raeburn 16072: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16073:
16074: =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 16075:
1.286 matthew 16076: =back
1.297 matthew 16077:
16078: =item *
16079:
16080: modify_student_enrollment
16081:
1.1172.2.31 raeburn 16082: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16083: 'role.request.course' must be defined for this function to proceed.
16084:
16085: Inputs:
16086:
16087: =over 4
16088:
1.1172.2.31 raeburn 16089: =item $udom, student's domain
1.297 matthew 16090:
1.1172.2.31 raeburn 16091: =item $uname, student's name
1.297 matthew 16092:
1.1172.2.31 raeburn 16093: =item $uid, student's user id
1.297 matthew 16094:
1.1172.2.31 raeburn 16095: =item $first, student's first name
1.297 matthew 16096:
16097: =item $middle
16098:
16099: =item $last
16100:
16101: =item $gene
16102:
16103: =item $usec
16104:
16105: =item $end
16106:
16107: =item $start
16108:
1.957 raeburn 16109: =item $type
16110:
16111: =item $locktype
16112:
16113: =item $cid
16114:
16115: =item $selfenroll
16116:
16117: =item $context
16118:
1.1172.2.19 raeburn 16119: =item $credits, number of credits student will earn from this class
16120:
1.1172.2.76 raeburn 16121: =item $instsec, institutional course section code for student
16122:
1.297 matthew 16123: =back
16124:
1.191 harris41 16125:
16126: =item *
16127:
1.243 albertel 16128: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16129: custom role; give a custom role to a user for the level given by URL. Specify
16130: name and domain of role author, and role name
1.191 harris41 16131:
16132: =item *
16133:
1.243 albertel 16134: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16135:
16136: =item *
16137:
1.243 albertel 16138: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16139:
16140: =back
16141:
16142: =head2 Course Infomation
16143:
16144: =over 4
1.191 harris41 16145:
16146: =item *
16147:
1.1118 foxr 16148: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16149: specified course id, including all environment settings for the
16150: course, the description of the course will be in the hash under the
16151: key 'description'
1.191 harris41 16152:
1.1118 foxr 16153: $options is an optional parameter that if supplied is a hash reference that controls
16154: what how this function works. It has the following key/values:
16155:
16156: =over 4
16157:
16158: =item freshen_cache
16159:
16160: If defined, and the environment cache for the course is valid, it is
16161: returned in the returned hash.
16162:
16163: =item one_time
16164:
16165: If defined, the last cache time is set to _now_
16166:
16167: =item user
16168:
16169: If defined, the supplied username is used instead of the current user.
16170:
16171:
16172: =back
16173:
1.191 harris41 16174: =item *
16175:
1.624 albertel 16176: resdata($name,$domain,$type,@which) : request for current parameter
16177: setting for a specific $type, where $type is either 'course' or 'user',
16178: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 16179: answers for 10 minutes.
1.243 albertel 16180:
1.877 foxr 16181: =item *
16182:
16183: get_courseresdata($courseid, $domain) : dump the entire course resource
16184: data base, returning a hash that is keyed by the resource name and has
16185: values that are the resource value. I believe that the timestamps and
16186: versions are also returned.
16187:
1.243 albertel 16188: =back
16189:
16190: =head2 Course Modification
16191:
16192: =over 4
1.191 harris41 16193:
16194: =item *
16195:
1.243 albertel 16196: writecoursepref($courseid,%prefs) : write preferences (environment
16197: database) for a course
1.191 harris41 16198:
16199: =item *
16200:
1.1011 raeburn 16201: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16202:
16203: =item *
16204:
1.1038 raeburn 16205: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16206:
1.1167 droeschl 16207: =item *
16208:
16209: is_course($courseid), is_course($cdom, $cnum)
16210:
16211: Accepts either a combined $courseid (in the form of domain_courseid) or the
16212: two component version $cdom, $cnum. It checks if the specified course exists.
16213:
16214: Returns:
16215: undef if the course doesn't exist, otherwise
16216: in scalar context the combined courseid.
16217: in list context the two components of the course identifier, domain and
16218: courseid.
16219:
1.243 albertel 16220: =back
16221:
1.1172.2.109 raeburn 16222: =head2 Bubblesheet Configuration
16223:
16224: =over 4
16225:
16226: =item *
16227:
16228: get_scantron_config($which)
16229:
16230: $which - the name of the configuration to parse from the file.
16231:
16232: Parses and returns the bubblesheet configuration line selected as a
16233: hash of configuration file fields.
16234:
16235:
16236: Returns:
16237: If the named configuration is not in the file, an empty
16238: hash is returned.
16239:
16240: a hash with the fields
16241: name - internal name for the this configuration setup
16242: description - text to display to operator that describes this config
16243: CODElocation - if 0 or the string 'none'
16244: - no CODE exists for this config
16245: if -1 || the string 'letter'
16246: - a CODE exists for this config and is
16247: a string of letters
16248: Unsupported value (but planned for future support)
16249: if a positive integer
16250: - The CODE exists as the first n items from
16251: the question section of the form
16252: if the string 'number'
16253: - The CODE exists for this config and is
16254: a string of numbers
16255: CODEstart - (only matter if a CODE exists) column in the line where
16256: the CODE starts
16257: CODElength - length of the CODE
16258: IDstart - column where the student/employee ID starts
16259: IDlength - length of the student/employee ID info
16260: Qstart - column where the information from the bubbled
16261: 'questions' start
16262: Qlength - number of columns comprising a single bubble line from
16263: the sheet. (usually either 1 or 10)
16264: Qon - either a single character representing the character used
16265: to signal a bubble was chosen in the positional setup, or
16266: the string 'letter' if the letter of the chosen bubble is
16267: in the final, or 'number' if a number representing the
16268: chosen bubble is in the file (1->A 0->J)
16269: Qoff - the character used to represent that a bubble was
16270: left blank
16271: PaperID - if the scanning process generates a unique number for each
16272: sheet scanned the column that this ID number starts in
16273: PaperIDlength - number of columns that comprise the unique ID number
16274: for the sheet of paper
16275: FirstName - column that the first name starts in
16276: FirstNameLength - number of columns that the first name spans
16277: LastName - column that the last name starts in
16278: LastNameLength - number of columns that the last name spans
16279: BubblesPerRow - number of bubbles available in each row used to
16280: bubble an answer. (If not specified, 10 assumed).
16281:
16282:
16283: =item *
16284:
16285: get_scantronformat_file($cdom)
16286:
16287: $cdom - the course's domain (optional); if not supplied, uses
16288: domain for current $env{'request.course.id'}.
16289:
16290: Returns an array containing lines from the scantron format file for
16291: the domain of the course.
16292:
16293: If a url for a custom.tab file is listed in domain's configuration.db,
16294: lines are from this file.
16295:
16296: Otherwise, if a default.tab has been published in RES space by the
16297: domainconfig user, lines are from this file.
16298:
16299: Otherwise, fall back to getting lines from the legacy file on the
16300: local server: /home/httpd/lonTabs/default_scantronformat.tab
16301:
16302: =back
16303:
1.243 albertel 16304: =head2 Resource Subroutines
16305:
16306: =over 4
1.191 harris41 16307:
16308: =item *
16309:
1.243 albertel 16310: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16311:
16312: =item *
16313:
1.243 albertel 16314: repcopy($filename) : subscribes to the requested file, and attempts to
16315: replicate from the owning library server, Might return
1.607 raeburn 16316: 'unavailable', 'not_found', 'forbidden', 'ok', or
16317: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16318: resource. Expects the local filesystem pathname
16319: (/home/httpd/html/res/....)
16320:
16321: =back
16322:
16323: =head2 Resource Information
16324:
16325: =over 4
1.191 harris41 16326:
16327: =item *
16328:
1.1172.2.28 raeburn 16329: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16330: and returns the value of a variety of different possible values,
16331: $varname should be a request string, and the other parameters can be
16332: used to specify who and what one is asking about. Ordinarily, $cid
16333: does not need to be specified, as it is retrived from
16334: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16335: within lonuserstate::loadmap() when initializing a course, before
16336: $env{'request.course.id'} has been set, so it needs to be provided
16337: in that one case.
1.243 albertel 16338:
16339: Possible values for $varname are environment.lastname (or other item
16340: from the envirnment hash), user.name (or someother aspect about the
16341: user), resource.0.maxtries (or some other part and parameter of a
16342: resource)
1.204 albertel 16343:
16344: =item *
16345:
1.243 albertel 16346: directcondval($number) : get current value of a condition; reads from a state
16347: string
1.204 albertel 16348:
16349: =item *
16350:
1.243 albertel 16351: condval($condidx) : value of condition index based on state
1.204 albertel 16352:
16353: =item *
16354:
1.1172.2.146. .13(raeb 16355:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16356: resource's metadata, $what should be either a specific key, or either
16357: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146. .13(raeb 16358:-23): packages that this resource currently uses, the last 3 arguments are
16359:-23): only used internally for recursive metadata.
16360:-23):
16361:-23): the toolsymb is only used where the uri is for an external tool (for which
16362:-23): the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16363:
16364: this function automatically caches all requests
1.191 harris41 16365:
16366: =item *
16367:
1.243 albertel 16368: metadata_query($query,$custom,$customshow) : make a metadata query against the
16369: network of library servers; returns file handle of where SQL and regex results
16370: will be stored for query
1.191 harris41 16371:
16372: =item *
16373:
1.1172.2.66 raeburn 16374: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16375: return symbolic list entry (all arguments optional).
16376:
16377: Args: filename is the filename (including path) for the file for which a symb
16378: is required; donotrecurse, if true will prevent calls to allowed() being made
16379: to check access status if more than one resource was found in the bighash
16380: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16381: a randompick); ignorecachednull, if true will prevent a symb of '' being
16382: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16383: cause possible symbs to be checked to determine if they are subject to content
16384: blocking, if so they will not be included as possible symbs; possibles is a
16385: ref to a hash, which, as a side effect, will be populated with all possible
16386: symbs (content blocking not tested).
16387:
1.243 albertel 16388: returns the data handle
1.191 harris41 16389:
16390: =item *
16391:
1.1172.2.17 raeburn 16392: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 16393: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16394: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 16395: on failure, user must be in a course, as it assumes the existence of
16396: the course initial hash, and uses $env('request.course.id'}. The third
16397: arg is an optional reference to a scalar. If this arg is passed in the
16398: call to symbverify, it will be set to 1 if the symb has been set to be
16399: encrypted; otherwise it will be null.
1.243 albertel 16400:
1.191 harris41 16401: =item *
16402:
1.243 albertel 16403: symbclean($symb) : removes versions numbers from a symb, returns the
16404: cleaned symb
1.191 harris41 16405:
16406: =item *
16407:
1.243 albertel 16408: is_on_map($uri) : checks if the $uri is somewhere on the current
16409: course map, user must be in a course for it to work.
1.191 harris41 16410:
16411: =item *
16412:
1.243 albertel 16413: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16414:
16415: =item *
16416:
1.243 albertel 16417: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16418: a random seed, all arguments are optional, if they aren't sent it uses the
16419: environment to derive them. Note: if symb isn't sent and it can't get one
16420: from &symbread it will use the current time as its return value
1.191 harris41 16421:
16422: =item *
16423:
1.243 albertel 16424: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16425: unfakeable, receipt
1.191 harris41 16426:
16427: =item *
16428:
1.620 albertel 16429: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16430:
16431: =item *
16432:
1.243 albertel 16433: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16434:
16435: =item *
16436:
1.243 albertel 16437: 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 16438:
16439: =item *
16440:
1.243 albertel 16441: 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 16442:
16443: =item *
16444:
1.243 albertel 16445: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16446:
16447: =item *
16448:
1.243 albertel 16449: devalidate($symb) : devalidate temporary spreadsheet calculations,
16450: forcing spreadsheet to reevaluate the resource scores next time.
16451:
1.1172.2.13 raeburn 16452: =item *
16453:
16454: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16455: when viewing in course context.
16456:
16457: input: six args -- filename (decluttered), course number, course domain,
16458: url, symb (if registered) and group (if this is a
16459: group item -- e.g., bulletin board, group page etc.).
16460:
16461: output: array of five scalars --
16462: $cfile -- url for file editing if editable on current server
16463: $home -- homeserver of resource (i.e., for author if published,
16464: or course if uploaded.).
16465: $switchserver -- 1 if server switch will be needed.
16466: $forceedit -- 1 if icon/link should be to go to edit mode
16467: $forceview -- 1 if icon/link should be to go to view mode
16468:
16469: =item *
16470:
16471: is_course_upload($file,$cnum,$cdom)
16472:
16473: Used in course context to determine if current file was uploaded to
16474: the course (i.e., would be found in /userfiles/docs on the course's
16475: homeserver.
16476:
16477: input: 3 args -- filename (decluttered), course number and course domain.
16478: output: boolean -- 1 if file was uploaded.
16479:
1.243 albertel 16480: =back
16481:
16482: =head2 Storing/Retreiving Data
16483:
16484: =over 4
1.191 harris41 16485:
16486: =item *
16487:
1.1172.2.64 raeburn 16488: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16489: permanently for this url; hashref needs to be given and should be a \%hashname;
16490: the remaining args aren't required and if they aren't passed or are '' they will
16491: be derived from the env (with the exception of $laststore, which is an
16492: optional arg used when a user's submission is stored in grading).
16493: $laststore is $version=$timestamp, where $version is the most recent version
16494: number retrieved for the corresponding $symb in the $namespace db file, and
16495: $timestamp is the timestamp for that transaction (UNIX time).
16496: $laststore is currently only passed when cstore() is called by
16497: structuretags::finalize_storage().
1.191 harris41 16498:
16499: =item *
16500:
1.1172.2.64 raeburn 16501: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16502: but uses critical subroutine
1.191 harris41 16503:
16504: =item *
16505:
1.243 albertel 16506: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16507: all args are optional
1.191 harris41 16508:
16509: =item *
16510:
1.717 albertel 16511: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16512: dumps the complete (or key matching regexp) namespace into a hash
16513: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16514: normally &store()ed into
16515:
16516: $range should be either an integer '100' (give me the first 100
16517: matching records)
16518: or be two integers sperated by a - with no spaces
16519: '30-50' (give me the 30th through the 50th matching
16520: records)
16521:
16522:
16523: =item *
16524:
1.1172.2.59 raeburn 16525: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16526: replaces a &store() version of data with a replacement set of data
16527: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 16528: reference. If $tolog is true, the transaction is logged in the courselog
16529: with an action=PUTSTORE.
1.717 albertel 16530:
16531: =item *
16532:
1.243 albertel 16533: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16534: works very similar to store/cstore, but all data is stored in a
16535: temporary location and can be reset using tmpreset, $storehash should
16536: be a hash reference, returns nothing on success
1.191 harris41 16537:
16538: =item *
16539:
1.243 albertel 16540: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16541: similar to restore, but all data is stored in a temporary location and
16542: can be reset using tmpreset. Returns a hash of values on success,
16543: error string otherwise.
1.191 harris41 16544:
16545: =item *
16546:
1.243 albertel 16547: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16548: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16549:
16550: =item *
16551:
1.243 albertel 16552: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16553: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16554:
16555: =item *
16556:
1.243 albertel 16557: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16558: namesp ($udom and $uname are optional)
1.191 harris41 16559:
16560: =item *
16561:
1.702 albertel 16562: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16563: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16564: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16565:
1.702 albertel 16566: $range should be either an integer '100' (give me the first 100
16567: matching records)
16568: or be two integers sperated by a - with no spaces
16569: '30-50' (give me the 30th through the 50th matching
16570: records)
1.449 matthew 16571: =item *
16572:
16573: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16574: $store can be a scalar, an array reference, or if the amount to be
16575: incremented is > 1, a hash reference.
16576:
16577: ($udom and $uname are optional)
1.191 harris41 16578:
16579: =item *
16580:
1.243 albertel 16581: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16582: ($udom and $uname are optional)
1.191 harris41 16583:
16584: =item *
16585:
1.243 albertel 16586: cput($namespace,$storehash,$udom,$uname) : critical put
16587: ($udom and $uname are optional)
1.191 harris41 16588:
16589: =item *
16590:
1.748 albertel 16591: newput($namespace,$storehash,$udom,$uname) :
16592:
16593: Attempts to store the items in the $storehash, but only if they don't
16594: currently exist, if this succeeds you can be certain that you have
16595: successfully created a new key value pair in the $namespace db.
16596:
16597:
16598: Args:
16599: $namespace: name of database to store values to
16600: $storehash: hashref to store to the db
16601: $udom: (optional) domain of user containing the db
16602: $uname: (optional) name of user caontaining the db
16603:
16604: Returns:
16605: 'ok' -> succeeded in storing all keys of $storehash
16606: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16607: least <key> already existed in the db (other
16608: requested keys may also already exist)
1.967 bisitz 16609: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16610: 'con_lost' -> unable to contact request server
16611: 'refused' -> action was not allowed by remote machine
16612:
16613:
16614: =item *
16615:
1.243 albertel 16616: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16617: reference filled in from namesp (encrypts the return communication)
16618: ($udom and $uname are optional)
1.191 harris41 16619:
16620: =item *
16621:
1.243 albertel 16622: log($udom,$name,$home,$message) : write to permanent log for user; use
16623: critical subroutine
16624:
1.806 raeburn 16625: =item *
16626:
1.860 raeburn 16627: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16628: array reference filled in from namespace found in domain level on either
16629: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16630:
16631: =item *
16632:
1.860 raeburn 16633: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16634: domain level either on specified domain server ($uhome) or primary domain
16635: server ($udom and $uhome are optional)
1.806 raeburn 16636:
1.943 raeburn 16637: =item *
16638:
1.1172.2.35 raeburn 16639: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16640: for: authentication, language, quotas, timezone, date locale, and portal URL in
16641: the target domain.
16642:
16643: May also include additional key => value pairs for the following groups:
16644:
16645: =over
16646:
16647: =item
16648: disk quotas (MB allocated by default to portfolios and authoring spaces).
16649:
16650: =over
16651:
16652: =item defaultquota, authorquota
16653:
16654: =back
16655:
16656: =item
16657: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16658: portfolio for users).
16659:
16660: =over
16661:
16662: =item
16663: aboutme, blog, webdav, portfolio
16664:
16665: =back
16666:
16667: =item
16668: requestcourses: ability to request courses, and how requests are processed.
16669:
16670: =over
16671:
16672: =item
1.1172.2.37 raeburn 16673: official, unofficial, community, textbook
1.1172.2.35 raeburn 16674:
16675: =back
16676:
16677: =item
16678: inststatus: types of institutional affiliation, and order in which they are displayed.
16679:
16680: =over
16681:
16682: =item
1.1172.2.44 raeburn 16683: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 16684:
16685: =back
16686:
16687: =item
16688: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16689: for course's uploaded content.
16690:
16691: =over
16692:
16693: =item
1.1172.2.68 raeburn 16694: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16695: communityquota, textbookquota
1.1172.2.35 raeburn 16696:
16697: =back
16698:
16699: =item
16700: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16701: on your servers.
16702:
16703: =over
16704:
16705: =item
16706: remotesessions, hostedsessions
16707:
16708: =back
16709:
16710: =back
16711:
16712: In cases where a domain coordinator has never used the "Set Domain Configuration"
16713: utility to create a configuration.db file on a domain's primary library server
16714: only the following domain defaults: auth_def, auth_arg_def, lang_def
16715: -- corresponding values are authentication type (internal, krb4, krb5,
16716: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16717: will be available. Values are retrieved from cache (if current), unless the
16718: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16719: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16720:
16721: Typical usage:
1.943 raeburn 16722:
1.1172.2.35 raeburn 16723: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16724:
1.243 albertel 16725: =back
16726:
16727: =head2 Network Status Functions
16728:
16729: =over 4
1.191 harris41 16730:
16731: =item *
16732:
1.1137 raeburn 16733: dirlist() : return directory list based on URI (first arg).
16734:
16735: Inputs: 1 required, 5 optional.
16736:
16737: =over
16738:
16739: =item
16740: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16741:
16742: =item
16743: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16744:
16745: =item
16746: $username - username of user/course to be listed. Extracted from $uri if absent.
16747:
16748: =item
16749: $getpropath - boolean: 1 if prepend path using &propath().
16750:
16751: =item
16752: $getuserdir - boolean: 1 if prepend path for "userfiles".
16753:
16754: =item
16755: $alternateRoot - path to prepend in place of path from $uri.
16756:
16757: =back
16758:
16759: Returns: Array of up to two items.
16760:
16761: =over
16762:
16763: a reference to an array of files/subdirectories
16764:
16765: =over
16766:
16767: Each element in the array of files/subdirectories is a & separated list of
16768: item name and the result of running stat on the item. If dirlist was requested
16769: for a file instead of a directory, the item name will be ''. For a directory
16770: listing, if the item is a metadata file, the element will end &N&M
16771: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16772: default copyright set (1).
16773:
16774: =back
16775:
16776: a scalar containing error condition (if encountered).
16777:
16778: =over
16779:
16780: =item
16781: no_host (no homeserver identified for $username:$domain).
16782:
16783: =item
16784: no_such_host (server contacted for listing not identified as valid host).
16785:
16786: =item
16787: con_lost (connection to remote server failed).
16788:
16789: =item
16790: refused (invalid $username:$domain received on lond side).
16791:
16792: =item
16793: no_such_dir (directory at specified path on lond side does not exist).
16794:
16795: =item
16796: empty (directory at specified path on lond side is empty).
16797:
16798: =over
16799:
16800: This is currently not encountered because the &ls3, &ls2,
16801: &ls (_handler) routines on the lond side do not filter out
16802: . and .. from a directory listing.
16803:
16804: =back
16805:
16806: =back
16807:
16808: =back
1.191 harris41 16809:
16810: =item *
16811:
1.243 albertel 16812: spareserver() : find server with least workload from spare.tab
16813:
1.986 foxr 16814:
16815: =item *
16816:
16817: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16818: if there is no corresponding loncapa host.
16819:
1.243 albertel 16820: =back
16821:
1.986 foxr 16822:
1.243 albertel 16823: =head2 Apache Request
16824:
16825: =over 4
1.191 harris41 16826:
16827: =item *
16828:
1.243 albertel 16829: ssi($url,%hash) : server side include, does a complete request cycle on url to
16830: localhost, posts hash
16831:
16832: =back
16833:
16834: =head2 Data to String to Data
16835:
16836: =over 4
1.191 harris41 16837:
16838: =item *
16839:
1.243 albertel 16840: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16841: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16842:
16843: =item *
16844:
1.243 albertel 16845: hashref2str($hashref) : convert a hashref into a string complete with
16846: escaping and '=' and '&' separators, supports elements that are
16847: arrayrefs and hashrefs
1.191 harris41 16848:
16849: =item *
16850:
1.243 albertel 16851: arrayref2str($arrayref) : convert an arrayref into a string complete
16852: with escaping and '&' separators, supports elements that are arrayrefs
16853: and hashrefs
1.191 harris41 16854:
16855: =item *
16856:
1.243 albertel 16857: str2hash($string) : convert string to hash using unescaping and
16858: splitting on '=' and '&', supports elements that are arrayrefs and
16859: hashrefs
1.191 harris41 16860:
16861: =item *
16862:
1.243 albertel 16863: str2array($string) : convert string to hash using unescaping and
16864: splitting on '&', supports elements that are arrayrefs and hashrefs
16865:
16866: =back
16867:
16868: =head2 Logging Routines
16869:
16870:
16871: These routines allow one to make log messages in the lonnet.log and
16872: lonnet.perm logfiles.
1.191 harris41 16873:
1.1119 foxr 16874: =over 4
16875:
1.191 harris41 16876: =item *
16877:
1.243 albertel 16878: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16879:
16880: =item *
16881:
1.243 albertel 16882: logthis() : append message to the normal lonnet.log file, it gets
16883: preiodically rolled over and deleted.
1.191 harris41 16884:
16885: =item *
16886:
1.243 albertel 16887: logperm() : append a permanent message to lonnet.perm.log, this log
16888: file never gets deleted by any automated portion of the system, only
16889: messages of critical importance should go in here.
16890:
1.1119 foxr 16891:
1.243 albertel 16892: =back
16893:
16894: =head2 General File Helper Routines
16895:
16896: =over 4
1.191 harris41 16897:
16898: =item *
16899:
1.481 raeburn 16900: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16901: (a) files in /uploaded
16902: (i) If a local copy of the file exists -
16903: compares modification date of local copy with last-modified date for
16904: definitive version stored on home server for course. If local copy is
16905: stale, requests a new version from the home server and stores it.
16906: If the original has been removed from the home server, then local copy
16907: is unlinked.
16908: (ii) If local copy does not exist -
16909: requests the file from the home server and stores it.
16910:
16911: If $caller is 'uploadrep':
16912: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16913: for request for files originally uploaded via DOCS.
16914: - returns 'ok' if fresh local copy now available, -1 otherwise.
16915:
16916: Otherwise:
16917: This indicates a call from the content generation phase of the request.
16918: - returns the entire contents of the file or -1.
16919:
16920: (b) files in /res
16921: - returns the entire contents of a file or -1;
16922: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16923:
1.712 albertel 16924:
16925: =item *
16926:
16927: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16928: reference
16929:
16930: returns either a stat() list of data about the file or an empty list
16931: if the file doesn't exist or couldn't find out about it (connection
16932: problems or user unknown)
16933:
1.191 harris41 16934: =item *
16935:
1.243 albertel 16936: filelocation($dir,$file) : returns file system location of a file
16937: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16938: directory that relative $file lookups are to looked in ($dir of /a/dir
16939: and a file of ../bob will become /a/bob)
1.191 harris41 16940:
16941: =item *
16942:
16943: hreflocation($dir,$file) : returns file system location or a URL; same as
16944: filelocation except for hrefs
16945:
16946: =item *
16947:
1.1172.2.49 raeburn 16948: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16949: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16950:
1.243 albertel 16951: =back
16952:
1.608 albertel 16953: =head2 Usererfile file routines (/uploaded*)
16954:
16955: =over 4
16956:
16957: =item *
16958:
16959: userfileupload(): main rotine for putting a file in a user or course's
16960: filespace, arguments are,
16961:
1.620 albertel 16962: formname - required - this is the name of the element in $env where the
1.608 albertel 16963: filename, and the contents of the file to create/modifed exist
1.620 albertel 16964: the filename is in $env{'form.'.$formname.'.filename'} and the
16965: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16966: context - if coursedoc, store the file in the course of the active role
16967: of the current user;
16968: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16969: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16970: subdir - required - subdirectory to put the file in under ../userfiles/
16971: if undefined, it will be placed in "unknown"
16972:
16973: (This routine calls clean_filename() to remove any dangerous
16974: characters from the filename, and then calls finuserfileupload() to
16975: complete the transaction)
16976:
16977: returns either the url of the uploaded file (/uploaded/....) if successful
16978: and /adm/notfound.html if unsuccessful
16979:
16980: =item *
16981:
16982: clean_filename(): routine for cleaing a filename up for storage in
16983: userfile space, argument is:
16984:
16985: filename - proposed filename
16986:
16987: returns: the new clean filename
16988:
16989: =item *
16990:
1.1090 raeburn 16991: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16992: userspace, probably shouldn't be called directly
16993:
16994: docuname: username or courseid of destination for the file
16995: docudom: domain of user/course of destination for the file
16996: formname: same as for userfileupload()
1.1090 raeburn 16997: fname: filename (including subdirectories) for the file
16998: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16999: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17000: allfiles: reference to hash used to store objects found by parser
17001: codebase: reference to hash used for codebases of java objects found by parser
17002: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17003: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17004: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17005: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17006: context: if 'overwrite', will move the uploaded file from its temporary location to
17007: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17008: mimetype: reference to scalar to accommodate mime type determined
17009: from File::MMagic if $parser = parse.
1.608 albertel 17010:
17011: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17012: and /adm/notfound.html if unsuccessful (or an error message if context
17013: was 'overwrite').
17014:
1.608 albertel 17015:
17016: =item *
17017:
17018: renameuserfile(): renames an existing userfile to a new name
17019:
17020: Args:
17021: docuname: username or courseid of destination for the file
17022: docudom: domain of user/course of destination for the file
17023: old: current file name (including any subdirs under userfiles)
17024: new: desired file name (including any subdirs under userfiles)
17025:
17026: =item *
17027:
17028: mkdiruserfile(): creates a directory is a userfiles dir
17029:
17030: Args:
17031: docuname: username or courseid of destination for the file
17032: docudom: domain of user/course of destination for the file
17033: dir: dir to create (including any subdirs under userfiles)
17034:
17035: =item *
17036:
17037: removeuserfile(): removes a file that exists in userfiles
17038:
17039: Args:
17040: docuname: username or courseid of destination for the file
17041: docudom: domain of user/course of destination for the file
17042: fname: filname to delete (including any subdirs under userfiles)
17043:
17044: =item *
17045:
17046: removeuploadedurl(): convience function for removeuserfile()
17047:
17048: Args:
17049: url: a full /uploaded/... url to delete
17050:
1.747 albertel 17051: =item *
17052:
17053: get_portfile_permissions():
17054: Args:
17055: domain: domain of user or course contain the portfolio files
17056: user: name of user or num of course contain the portfolio files
17057: Returns:
17058: hashref of a dump of the proper file_permissions.db
17059:
17060:
17061: =item *
17062:
17063: get_access_controls():
17064:
17065: Args:
17066: current_permissions: the hash ref returned from get_portfile_permissions()
17067: group: (optional) the group you want the files associated with
17068: file: (optional) the file you want access info on
17069:
17070: Returns:
1.749 raeburn 17071: a hash (keys are file names) of hashes containing
17072: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17073: values are XML containing access control settings (see below)
1.747 albertel 17074:
17075: Internal notes:
17076:
1.749 raeburn 17077: access controls are stored in file_permissions.db as key=value pairs.
17078: key -> path to file/file_name\0uniqueID:scope_end_start
17079: where scope -> public,guest,course,group,domains or users.
17080: end -> UNIX time for end of access (0 -> no end date)
17081: start -> UNIX time for start of access
17082:
17083: value -> XML description of access control
17084: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17085: <start></start>
17086: <end></end>
17087:
17088: <password></password> for scope type = guest
17089:
17090: <domain></domain> for scope type = course or group
17091: <number></number>
17092: <roles id="">
17093: <role></role>
17094: <access></access>
17095: <section></section>
17096: <group></group>
17097: </roles>
17098:
17099: <dom></dom> for scope type = domains
17100:
17101: <users> for scope type = users
17102: <user>
17103: <uname></uname>
17104: <udom></udom>
17105: </user>
17106: </users>
17107: </scope>
17108:
17109: Access data is also aggregated for each file in an additional key=value pair:
17110: key -> path to file/file_name\0accesscontrol
17111: value -> reference to hash
17112: hash contains key = value pairs
17113: where key = uniqueID:scope_end_start
17114: value = UNIX time record was last updated
17115:
17116: Used to improve speed of look-ups of access controls for each file.
17117:
17118: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17119:
1.1172.2.13 raeburn 17120: =item *
17121:
1.749 raeburn 17122: modify_access_controls():
17123:
17124: Modifies access controls for a portfolio file
17125: Args
17126: 1. file name
17127: 2. reference to hash of required changes,
17128: 3. domain
17129: 4. username
17130: where domain,username are the domain of the portfolio owner
17131: (either a user or a course)
17132:
17133: Returns:
17134: 1. result of additions or updates ('ok' or 'error', with error message).
17135: 2. result of deletions ('ok' or 'error', with error message).
17136: 3. reference to hash of any new or updated access controls.
17137: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17138: key = integer (inbound ID)
1.1172.2.13 raeburn 17139: value = uniqueID
17140:
17141: =item *
17142:
17143: get_timebased_id():
17144:
17145: Attempts to get a unique timestamp-based suffix for use with items added to a
17146: course via the Course Editor (e.g., folders, composite pages,
17147: group bulletin boards).
17148:
17149: Args: (first three required; six others optional)
17150:
17151: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17152: docssequence, or name of group
17153:
17154: 2. keyid (alphanumeric): name of temporary locking key in hash,
17155: e.g., num, boardids
17156:
17157: 3. namespace: name of gdbm file used to store suffixes already assigned;
17158: file will be named nohist_namespace.db
17159:
17160: 4. cdom: domain of course; default is current course domain from %env
17161:
17162: 5. cnum: course number; default is current course number from %env
17163:
17164: 6. idtype: set to concat if an additional digit is to be appended to the
17165: unix timestamp to form the suffix, if the plain timestamp is already
17166: in use. Default is to not do this, but simply increment the unix
17167: timestamp by 1 until a unique key is obtained.
17168:
17169: 7. who: holder of locking key; defaults to user:domain for user.
17170:
17171: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17172: retrying); default is 3.
17173:
17174: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17175:
17176: Returns:
17177:
17178: 1. suffix obtained (numeric)
17179:
17180: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17181:
17182: 3. error: contains (localized) error message if an error occurred.
17183:
1.747 albertel 17184:
1.608 albertel 17185: =back
17186:
1.243 albertel 17187: =head2 HTTP Helper Routines
17188:
17189: =over 4
17190:
1.191 harris41 17191: =item *
17192:
17193: escape() : unpack non-word characters into CGI-compatible hex codes
17194:
17195: =item *
17196:
17197: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17198:
1.243 albertel 17199: =back
17200:
17201: =head1 PRIVATE SUBROUTINES
17202:
17203: =head2 Underlying communication routines (Shouldn't call)
17204:
17205: =over 4
17206:
17207: =item *
17208:
17209: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17210:
17211: =item *
17212:
17213: reply() : uses subreply to send a message to remote machine, logs all failures
17214:
17215: =item *
17216:
17217: critical() : passes a critical message to another server; if cannot
17218: get through then place message in connection buffer directory and
17219: returns con_delayed, if incapable of saving message, returns
17220: con_failed
17221:
17222: =item *
17223:
17224: reconlonc() : tries to reconnect lonc client processes.
17225:
17226: =back
17227:
17228: =head2 Resource Access Logging
17229:
17230: =over 4
17231:
17232: =item *
17233:
17234: flushcourselogs() : flush (save) buffer logs and access logs
17235:
17236: =item *
17237:
17238: courselog($what) : save message for course in hash
17239:
17240: =item *
17241:
17242: courseacclog($what) : save message for course using &courselog(). Perform
17243: special processing for specific resource types (problems, exams, quizzes, etc).
17244:
1.191 harris41 17245: =item *
17246:
17247: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17248: as a PerlChildExitHandler
1.243 albertel 17249:
17250: =back
17251:
17252: =head2 Other
17253:
17254: =over 4
17255:
17256: =item *
17257:
17258: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17259:
17260: =back
17261:
17262: =cut
1.877 foxr 17263:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>