Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.146.2.22
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.146. .22(raeb 4:-24): # $Id: lonnet.pm,v 1.1172.2.146.2.21 2024/08/19 00:27:52 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:
1.1172.2.146. .22(raeb 3669:-24): #
3670:-24): # For /adm/viewcoauthors can only edit if author or co-author who is manager.
3671:-24): #
3672:-24):
3673:-24): if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
3674:-24): if (((&allowed('cca',"$cdom/$cnum")) ||
3675:-24): (&allowed('caa',"$cdom/$cnum"))) ||
3676:-24): ((&allowed('vca',"$cdom/$cnum") ||
3677:-24): &allowed('vaa',"$cdom/$cnum")) &&
3678:-24): ($env{"environment.internal.manager./$cdom/$cnum"}))) {
3679:-24): $home = $env{'user.home'};
3680:-24): $cfile = $resurl;
3681:-24): if ($env{'form.forceedit'}) {
3682:-24): $forceview = 1;
3683:-24): } else {
3684:-24): $forceedit = 1;
3685:-24): }
3686:-24): return ($cfile,$home,$switchserver,$forceedit,$forceview);
3687:-24): } else {
3688:-24): return;
3689:-24): }
3690:-24): }
3691:-24):
1.1172.2.13 raeburn 3692: if ($env{'request.course.id'}) {
3693: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3694: if ($group ne '') {
3695: # if this is a group homepage or group bulletin board, check group privs
3696: my $allowed = 0;
3697: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3698: if ((&allowed('mdg',$env{'request.course.id'}.
3699: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3700: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3701: $allowed = 1;
3702: }
3703: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3704: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3705: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3706: $allowed = 1;
3707: }
3708: }
3709: if ($allowed) {
3710: $home=&homeserver($cnum,$cdom);
3711: if ($env{'form.forceedit'}) {
3712: $forceview = 1;
3713: } else {
3714: $forceedit = 1;
3715: }
3716: $cfile = $resurl;
3717: } else {
3718: return;
3719: }
3720: } else {
1.1172.2.15 raeburn 3721: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3722: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3723: return;
3724: }
3725: } elsif (!$crsedit) {
1.1172.2.146. .21(raeb 3726:-24): if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1172.2.13 raeburn 3727: #
3728: # No edit allowed where CC has switched to student role.
3729: #
1.1172.2.146. .21(raeb 3730:-24): return;
3731:-24): } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
3732:-24): ($resurl =~ m{^/res/lib/templates/})) {
3733:-24): return;
3734:-24): }
1.1172.2.13 raeburn 3735: }
3736: }
3737: }
3738:
3739: if ($file ne '') {
3740: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3741: if (&is_course_upload($file,$cnum,$cdom)) {
3742: $uploaded = 1;
3743: $incourse = 1;
3744: if ($file =~/\.(htm|html|css|js|txt)$/) {
3745: $cfile = &hreflocation('',$file);
3746: if ($env{'form.forceedit'}) {
3747: $forceview = 1;
3748: } else {
3749: $forceedit = 1;
3750: }
3751: }
3752: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3753: $incourse = 1;
3754: if ($env{'form.forceedit'}) {
3755: $forceview = 1;
3756: } else {
3757: $forceedit = 1;
3758: }
3759: $cfile = $resurl;
3760: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3761: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3762: $incourse = 1;
3763: if ($env{'form.forceedit'}) {
3764: $forceview = 1;
3765: } else {
3766: $forceedit = 1;
3767: }
3768: $cfile = $resurl;
3769: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3770: $incourse = 1;
3771: $cfile = $resurl.'/smpedit';
3772: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3773: $incourse = 1;
3774: if ($env{'form.forceedit'}) {
3775: $forceview = 1;
3776: } else {
3777: $forceedit = 1;
3778: }
3779: $cfile = $resurl;
1.1172.2.122 raeburn 3780: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3781: my ($map,$id,$res) = &decode_symb($symb);
3782: if ($map =~ /\.page$/) {
3783: $incourse = 1;
3784: if ($env{'form.forceedit'}) {
3785: $forceview = 1;
3786: $cfile = $map;
3787: } else {
3788: $forceedit = 1;
3789: $cfile = '/adm/wrapper'.$resurl;
3790: }
3791: }
1.1172.2.146. .1(raebu 3792:22): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3793:22): $incourse = 1;
3794:22): if ($env{'form.forceedit'}) {
3795:22): $forceview = 1;
3796:22): } else {
3797:22): $forceedit = 1;
3798:22): }
3799:22): $cfile = $resurl;
1.1172.2.15 raeburn 3800: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3801: $incourse = 1;
3802: if ($env{'form.forceedit'}) {
3803: $forceview = 1;
3804: } else {
3805: $forceedit = 1;
3806: }
3807: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3808: }
3809: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3810: my $template = '/res/lib/templates/simpleproblem.problem';
3811: if (&is_on_map($template)) {
3812: $incourse = 1;
3813: $forceview = 1;
3814: $cfile = $template;
3815: }
3816: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3817: $incourse = 1;
3818: if ($env{'form.forceedit'}) {
3819: $forceview = 1;
3820: } else {
3821: $forceedit = 1;
3822: }
3823: $cfile = $resurl;
1.1172.2.146. .1(raebu 3824:22): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3825:22): $incourse = 1;
3826:22): if ($env{'form.forceedit'}) {
3827:22): $forceview = 1;
3828:22): } else {
3829:22): $forceedit = 1;
3830:22): }
3831:22): $cfile = $resurl;
1.1172.2.13 raeburn 3832: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3833: $incourse = 1;
3834: $forceview = 1;
3835: if ($symb) {
3836: my ($map,$id,$res)=&decode_symb($symb);
3837: $env{'request.symb'} = $symb;
3838: $cfile = &clutter($res);
3839: } else {
3840: $cfile = $env{'form.suppurl'};
1.1172.2.146. .1(raebu 3841:22): my $escfile = &unescape($cfile);
3842:22): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3843:22): $cfile = '/adm/wrapper'.$escfile;
3844:22): } else {
3845:22): $escfile =~ s{^http://}{};
3846:22): $cfile = &escape("/adm/wrapper/ext/$escfile");
3847:22): }
1.1172.2.13 raeburn 3848: }
1.1172.2.31 raeburn 3849: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3850: if ($env{'form.forceedit'}) {
3851: $forceview = 1;
3852: } else {
3853: $forceedit = 1;
3854: }
3855: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3856: }
3857: }
3858: if ($uploaded || $incourse) {
3859: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3860: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3861: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3862: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3863: # Check that the user has permission to edit this resource
3864: my $setpriv = 1;
3865: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3866: if (defined($cfudom)) {
3867: $home=&homeserver($cfuname,$cfudom);
3868: $cfile=$file;
3869: }
3870: }
3871: if (($cfile ne '') && (!$incourse || $uploaded) &&
3872: (($home ne '') && ($home ne 'no_host'))) {
3873: my @ids=¤t_machine_ids();
3874: unless (grep(/^\Q$home\E$/,@ids)) {
3875: $switchserver=1;
3876: }
3877: }
3878: }
3879: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3880: }
3881:
3882: sub is_course_upload {
3883: my ($file,$cnum,$cdom) = @_;
3884: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3885: $uploadpath =~ s{^\/}{};
3886: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3887: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3888: return 1;
3889: }
3890: return;
3891: }
3892:
3893: sub in_course {
3894: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3895: if ($hideprivileged) {
3896: my $skipuser;
1.1172.2.23 raeburn 3897: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3898: my @possdoms = ($cdom);
3899: if ($coursehash{'checkforpriv'}) {
3900: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3901: }
3902: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3903: $skipuser = 1;
3904: if ($coursehash{'nothideprivileged'}) {
3905: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3906: my $user;
3907: if ($item =~ /:/) {
3908: $user = $item;
3909: } else {
3910: $user = join(':',split(/[\@]/,$item));
3911: }
3912: if ($user eq $uname.':'.$udom) {
3913: undef($skipuser);
3914: last;
3915: }
3916: }
3917: }
3918: if ($skipuser) {
3919: return 0;
3920: }
3921: }
3922: }
3923: $type ||= 'any';
3924: if (!defined($cdom) || !defined($cnum)) {
3925: my $cid = $env{'request.course.id'};
3926: $cdom = $env{'course.'.$cid.'.domain'};
3927: $cnum = $env{'course.'.$cid.'.num'};
3928: }
3929: my $typesref;
3930: if (($type eq 'any') || ($type eq 'all')) {
3931: $typesref = ['active','previous','future'];
3932: } elsif ($type eq 'previous' || $type eq 'future') {
3933: $typesref = [$type];
3934: }
3935: my %roles = &get_my_roles($uname,$udom,'userroles',
3936: $typesref,undef,[$cdom]);
3937: my ($tmp) = keys(%roles);
3938: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3939: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3940: if (@course_roles > 0) {
3941: return 1;
3942: }
3943: return 0;
3944: }
3945:
1.478 albertel 3946: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3947: # input: action, courseID, current domain, intended
1.637 raeburn 3948: # path to file, source of file, instruction to parse file for objects,
3949: # ref to hash for embedded objects,
3950: # ref to hash for codebase of java objects.
1.1095 raeburn 3951: # reference to scalar to accommodate mime type determined
3952: # from File::MMagic if $parser = parse.
1.637 raeburn 3953: #
1.485 raeburn 3954: # output: url to file (if action was uploaddoc),
3955: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3956: #
1.478 albertel 3957: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3958: # course.
1.477 raeburn 3959: #
1.478 albertel 3960: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3961: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3962: # course's home server.
1.477 raeburn 3963: #
1.478 albertel 3964: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3965: # be copied from $source (current location) to
3966: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3967: # and will then be copied to
3968: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3969: # course's home server.
1.485 raeburn 3970: #
1.481 raeburn 3971: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3972: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3973: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3974: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3975: # in course's home server.
1.637 raeburn 3976: #
1.477 raeburn 3977:
3978: sub process_coursefile {
1.1095 raeburn 3979: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3980: $mimetype)=@_;
1.477 raeburn 3981: my $fetchresult;
1.638 albertel 3982: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3983: if ($action eq 'propagate') {
1.638 albertel 3984: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3985: $home);
1.481 raeburn 3986: } else {
1.477 raeburn 3987: my $fpath = '';
3988: my $fname = $file;
1.478 albertel 3989: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3990: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3991: my $filepath = &build_filepath($fpath);
1.481 raeburn 3992: if ($action eq 'copy') {
3993: if ($source eq '') {
3994: $fetchresult = 'no source file';
3995: return $fetchresult;
3996: } else {
3997: my $destination = $filepath.'/'.$fname;
3998: rename($source,$destination);
3999: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4000: $home);
1.481 raeburn 4001: }
4002: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 4003: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4004: print $fh $env{'form.'.$source};
1.481 raeburn 4005: close($fh);
1.637 raeburn 4006: if ($parser eq 'parse') {
1.1024 raeburn 4007: my $mm = new File::MMagic;
1.1095 raeburn 4008: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4009: if ($type eq 'text/html') {
1.1024 raeburn 4010: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4011: unless ($parse_result eq 'ok') {
4012: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4013: }
1.637 raeburn 4014: }
1.1095 raeburn 4015: if (ref($mimetype)) {
4016: $$mimetype = $type;
4017: }
1.637 raeburn 4018: }
1.477 raeburn 4019: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4020: $home);
1.481 raeburn 4021: if ($fetchresult eq 'ok') {
4022: return '/uploaded/'.$fpath.'/'.$fname;
4023: } else {
4024: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4025: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4026: return '/adm/notfound.html';
4027: }
1.477 raeburn 4028: }
4029: }
1.485 raeburn 4030: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4031: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4032: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4033: }
4034: return $fetchresult;
4035: }
4036:
1.637 raeburn 4037: sub build_filepath {
4038: my ($fpath) = @_;
4039: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4040: unless ($fpath eq '') {
4041: my @parts=split('/',$fpath);
4042: foreach my $part (@parts) {
4043: $filepath.= '/'.$part;
4044: if ((-e $filepath)!=1) {
4045: mkdir($filepath,0777);
4046: }
4047: }
4048: }
4049: return $filepath;
4050: }
4051:
4052: sub store_edited_file {
1.638 albertel 4053: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4054: my $file = $primary_url;
4055: $file =~ s#^/uploaded/$docudom/$docuname/##;
4056: my $fpath = '';
4057: my $fname = $file;
4058: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4059: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4060: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 4061: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4062: print $fh $content;
4063: close($fh);
1.638 albertel 4064: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4065: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4066: $home);
1.637 raeburn 4067: if ($$fetchresult eq 'ok') {
4068: return '/uploaded/'.$fpath.'/'.$fname;
4069: } else {
1.638 albertel 4070: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4071: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4072: return '/adm/notfound.html';
4073: }
4074: }
4075:
1.531 albertel 4076: sub clean_filename {
1.831 albertel 4077: my ($fname,$args)=@_;
1.315 www 4078: # Replace Windows backslashes by forward slashes
1.257 www 4079: $fname=~s/\\/\//g;
1.831 albertel 4080: if (!$args->{'keep_path'}) {
4081: # Get rid of everything but the actual filename
4082: $fname=~s/^.*\/([^\/]+)$/$1/;
4083: }
1.315 www 4084: # Replace spaces by underscores
4085: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 4086: # Transliterate non-ascii text to ascii
4087: my $lang = &Apache::lonlocal::current_language();
4088: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4089: # Replace all other weird characters by nothing
1.831 albertel 4090: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4091: # Replace all .\d. sequences with _\d. so they no longer look like version
4092: # numbers
4093: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 4094: # Replace three or more adjacent underscores with one for consistency
4095: # with loncfile::filename_check() so complete url can be extracted by
4096: # lonnet::decode_symb()
4097: $fname=~s/_{3,}/_/g;
1.531 albertel 4098: return $fname;
4099: }
1.1172.2.110 raeburn 4100:
1.1051 raeburn 4101: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4102: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4103: # image with the same aspect ratio as the original, but with dimensions which do
4104: # not exceed $resizewidth and $resizeheight.
4105:
1.984 neumanie 4106: sub resizeImage {
1.1051 raeburn 4107: my ($img_path,$resizewidth,$resizeheight) = @_;
4108: my $ima = Image::Magick->new;
4109: my $resized;
4110: if (-e $img_path) {
4111: $ima->Read($img_path);
4112: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4113: my $width = $ima->Get('width');
4114: my $height = $ima->Get('height');
4115: if ($width > $resizewidth) {
4116: my $factor = $width/$resizewidth;
4117: my $newheight = $height/$factor;
4118: $ima->Scale(width=>$resizewidth,height=>$newheight);
4119: $resized = 1;
4120: }
4121: }
4122: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4123: my $width = $ima->Get('width');
4124: my $height = $ima->Get('height');
4125: if ($height > $resizeheight) {
4126: my $factor = $height/$resizeheight;
4127: my $newwidth = $width/$factor;
4128: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4129: $resized = 1;
4130: }
4131: }
4132: if ($resized) {
4133: $ima->Write($img_path);
4134: }
4135: }
4136: return;
1.977 amueller 4137: }
4138:
1.608 albertel 4139: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4140: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4141: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4142: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.146. .13(raeb 4143:-23): # canceloverwrite, scantron, toollogo or ''.
1.1090 raeburn 4144: # if 'coursedoc': upload to the current course
4145: # if 'existingfile': write file to tmp/overwrites directory
4146: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4147: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4148: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 4149: # $parser - instruction to parse file for objects ($parser = parse) or
4150: # if context is 'scantron', $parser is hashref of csv column mapping
4151: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4152: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4153: # $allfiles - reference to hash for embedded objects
4154: # $codebase - reference to hash for codebase of java objects
1.1172.2.146. .13(raeb 4155:-23): # $destuname - username for permanent storage of uploaded file
4156:-23): # $destudom - domain for permanaent storage of uploaded file
1.860 raeburn 4157: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4158: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4159: # $resizewidth - width (pixels) to which to resize uploaded image
4160: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4161: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4162: # from File::MMagic.
1.858 raeburn 4163: #
1.686 albertel 4164: # output: url of file in userspace, or error: <message>
4165: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4166:
1.531 albertel 4167: sub userfileupload {
1.1090 raeburn 4168: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4169: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4170: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4171: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4172: $fname=&clean_filename($fname);
1.1090 raeburn 4173: # See if there is anything left
1.257 www 4174: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 4175: # If filename now begins with a . prepend unix timestamp _ milliseconds
4176: if ($fname =~ /^\./) {
4177: my ($s,$usec) = &gettimeofday();
4178: while (length($usec) < 6) {
4179: $usec = '0'.$usec;
4180: }
4181: $fname = $s.'_'.substr($usec,0,3).$fname;
4182: }
1.1090 raeburn 4183: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4184: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4185: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4186: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4187: my $now = time;
1.1090 raeburn 4188: my $filepath;
1.1095 raeburn 4189: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4190: $filepath = 'tmp/helprequests/'.$now;
4191: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4192: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4193: '_'.$env{'user.domain'}.'/pending';
4194: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4195: my ($docuname,$docudom);
1.1172.2.96 raeburn 4196: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4197: $docudom = $destudom;
4198: } else {
4199: $docudom = $env{'user.domain'};
4200: }
1.1172.2.96 raeburn 4201: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4202: $docuname = $destuname;
4203: } else {
4204: $docuname = $env{'user.name'};
4205: }
4206: if (exists($env{'form.group'})) {
4207: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4208: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4209: }
4210: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4211: if ($context eq 'canceloverwrite') {
4212: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4213: if (-e $tempfile) {
4214: my @info = stat($tempfile);
4215: if ($info[9] eq $env{'form.timestamp'}) {
4216: unlink($tempfile);
4217: }
4218: }
4219: return;
1.523 raeburn 4220: }
4221: }
1.1090 raeburn 4222: # Create the directory if not present
1.741 raeburn 4223: my @parts=split(/\//,$filepath);
4224: my $fullpath = $perlvar{'lonDaemons'};
4225: for (my $i=0;$i<@parts;$i++) {
4226: $fullpath .= '/'.$parts[$i];
4227: if ((-e $fullpath)!=1) {
4228: mkdir($fullpath,0777);
4229: }
4230: }
1.1172.2.96 raeburn 4231: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4232: print $fh $env{'form.'.$formname};
4233: close($fh);
1.1090 raeburn 4234: if ($context eq 'existingfile') {
4235: my @info = stat($fullpath.'/'.$fname);
4236: return ($fullpath.'/'.$fname,$info[9]);
4237: } else {
4238: return $fullpath.'/'.$fname;
4239: }
1.523 raeburn 4240: }
1.995 raeburn 4241: if ($subdir eq 'scantron') {
4242: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4243: } else {
1.995 raeburn 4244: $fname="$subdir/$fname";
4245: }
1.1090 raeburn 4246: if ($context eq 'coursedoc') {
1.638 albertel 4247: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4248: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4249: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4250: return &finishuserfileupload($docuname,$docudom,
4251: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4252: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4253: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4254: } else {
1.1172.2.21 raeburn 4255: if ($env{'form.folder'}) {
4256: $fname=$env{'form.folder'}.'/'.$fname;
4257: }
1.638 albertel 4258: return &process_coursefile('uploaddoc',$docuname,$docudom,
4259: $fname,$formname,$parser,
1.1095 raeburn 4260: $allfiles,$codebase,$mimetype);
1.481 raeburn 4261: }
1.719 banghart 4262: } elsif (defined($destuname)) {
4263: my $docuname=$destuname;
4264: my $docudom=$destudom;
1.860 raeburn 4265: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4266: $parser,$allfiles,$codebase,
1.1051 raeburn 4267: $thumbwidth,$thumbheight,
1.1095 raeburn 4268: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4269: } else {
1.638 albertel 4270: my $docuname=$env{'user.name'};
4271: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 4272: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4273: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4274: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4275: }
1.860 raeburn 4276: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4277: $parser,$allfiles,$codebase,
1.1051 raeburn 4278: $thumbwidth,$thumbheight,
1.1095 raeburn 4279: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4280: }
1.271 www 4281: }
4282:
4283: sub finishuserfileupload {
1.860 raeburn 4284: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4285: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4286: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4287: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4288:
1.860 raeburn 4289: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4290: $file=$fname;
4291: if ($fname=~m|/|) {
4292: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4293: $path.=$fnamepath.'/';
4294: }
1.259 www 4295: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4296: my $count;
4297: for ($count=4;$count<=$#parts;$count++) {
4298: $filepath.="/$parts[$count]";
4299: if ((-e $filepath)!=1) {
4300: mkdir($filepath,0777);
4301: }
4302: }
1.984 neumanie 4303:
1.258 www 4304: # Save the file
4305: {
1.1172.2.96 raeburn 4306: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4307: &logthis('Failed to create '.$filepath.'/'.$file);
4308: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4309: return '/adm/notfound.html';
4310: }
1.1090 raeburn 4311: if ($context eq 'overwrite') {
1.1117 foxr 4312: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4313: my $target = $filepath.'/'.$file;
4314: if (-e $source) {
4315: my @info = stat($source);
4316: if ($info[9] eq $env{'form.timestamp'}) {
4317: unless (&File::Copy::move($source,$target)) {
4318: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4319: return "Moving from $source failed";
4320: }
4321: } else {
4322: return "Temporary file: $source had unexpected date/time for last modification";
4323: }
4324: } else {
4325: return "Temporary file: $source missing";
4326: }
4327: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4328: &logthis('Failed to write to '.$filepath.'/'.$file);
4329: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4330: return '/adm/notfound.html';
4331: }
1.570 albertel 4332: close(FH);
1.1051 raeburn 4333: if ($resizewidth && $resizeheight) {
4334: my $mm = new File::MMagic;
4335: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4336: if ($mime_type =~ m{^image/}) {
4337: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4338: }
1.977 amueller 4339: }
1.258 www 4340: }
1.1152 raeburn 4341: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4342: if (ref($mimetype)) {
4343: if ($$mimetype eq '') {
4344: my $mm = new File::MMagic;
4345: my $type = $mm->checktype_filename($filepath.'/'.$file);
4346: $$mimetype = $type;
4347: }
4348: }
4349: }
1.1172.2.109 raeburn 4350: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4351: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4352: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4353: $allfiles,$codebase);
4354: unless ($parse_result eq 'ok') {
4355: &logthis('Failed to parse '.$filepath.$file.
4356: ' for embedded media: '.$parse_result);
4357: }
1.637 raeburn 4358: }
1.1172.2.109 raeburn 4359: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4360: my $format = $env{'form.scantron_format'};
4361: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4362: }
1.860 raeburn 4363: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4364: my $input = $filepath.'/'.$file;
4365: my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146. .13(raeb 4366:-23): my $makethumb;
1.860 raeburn 4367: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146. .13(raeb 4368:-23): if ($context eq 'toollogo') {
4369:-23): my ($fullwidth,$fullheight) = &check_dimensions($input);
4370:-23): if ($fullwidth ne '' && $fullheight ne '') {
4371:-23): if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
4372:-23): $makethumb = 1;
4373:-23): }
4374:-23): }
4375:-23): } else {
4376:-23): $makethumb = 1;
4377:-23): }
4378:-23): if ($makethumb) {
4379:-23): my @args = ('convert','-sample',$thumbsize,$input,$output);
4380:-23): system({$args[0]} @args);
4381:-23): if (-e $filepath.'/'.'tn-'.$file) {
4382:-23): $fetchthumb = 1;
4383:-23): }
1.860 raeburn 4384: }
4385: }
1.858 raeburn 4386:
1.259 www 4387: # Notify homeserver to grep it
4388: #
1.984 neumanie 4389: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4390: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4391: if ($fetchresult eq 'ok') {
1.860 raeburn 4392: if ($fetchthumb) {
4393: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4394: if ($thumbresult ne 'ok') {
4395: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4396: $docuhome.': '.$thumbresult);
4397: }
4398: }
1.259 www 4399: #
1.258 www 4400: # Return the URL to it
1.494 albertel 4401: return '/uploaded/'.$path.$file;
1.263 www 4402: } else {
1.494 albertel 4403: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4404: ': '.$fetchresult);
1.263 www 4405: return '/adm/notfound.html';
1.858 raeburn 4406: }
1.493 albertel 4407: }
4408:
1.637 raeburn 4409: sub extract_embedded_items {
1.961 raeburn 4410: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4411: my @state = ();
1.1164 raeburn 4412: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4413: my %javafiles = (
4414: codebase => '',
4415: code => '',
4416: archive => ''
4417: );
4418: my %mediafiles = (
4419: src => '',
4420: movie => '',
4421: );
1.648 raeburn 4422: my $p;
4423: if ($content) {
4424: $p = HTML::LCParser->new($content);
4425: } else {
1.961 raeburn 4426: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4427: }
1.641 albertel 4428: while (my $t=$p->get_token()) {
1.640 albertel 4429: if ($t->[0] eq 'S') {
4430: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4431: push(@state, $tagname);
1.648 raeburn 4432: if (lc($tagname) eq 'allow') {
4433: &add_filetype($allfiles,$attr->{'src'},'src');
4434: }
1.640 albertel 4435: if (lc($tagname) eq 'img') {
4436: &add_filetype($allfiles,$attr->{'src'},'src');
4437: }
1.886 albertel 4438: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4439: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4440: &add_filetype($allfiles,$attr->{'href'},'href');
4441: }
1.886 albertel 4442: }
1.645 raeburn 4443: if (lc($tagname) eq 'script') {
1.1164 raeburn 4444: my $src;
1.645 raeburn 4445: if ($attr->{'archive'} =~ /\.jar$/i) {
4446: &add_filetype($allfiles,$attr->{'archive'},'archive');
4447: } else {
1.1164 raeburn 4448: if ($attr->{'src'} ne '') {
4449: $src = $attr->{'src'};
4450: &add_filetype($allfiles,$src,'src');
4451: }
4452: }
4453: my $text = $p->get_trimmed_text();
4454: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4455: my @swfargs = split(/,/,$1);
4456: foreach my $item (@swfargs) {
4457: $item =~ s/["']//g;
4458: $item =~ s/^\s+//;
4459: $item =~ s/\s+$//;
4460: }
4461: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4462: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4463: push(@{$related{$swfargs[0]}},$swfargs[2]);
4464: } else {
4465: $related{$swfargs[0]} = [$swfargs[2]];
4466: }
4467: }
1.645 raeburn 4468: }
4469: }
4470: if (lc($tagname) eq 'link') {
4471: if (lc($attr->{'rel'}) eq 'stylesheet') {
4472: &add_filetype($allfiles,$attr->{'href'},'href');
4473: }
4474: }
1.640 albertel 4475: if (lc($tagname) eq 'object' ||
4476: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4477: foreach my $item (keys(%javafiles)) {
4478: $javafiles{$item} = '';
4479: }
1.1164 raeburn 4480: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4481: $lastids{lc($tagname)} = $attr->{'id'};
4482: }
1.640 albertel 4483: }
4484: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4485: my $name = lc($attr->{'name'});
4486: foreach my $item (keys(%javafiles)) {
4487: if ($name eq $item) {
4488: $javafiles{$item} = $attr->{'value'};
4489: last;
4490: }
4491: }
1.1164 raeburn 4492: my $pathfrom;
1.640 albertel 4493: foreach my $item (keys(%mediafiles)) {
4494: if ($name eq $item) {
1.1164 raeburn 4495: $pathfrom = $attr->{'value'};
4496: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4497: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4498: last;
4499: }
4500: }
1.1164 raeburn 4501: if ($name eq 'flashvars') {
4502: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4503: }
4504: if ($pathfrom ne '') {
4505: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4506: $pathfrom);
4507: }
1.640 albertel 4508: }
4509: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4510: foreach my $item (keys(%javafiles)) {
4511: if ($attr->{$item}) {
4512: $javafiles{$item} = $attr->{$item};
4513: last;
4514: }
4515: }
4516: foreach my $item (keys(%mediafiles)) {
4517: if ($attr->{$item}) {
4518: &add_filetype($allfiles,$attr->{$item},$item);
4519: last;
4520: }
4521: }
1.1164 raeburn 4522: if (lc($tagname) eq 'embed') {
4523: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4524: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4525: $attr->{'src'});
4526: }
4527: }
1.640 albertel 4528: }
1.1172.2.35 raeburn 4529: if (lc($tagname) eq 'iframe') {
4530: my $src = $attr->{'src'} ;
4531: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4532: &add_filetype($allfiles,$src,'src');
4533: } elsif ($src =~ m{^/}) {
4534: if ($env{'request.course.id'}) {
4535: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4536: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4537: my $url = &hreflocation('',$fullpath);
4538: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4539: my $relpath = $1;
4540: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4541: &add_filetype($allfiles,$1,'src');
4542: }
4543: }
4544: }
4545: }
4546: }
1.1164 raeburn 4547: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4548: pop(@state);
1.1164 raeburn 4549: }
1.640 albertel 4550: } elsif ($t->[0] eq 'E') {
4551: my ($tagname) = ($t->[1]);
4552: if ($javafiles{'codebase'} ne '') {
4553: $javafiles{'codebase'} .= '/';
4554: }
4555: if (lc($tagname) eq 'applet' ||
4556: lc($tagname) eq 'object' ||
4557: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4558: ) {
4559: foreach my $item (keys(%javafiles)) {
4560: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4561: my $file=$javafiles{'codebase'}.$javafiles{$item};
4562: &add_filetype($allfiles,$file,$item);
4563: }
4564: }
4565: }
4566: pop @state;
4567: }
4568: }
1.1164 raeburn 4569: foreach my $id (sort(keys(%flashvars))) {
4570: if ($shockwave{$id} ne '') {
4571: my @pairs = split(/\&/,$flashvars{$id});
4572: foreach my $pair (@pairs) {
4573: my ($key,$value) = split(/\=/,$pair);
4574: if ($key eq 'thumb') {
4575: &add_filetype($allfiles,$value,$key);
4576: } elsif ($key eq 'content') {
4577: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4578: my ($ext) = ($value =~ /\.([^.]+)$/);
4579: if ($ext ne '') {
4580: &add_filetype($allfiles,$path.$value,$ext);
4581: }
4582: }
4583: }
4584: }
4585: }
1.637 raeburn 4586: return 'ok';
4587: }
4588:
1.639 albertel 4589: sub add_filetype {
4590: my ($allfiles,$file,$type)=@_;
4591: if (exists($allfiles->{$file})) {
4592: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4593: push(@{$allfiles->{$file}}, &escape($type));
4594: }
4595: } else {
4596: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4597: }
4598: }
4599:
1.1164 raeburn 4600: sub embedded_dependency {
4601: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4602: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4603: if (($identifier ne '') &&
4604: (ref($related->{$identifier}) eq 'ARRAY') &&
4605: ($pathfrom ne '')) {
4606: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4607: foreach my $dep (@{$related->{$identifier}}) {
4608: &add_filetype($allfiles,$path.$dep,'object');
4609: }
4610: }
4611: }
4612: return;
4613: }
4614:
1.1172.2.146. .13(raeb 4615:-23): sub check_dimensions {
4616:-23): my ($inputfile) = @_;
4617:-23): my ($fullwidth,$fullheight);
4618:-23): if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
4619:-23): my $mm = new File::MMagic;
4620:-23): my $mime_type = $mm->checktype_filename($inputfile);
4621:-23): if ($mime_type =~ m{^image/}) {
4622:-23): if (open(PIPE,"identify $inputfile 2>&1 |")) {
4623:-23): my $imageinfo = <PIPE>;
4624:-23): if (!close(PIPE)) {
4625:-23): &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
4626:-23): }
4627:-23): chomp($imageinfo);
4628:-23): my ($fullsize) =
4629:-23): ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
4630:-23): if ($fullsize) {
4631:-23): ($fullwidth,$fullheight) = split(/x/,$fullsize);
4632:-23): }
4633:-23): }
4634:-23): }
4635:-23): }
4636:-23): return ($fullwidth,$fullheight);
4637:-23): }
4638:-23):
1.1172.2.109 raeburn 4639: sub bubblesheet_converter {
4640: my ($cdom,$fullpath,$config,$format) = @_;
4641: if ((&domain($cdom) ne '') &&
4642: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4643: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4644: my (%csvcols,%csvoptions);
4645: if (ref($config->{'fields'}) eq 'HASH') {
4646: %csvcols = %{$config->{'fields'}};
4647: }
4648: if (ref($config->{'options'}) eq 'HASH') {
4649: %csvoptions = %{$config->{'options'}};
4650: }
4651: my %csvbynum = reverse(%csvcols);
4652: my %scantronconf = &get_scantron_config($format,$cdom);
4653: if (keys(%scantronconf)) {
4654: my %bynum = (
4655: $scantronconf{CODEstart} => 'CODEstart',
4656: $scantronconf{IDstart} => 'IDstart',
4657: $scantronconf{PaperID} => 'PaperID',
4658: $scantronconf{FirstName} => 'FirstName',
4659: $scantronconf{LastName} => 'LastName',
4660: $scantronconf{Qstart} => 'Qstart',
4661: );
4662: my @ordered;
4663: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4664: push(@ordered,$bynum{$item});
4665: }
4666: my %mapstart = (
4667: CODEstart => 'CODE',
4668: IDstart => 'ID',
4669: PaperID => 'PaperID',
4670: FirstName => 'FirstName',
4671: LastName => 'LastName',
4672: Qstart => 'FirstQuestion',
4673: );
4674: my %maplength = (
4675: CODEstart => 'CODElength',
4676: IDstart => 'IDlength',
4677: PaperID => 'PaperIDlength',
4678: FirstName => 'FirstNamelength',
4679: LastName => 'LastNamelength',
4680: );
4681: if (open(my $fh,'<',$fullpath)) {
4682: my $output;
4683: my %lettdig = &letter_to_digits();
4684: my %diglett = reverse(%lettdig);
4685: my $numletts = scalar(keys(%lettdig));
4686: my $num = 0;
4687: while (my $line=<$fh>) {
4688: $num ++;
4689: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4690: $line =~ s{[\r\n]+$}{};
4691: my %found;
1.1172.2.143 raeburn 4692: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4693: my ($qstart,$record);
4694: for (my $i=0; $i<@values; $i++) {
4695: if ((($qstart ne '') && ($i > $qstart)) ||
4696: ($csvbynum{$i} eq 'FirstQuestion')) {
4697: if ($values[$i] eq '') {
4698: $values[$i] = $scantronconf{'Qoff'};
4699: } elsif ($scantronconf{'Qon'} eq 'number') {
4700: if ($values[$i] =~ /^[A-Ja-j]$/) {
4701: $values[$i] = $lettdig{uc($values[$i])};
4702: }
4703: } elsif ($scantronconf{'Qon'} eq 'letter') {
4704: if ($values[$i] =~ /^[0-9]$/) {
4705: $values[$i] = $diglett{$values[$i]};
4706: }
4707: } else {
4708: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4709: my $digit;
4710: if ($values[$i] =~ /^[A-Ja-j]$/) {
4711: $digit = $lettdig{uc($values[$i])}-1;
4712: if ($values[$i] eq 'J') {
4713: $digit += $numletts;
4714: }
4715: } elsif ($values[$i] =~ /^[0-9]$/) {
4716: $digit = $values[$i]-1;
4717: if ($values[$i] eq '0') {
4718: $digit += $numletts;
4719: }
4720: }
4721: my $qval='';
4722: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4723: if ($j == $digit) {
4724: $qval .= $scantronconf{'Qon'};
4725: } else {
4726: $qval .= $scantronconf{'Qoff'};
4727: }
4728: }
4729: $values[$i] = $qval;
4730: }
4731: }
4732: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4733: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4734: }
4735: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4736: if ($numblank > 0) {
4737: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4738: }
4739: if ($csvbynum{$i} eq 'FirstQuestion') {
4740: $qstart = $i;
4741: $found{$csvbynum{$i}} = $values[$i];
4742: } else {
4743: $found{'FirstQuestion'} .= $values[$i];
4744: }
4745: } elsif (exists($csvbynum{$i})) {
4746: if ($csvoptions{'rem'}) {
4747: $values[$i] =~ s/^\s+//;
4748: }
4749: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4750: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4751: $values[$i] = '0'.$values[$i];
4752: }
4753: }
4754: $found{$csvbynum{$i}} = $values[$i];
4755: }
4756: }
4757: foreach my $item (@ordered) {
4758: my $currlength = 1+length($record);
4759: my $numspaces = $scantronconf{$item} - $currlength;
4760: if ($numspaces > 0) {
4761: $record .= (' ' x $numspaces);
4762: }
4763: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4764: unless ($item eq 'Qstart') {
4765: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4766: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4767: }
4768: }
4769: $record .= $found{$mapstart{$item}};
4770: }
4771: }
4772: $output .= "$record\n";
4773: }
4774: close($fh);
4775: if ($output) {
4776: if (open(my $fh,'>',$fullpath)) {
4777: print $fh $output;
4778: close($fh);
4779: }
4780: }
4781: }
4782: }
4783: return;
4784: }
4785: }
4786:
4787: sub letter_to_digits {
4788: my %lettdig = (
4789: A => 1,
4790: B => 2,
4791: C => 3,
4792: D => 4,
4793: E => 5,
4794: F => 6,
4795: G => 7,
4796: H => 8,
4797: I => 9,
4798: J => 0,
4799: );
4800: return %lettdig;
4801: }
4802:
4803: sub get_scantron_config {
4804: my ($which,$cdom) = @_;
4805: my @lines = &get_scantronformat_file($cdom);
4806: my %config;
4807: #FIXME probably should move to XML it has already gotten a bit much now
4808: foreach my $line (@lines) {
4809: my ($name,$descrip)=split(/:/,$line);
4810: if ($name ne $which ) { next; }
4811: chomp($line);
4812: my @config=split(/:/,$line);
4813: $config{'name'}=$config[0];
4814: $config{'description'}=$config[1];
4815: $config{'CODElocation'}=$config[2];
4816: $config{'CODEstart'}=$config[3];
4817: $config{'CODElength'}=$config[4];
4818: $config{'IDstart'}=$config[5];
4819: $config{'IDlength'}=$config[6];
4820: $config{'Qstart'}=$config[7];
4821: $config{'Qlength'}=$config[8];
4822: $config{'Qoff'}=$config[9];
4823: $config{'Qon'}=$config[10];
4824: $config{'PaperID'}=$config[11];
4825: $config{'PaperIDlength'}=$config[12];
4826: $config{'FirstName'}=$config[13];
4827: $config{'FirstNamelength'}=$config[14];
4828: $config{'LastName'}=$config[15];
4829: $config{'LastNamelength'}=$config[16];
4830: $config{'BubblesPerRow'}=$config[17];
4831: last;
4832: }
4833: return %config;
4834: }
4835:
4836: sub get_scantronformat_file {
4837: my ($cdom) = @_;
4838: if ($cdom eq '') {
4839: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4840: }
4841: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4842: my $gottab = 0;
4843: my @lines;
4844: if (ref($domconfig{'scantron'}) eq 'HASH') {
4845: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4846: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4847: if ($formatfile ne '-1') {
4848: @lines = split("\n",$formatfile,-1);
4849: $gottab = 1;
4850: }
4851: }
4852: }
4853: if (!$gottab) {
4854: my $confname = $cdom.'-domainconfig';
4855: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4856: my $formatfile = &getfile($default);
4857: if ($formatfile ne '-1') {
4858: @lines = split("\n",$formatfile,-1);
4859: $gottab = 1;
4860: }
4861: }
4862: if (!$gottab) {
4863: my @domains = ¤t_machine_domains();
4864: if (grep(/^\Q$cdom\E$/,@domains)) {
4865: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4866: @lines = <$fh>;
4867: close($fh);
4868: }
4869: } else {
4870: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4871: @lines = <$fh>;
4872: close($fh);
4873: }
4874: }
1.1172.2.146. .8(raebu 4875:23): chomp(@lines);
1.1172.2.109 raeburn 4876: }
4877: return @lines;
4878: }
4879:
1.493 albertel 4880: sub removeuploadedurl {
1.984 neumanie 4881: my ($url)=@_;
4882: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4883: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4884: }
4885:
4886: sub removeuserfile {
4887: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4888: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4889: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4890: if ($result eq 'ok') {
1.798 raeburn 4891: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4892: my $metafile = $fname.'.meta';
4893: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4894: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4896: my $sqlresult =
1.823 albertel 4897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4898: 'portfolio_metadata',$group,
4899: 'delete');
1.798 raeburn 4900: }
4901: }
4902: return $result;
1.257 www 4903: }
1.15 www 4904:
1.530 albertel 4905: sub mkdiruserfile {
4906: my ($docuname,$docudom,$dir)=@_;
4907: my $home=&homeserver($docuname,$docudom);
4908: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4909: }
4910:
1.531 albertel 4911: sub renameuserfile {
4912: my ($docuname,$docudom,$old,$new)=@_;
4913: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4914: my $result = &reply("renameuserfile:$docudom:$docuname:".
4915: &escape("$old").':'.&escape("$new"),$home);
4916: if ($result eq 'ok') {
4917: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4918: my $oldmeta = $old.'.meta';
4919: my $newmeta = $new.'.meta';
4920: my $metaresult =
4921: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4922: my $url = "/uploaded/$docudom/$docuname/$old";
4923: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4924: my $sqlresult =
1.823 albertel 4925: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4926: 'portfolio_metadata',$group,
4927: 'delete');
1.798 raeburn 4928: }
4929: }
4930: return $result;
1.531 albertel 4931: }
4932:
1.14 www 4933: # ------------------------------------------------------------------------- Log
4934:
4935: sub log {
4936: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4937: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4938: }
4939:
4940: # ------------------------------------------------------------------ Course Log
1.352 www 4941: #
4942: # This routine flushes several buffers of non-mission-critical nature
4943: #
1.157 www 4944:
4945: sub flushcourselogs {
1.352 www 4946: &logthis('Flushing log buffers');
4947: #
4948: # course logs
4949: # This is a log of all transactions in a course, which can be used
4950: # for data mining purposes
4951: #
4952: # It also collects the courseid database, which lists last transaction
4953: # times and course titles for all courseids
4954: #
4955: my %courseidbuffer=();
1.921 raeburn 4956: foreach my $crsid (keys(%courselogs)) {
1.352 www 4957: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4958: &escape($courselogs{$crsid}),
4959: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4960: delete $courselogs{$crsid};
4961: } else {
4962: &logthis('Failed to flush log buffer for '.$crsid);
4963: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4964: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4965: " exceeded maximum size, deleting.</font>");
4966: delete $courselogs{$crsid};
4967: }
1.352 www 4968: }
1.920 raeburn 4969: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4970: 'description' => $coursedescrbuf{$crsid},
4971: 'inst_code' => $courseinstcodebuf{$crsid},
4972: 'type' => $coursetypebuf{$crsid},
4973: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4974: };
1.191 harris41 4975: }
1.352 www 4976: #
4977: # Write course id database (reverse lookup) to homeserver of courses
4978: # Is used in pickcourse
4979: #
1.840 albertel 4980: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4981: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4982: $courseidbuffer{$crs_home},
4983: $crs_home,'timeonly');
1.352 www 4984: }
4985: #
4986: # File accesses
4987: # Writes to the dynamic metadata of resources to get hit counts, etc.
4988: #
1.449 matthew 4989: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4990: if ($entry =~ /___count$/) {
4991: my ($dom,$name);
1.807 albertel 4992: ($dom,$name,undef)=
1.811 albertel 4993: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4994: if (! defined($dom) || $dom eq '' ||
4995: ! defined($name) || $name eq '') {
1.620 albertel 4996: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4997: #
4998: # FIXME 11/29/2021
4999: # Typo in rev. 1.458 (2003/12/09)??
5000: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5001: #
1.1172.2.146. .13(raeb 5002:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142 raeburn 5003: # $dom and $name will always be null, so the &inc() call will default to storing this data
5004: # in a nohist_accesscount.db file for the user rather than the course.
5005: #
5006: # That said there is a lot of noise in the data being stored.
5007: # So counts for prtspool/ and adm/ etc. are recorded.
5008: #
5009: # A review of which items ending '___count' are written to %accesshash should likely be
5010: # made before deciding whether to set these to 'course.' instead of 'request.'
5011: #
5012: # Under the current scheme each user receives a nohist_accesscount.db file listing
5013: # accesses for things which are not published resources, regardless of course, and
5014: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5015: # anyone in the course for things which are not published resources.
5016: #
5017: # For an author, nohist_accesscount.db ends up having records for other items
5018: # mixed up with the legitimate access counts for the author's published resources.
5019: #
1.620 albertel 5020: $dom = $env{'request.'.$cid.'.domain'};
5021: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5022: }
1.450 matthew 5023: my $value = $accesshash{$entry};
5024: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5025: my %temphash=($url => $value);
1.449 matthew 5026: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5027: if ($result eq 'ok') {
5028: delete $accesshash{$entry};
5029: }
5030: } else {
1.811 albertel 5031: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5032: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5033: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5034: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5035: delete $accesshash{$entry};
5036: }
1.185 www 5037: }
1.191 harris41 5038: }
1.352 www 5039: #
5040: # Roles
5041: # Reverse lookup of user roles for course faculty/staff and co-authorship
5042: #
1.800 albertel 5043: foreach my $entry (keys(%userrolehash)) {
1.351 www 5044: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5045: split(/\:/,$entry);
5046: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 5047: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5048: $rudom,$runame) eq 'ok') {
5049: delete $userrolehash{$entry};
5050: }
5051: }
1.662 raeburn 5052: #
1.1172.2.90 raeburn 5053: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5054: #
5055: my %domrolebuffer = ();
1.1000 raeburn 5056: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5057: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5058: if ($domrolebuffer{$rudom}) {
5059: $domrolebuffer{$rudom}.='&'.&escape($entry).
5060: '='.&escape($domainrolehash{$entry});
5061: } else {
5062: $domrolebuffer{$rudom}.=&escape($entry).
5063: '='.&escape($domainrolehash{$entry});
5064: }
5065: delete $domainrolehash{$entry};
5066: }
5067: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 5068: my %servers;
5069: if (defined(&domain($dom,'primary'))) {
5070: my $primary=&domain($dom,'primary');
5071: my $hostname=&hostname($primary);
5072: $servers{$primary} = $hostname;
5073: } else {
5074: %servers = &get_servers($dom,'library');
5075: }
1.841 albertel 5076: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 5077: if (&reply('domroleput:'.$dom.':'.
5078: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5079: last;
5080: } else {
1.841 albertel 5081: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5082: }
1.662 raeburn 5083: }
5084: }
1.186 www 5085: $dumpcount++;
1.157 www 5086: }
5087:
5088: sub courselog {
5089: my $what=shift;
1.158 www 5090: $what=time.':'.$what;
1.620 albertel 5091: unless ($env{'request.course.id'}) { return ''; }
5092: $coursedombuf{$env{'request.course.id'}}=
5093: $env{'course.'.$env{'request.course.id'}.'.domain'};
5094: $coursenumbuf{$env{'request.course.id'}}=
5095: $env{'course.'.$env{'request.course.id'}.'.num'};
5096: $coursehombuf{$env{'request.course.id'}}=
5097: $env{'course.'.$env{'request.course.id'}.'.home'};
5098: $coursedescrbuf{$env{'request.course.id'}}=
5099: $env{'course.'.$env{'request.course.id'}.'.description'};
5100: $courseinstcodebuf{$env{'request.course.id'}}=
5101: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5102: $courseownerbuf{$env{'request.course.id'}}=
5103: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5104: $coursetypebuf{$env{'request.course.id'}}=
5105: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5106: if (defined $courselogs{$env{'request.course.id'}}) {
5107: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5108: } else {
1.620 albertel 5109: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5110: }
1.620 albertel 5111: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5112: &flushcourselogs();
5113: }
1.158 www 5114: }
5115:
5116: sub courseacclog {
5117: my $fnsymb=shift;
1.620 albertel 5118: unless ($env{'request.course.id'}) { return ''; }
5119: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5120: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5121: $what.=':POST';
1.583 matthew 5122: # FIXME: Probably ought to escape things....
1.800 albertel 5123: foreach my $key (keys(%env)) {
5124: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5125: my $formitem = $1;
5126: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5127: $what.=':'.$formitem.'='.$env{$key};
5128: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 5129: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 5130: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 5131: } else {
5132: $what.=':'.$formitem.'='.$env{$key};
5133: }
1.975 raeburn 5134: }
1.158 www 5135: }
1.191 harris41 5136: }
1.583 matthew 5137: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5138: # FIXME: We should not be depending on a form parameter that someone
5139: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5140: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5141: $what.= ':POST';
5142: # FIXME: Probably ought to escape things....
5143: foreach my $element ('courseexp','crsfulltext','crsrelated',
5144: 'crsdiscuss') {
1.620 albertel 5145: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5146: }
5147: }
1.158 www 5148: }
5149: &courselog($what);
1.149 www 5150: }
5151:
1.185 www 5152: sub countacc {
5153: my $url=&declutter(shift);
1.458 matthew 5154: return if (! defined($url) || $url eq '');
1.620 albertel 5155: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5156: #
5157: # Mark that this url was used in this course
5158: #
1.620 albertel 5159: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5160: #
5161: # Increase the access count for this resource in this child process
5162: #
1.281 www 5163: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5164: $accesshash{$key}++;
1.185 www 5165: }
1.349 www 5166:
1.361 www 5167: sub linklog {
5168: my ($from,$to)=@_;
5169: $from=&declutter($from);
5170: $to=&declutter($to);
5171: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5172: $accesshash{$to.'___'.$from.'___goto'}=1;
5173: }
1.1160 www 5174:
5175: sub statslog {
5176: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5177: if ($users<2) { return; }
5178: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5179: 'course' => $env{'request.course.id'},
5180: 'sections' => '"all"',
5181: 'num_students' => $users,
5182: 'part' => $part,
5183: 'symb' => $symb,
5184: 'mean_tries' => $av_attempts,
5185: 'deg_of_diff' => $degdiff});
5186: foreach my $key (keys(%dynstore)) {
5187: $accesshash{$key}=$dynstore{$key};
5188: }
5189: }
1.361 www 5190:
1.349 www 5191: sub userrolelog {
5192: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5193: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5194: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5195: $userrolehash
5196: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5197: =$tend.':'.$tstart;
1.662 raeburn 5198: }
1.1169 droeschl 5199: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5200: $userrolehash
5201: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5202: =$tend.':'.$tstart;
5203: }
1.1172.2.90 raeburn 5204: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5205: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5206: $domainrolehash
5207: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5208: = $tend.':'.$tstart;
5209: }
1.351 www 5210: }
5211:
1.957 raeburn 5212: sub courserolelog {
5213: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 5214: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5215: my $cdom = $1;
5216: my $cnum = $2;
5217: my $sec = $3;
5218: my $namespace = 'rolelog';
5219: my %storehash = (
5220: role => $trole,
5221: start => $tstart,
5222: end => $tend,
5223: selfenroll => $selfenroll,
5224: context => $context,
5225: );
5226: if ($trole eq 'gr') {
5227: $namespace = 'groupslog';
5228: $storehash{'group'} = $sec;
5229: } else {
5230: $storehash{'section'} = $sec;
1.1172.2.146. .16(raeb 5231:-23): my ($curruserdomstr,$newuserdomstr);
5232:-23): if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
5233:-23): $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
5234:-23): } else {
5235:-23): my %courseinfo = &coursedescription($cdom.'/'.$cnum);
5236:-23): $curruserdomstr = $courseinfo{'internal.userdomains'};
5237:-23): }
5238:-23): if ($curruserdomstr ne '') {
5239:-23): my @udoms = split(/,/,$curruserdomstr);
5240:-23): unless (grep(/^\Q$domain\E/,@udoms)) {
5241:-23): push(@udoms,$domain);
5242:-23): $newuserdomstr = join(',',sort(@udoms));
5243:-23): }
5244:-23): } else {
5245:-23): $newuserdomstr = $domain;
5246:-23): }
5247:-23): if ($newuserdomstr ne '') {
5248:-23): my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
5249:-23): $cdom,$cnum);
5250:-23): if ($putresult eq 'ok') {
5251:-23): unless (($selfenroll) || ($context eq 'selfenroll')) {
5252:-23): if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
5253:-23): ($context eq 'automated') || ($context eq 'domain')) {
5254:-23): $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
5255:-23): } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
5256:-23): &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
5257:-23): }
5258:-23): }
5259:-23): }
5260:-23): }
1.1172.2.9 raeburn 5261: }
5262: &write_log('course',$namespace,\%storehash,$delflag,$username,
5263: $domain,$cnum,$cdom);
5264: if (($trole ne 'st') || ($sec ne '')) {
5265: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5266: }
5267: }
5268: return;
5269: }
5270:
1.1172.2.9 raeburn 5271: sub domainrolelog {
5272: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5273: if ($area =~ m{^/($match_domain)/$}) {
5274: my $cdom = $1;
5275: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5276: my $namespace = 'rolelog';
5277: my %storehash = (
5278: role => $trole,
5279: start => $tstart,
5280: end => $tend,
5281: context => $context,
5282: );
5283: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5284: $domain,$domconfiguser,$cdom);
5285: }
5286: return;
5287:
5288: }
5289:
5290: sub coauthorrolelog {
5291: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5292: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5293: my $audom = $1;
5294: my $auname = $2;
5295: my $namespace = 'rolelog';
5296: my %storehash = (
5297: role => $trole,
5298: start => $tstart,
5299: end => $tend,
5300: context => $context,
5301: );
5302: &write_log('author',$namespace,\%storehash,$delflag,$username,
5303: $domain,$auname,$audom);
5304: }
5305: return;
5306: }
5307:
1.351 www 5308: sub get_course_adv_roles {
1.948 raeburn 5309: my ($cid,$codes) = @_;
1.620 albertel 5310: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5311: my %coursehash=&coursedescription($cid);
1.988 raeburn 5312: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5313: my %nothide=();
1.800 albertel 5314: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5315: if ($user !~ /:/) {
5316: $nothide{join(':',split(/[\@]/,$user))}=1;
5317: } else {
5318: $nothide{$user}=1;
5319: }
1.470 www 5320: }
1.1172.2.23 raeburn 5321: my @possdoms = ($coursehash{'domain'});
5322: if ($coursehash{'checkforpriv'}) {
5323: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5324: }
1.351 www 5325: my %returnhash=();
5326: my %dumphash=
5327: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5328: my $now=time;
1.997 raeburn 5329: my %privileged;
1.1000 raeburn 5330: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5331: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5332: if (($tstart) && ($tstart<0)) { next; }
5333: if (($tend) && ($tend<$now)) { next; }
5334: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5335: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5336: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 5337: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5338: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5339: if ($role eq 'cr') { next; }
1.948 raeburn 5340: if ($codes) {
5341: if ($section) { $role .= ':'.$section; }
5342: if ($returnhash{$role}) {
5343: $returnhash{$role}.=','.$username.':'.$domain;
5344: } else {
5345: $returnhash{$role}=$username.':'.$domain;
5346: }
1.351 www 5347: } else {
1.988 raeburn 5348: my $key=&plaintext($role,$crstype);
1.973 bisitz 5349: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5350: if ($returnhash{$key}) {
5351: $returnhash{$key}.=','.$username.':'.$domain;
5352: } else {
5353: $returnhash{$key}=$username.':'.$domain;
5354: }
1.351 www 5355: }
1.948 raeburn 5356: }
1.400 www 5357: return %returnhash;
5358: }
5359:
5360: sub get_my_roles {
1.937 raeburn 5361: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5362: unless (defined($uname)) { $uname=$env{'user.name'}; }
5363: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5364: my (%dumphash,%nothide);
1.1086 raeburn 5365: if ($context eq 'userroles') {
1.1166 raeburn 5366: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5367: } else {
1.1172.2.23 raeburn 5368: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5369: if ($hidepriv) {
5370: my %coursehash=&coursedescription($udom.'_'.$uname);
5371: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5372: if ($user !~ /:/) {
5373: $nothide{join(':',split(/[\@]/,$user))} = 1;
5374: } else {
5375: $nothide{$user} = 1;
5376: }
5377: }
5378: }
1.858 raeburn 5379: }
1.400 www 5380: my %returnhash=();
5381: my $now=time;
1.999 raeburn 5382: my %privileged;
1.800 albertel 5383: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5384: my ($role,$tend,$tstart);
5385: if ($context eq 'userroles') {
1.1149 raeburn 5386: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5387: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5388: } else {
5389: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5390: }
1.400 www 5391: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5392: my $status = 'active';
1.939 raeburn 5393: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5394: $status = 'previous';
5395: }
5396: if (($tstart) && ($now<$tstart)) {
5397: $status = 'future';
5398: }
5399: if (ref($types) eq 'ARRAY') {
5400: if (!grep(/^\Q$status\E$/,@{$types})) {
5401: next;
5402: }
5403: } else {
5404: if ($status ne 'active') {
5405: next;
5406: }
5407: }
1.867 raeburn 5408: my ($rolecode,$username,$domain,$section,$area);
5409: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5410: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5411: (undef,$domain,$username,$section) = split(/\//,$area);
5412: } else {
5413: ($role,$username,$domain,$section) = split(/\:/,$entry);
5414: }
1.832 raeburn 5415: if (ref($roledoms) eq 'ARRAY') {
5416: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5417: next;
5418: }
5419: }
5420: if (ref($roles) eq 'ARRAY') {
5421: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5422: if ($role =~ /^cr\//) {
5423: if (!grep(/^cr$/,@{$roles})) {
5424: next;
5425: }
1.1104 raeburn 5426: } elsif ($role =~ /^gr\//) {
5427: if (!grep(/^gr$/,@{$roles})) {
5428: next;
5429: }
1.922 raeburn 5430: } else {
5431: next;
5432: }
1.832 raeburn 5433: }
1.867 raeburn 5434: }
1.937 raeburn 5435: if ($hidepriv) {
1.1172.2.23 raeburn 5436: my @privroles = ('dc','su');
1.999 raeburn 5437: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5438: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5439: } else {
1.1172.2.23 raeburn 5440: my $possdoms = [$domain];
5441: if (ref($roledoms) eq 'ARRAY') {
5442: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5443: }
1.1172.2.23 raeburn 5444: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5445: if (!$nothide{$username.':'.$domain}) {
5446: next;
5447: }
5448: }
1.937 raeburn 5449: }
5450: }
1.933 raeburn 5451: if ($withsec) {
5452: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5453: $tstart.':'.$tend;
5454: } else {
5455: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5456: }
1.832 raeburn 5457: }
1.373 www 5458: return %returnhash;
1.399 www 5459: }
5460:
1.1172.2.89 raeburn 5461: sub get_all_adhocroles {
5462: my ($dom) = @_;
5463: my @roles_by_num = ();
5464: my %domdefaults = &get_domain_defaults($dom);
5465: my (%description,%access_in_dom,%access_info);
5466: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5467: my $count = 0;
5468: my %domcurrent = %{$domdefaults{'adhocroles'}};
5469: my %ordered;
5470: foreach my $role (sort(keys(%domcurrent))) {
5471: my ($order,$desc,$access_in_dom);
5472: if (ref($domcurrent{$role}) eq 'HASH') {
5473: $order = $domcurrent{$role}{'order'};
5474: $desc = $domcurrent{$role}{'desc'};
5475: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5476: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5477: }
5478: if ($order eq '') {
5479: $order = $count;
5480: }
5481: $ordered{$order} = $role;
5482: if ($desc ne '') {
5483: $description{$role} = $desc;
5484: } else {
5485: $description{$role}= $role;
5486: }
5487: $count++;
5488: }
5489: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5490: push(@roles_by_num,$ordered{$item});
5491: }
5492: }
5493: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5494: }
5495:
5496: sub get_my_adhocroles {
5497: my ($cid,$checkreg) = @_;
5498: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5499: if ($env{'request.course.id'} eq $cid) {
5500: $cdom = $env{'course.'.$cid.'.domain'};
5501: $cnum = $env{'course.'.$cid.'.num'};
5502: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5503: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5504: $cdom = $1;
5505: $cnum = $2;
5506: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5507: $cdom,$cnum);
5508: }
5509: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5510: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5511: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5512: if ($rosterhash{$user} ne '') {
5513: my $type = (split(/:/,$rosterhash{$user}))[5];
5514: return ([],{}) if ($type eq 'auto');
5515: }
5516: }
5517: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5518: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5519: my $then=$env{'user.login.time'};
5520: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5521: if (!$update) {
5522: $update = $then;
5523: }
5524: my @liveroles;
5525: foreach my $role ('dh','da') {
5526: if ($env{"user.role.$role./$cdom/"}) {
5527: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5528: my $limit = $update;
5529: if ($env{'request.role'} eq "$role./$cdom/") {
5530: $limit = $then;
5531: }
5532: my $activerole = 1;
5533: if ($tstart && $tstart>$limit) { $activerole = 0; }
5534: if ($tend && $tend <$limit) { $activerole = 0; }
5535: if ($activerole) {
5536: push(@liveroles,$role);
5537: }
5538: }
5539: }
5540: if (@liveroles) {
1.1172.2.89 raeburn 5541: if (&homeserver($cnum,$cdom) ne 'no_host') {
5542: my ($accessref,$accessinfo,%access_in_dom);
5543: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5544: if (ref($roles_by_num) eq 'ARRAY') {
5545: if (@{$roles_by_num}) {
5546: my %settings;
5547: if ($env{'request.course.id'} eq $cid) {
5548: foreach my $envkey (keys(%env)) {
5549: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5550: $settings{$1} = $env{$envkey};
5551: }
5552: }
5553: } else {
5554: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5555: }
5556: my %setincrs;
5557: if ($settings{'internal.adhocaccess'}) {
5558: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5559: }
5560: my @statuses;
5561: if ($env{'environment.inststatus'}) {
5562: @statuses = split(/,/,$env{'environment.inststatus'});
5563: }
5564: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5565: if (ref($accessref) eq 'HASH') {
5566: %access_in_dom = %{$accessref};
5567: }
5568: foreach my $role (@{$roles_by_num}) {
5569: my ($curraccess,@okstatus,@personnel);
5570: if ($setincrs{$role}) {
5571: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5572: if ($curraccess eq 'status') {
5573: @okstatus = split(/\&/,$rest);
5574: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5575: @personnel = split(/\&/,$rest);
5576: }
5577: } else {
5578: $curraccess = $access_in_dom{$role};
5579: if (ref($accessinfo) eq 'HASH') {
5580: if ($curraccess eq 'status') {
5581: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5582: @okstatus = @{$accessinfo->{$role}};
5583: }
5584: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5585: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5586: @personnel = @{$accessinfo->{$role}};
5587: }
5588: }
5589: }
5590: }
5591: if ($curraccess eq 'none') {
5592: next;
5593: } elsif ($curraccess eq 'all') {
5594: push(@possroles,$role);
1.1172.2.90 raeburn 5595: } elsif ($curraccess eq 'dh') {
5596: if (grep(/^dh$/,@liveroles)) {
5597: push(@possroles,$role);
5598: } else {
5599: next;
5600: }
5601: } elsif ($curraccess eq 'da') {
5602: if (grep(/^da$/,@liveroles)) {
5603: push(@possroles,$role);
5604: } else {
5605: next;
5606: }
1.1172.2.89 raeburn 5607: } elsif ($curraccess eq 'status') {
5608: if (@okstatus) {
5609: if (!@statuses) {
5610: if (grep(/^default$/,@okstatus)) {
5611: push(@possroles,$role);
5612: }
5613: } else {
5614: foreach my $status (@okstatus) {
5615: if (grep(/^\Q$status\E$/,@statuses)) {
5616: push(@possroles,$role);
5617: last;
5618: }
5619: }
5620: }
5621: }
5622: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5623: if (grep(/^\Q$user\E$/,@personnel)) {
5624: if ($curraccess eq 'exc') {
5625: push(@possroles,$role);
5626: }
5627: } elsif ($curraccess eq 'inc') {
5628: push(@possroles,$role);
5629: }
5630: }
5631: }
5632: }
5633: }
5634: }
5635: }
5636: }
5637: }
5638: unless (ref($description) eq 'HASH') {
5639: if (ref($roles_by_num) eq 'ARRAY') {
5640: my %desc;
5641: map { $desc{$_} = $_; } (@{$roles_by_num});
5642: $description = \%desc;
5643: } else {
5644: $description = {};
5645: }
5646: }
5647: return (\@possroles,$description);
5648: }
5649:
1.399 www 5650: # ----------------------------------------------------- Frontpage Announcements
5651: #
5652: #
5653:
5654: sub postannounce {
5655: my ($server,$text)=@_;
1.844 albertel 5656: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5657: unless ($text=~/\w/) { $text=''; }
5658: return &reply('setannounce:'.&escape($text),$server);
5659: }
5660:
5661: sub getannounce {
1.448 albertel 5662:
1.1172.2.96 raeburn 5663: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5664: my $announcement='';
1.800 albertel 5665: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5666: close($fh);
1.399 www 5667: if ($announcement=~/\w/) {
5668: return
5669: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5670: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5671: } else {
5672: return '';
5673: }
5674: } else {
5675: return '';
5676: }
1.351 www 5677: }
1.353 www 5678:
5679: # ---------------------------------------------------------- Course ID routines
5680: # Deal with domain's nohist_courseid.db files
5681: #
5682:
5683: sub courseidput {
1.921 raeburn 5684: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5685: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5686: my $outcome;
5687: if ($caller eq 'timeonly') {
5688: my $cids = '';
5689: foreach my $item (keys(%$storehash)) {
5690: $cids.=&escape($item).'&';
5691: }
5692: $cids=~s/\&$//;
5693: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5694: $coursehome);
5695: } else {
5696: my $items = '';
5697: foreach my $item (keys(%$storehash)) {
5698: $items.= &escape($item).'='.
5699: &freeze_escape($$storehash{$item}).'&';
5700: }
5701: $items=~s/\&$//;
5702: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5703: $coursehome);
1.918 raeburn 5704: }
5705: if ($outcome eq 'unknown_cmd') {
5706: my $what;
5707: foreach my $cid (keys(%$storehash)) {
5708: $what .= &escape($cid).'=';
1.921 raeburn 5709: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5710: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5711: }
5712: $what =~ s/\:$/&/;
5713: }
5714: $what =~ s/\&$//;
5715: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5716: } else {
5717: return $outcome;
5718: }
1.353 www 5719: }
5720:
5721: sub courseiddump {
1.921 raeburn 5722: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5723: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5724: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5725: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5726: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5727: my $as_hash = 1;
5728: my %returnhash;
5729: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5730: my %libserv = &all_library();
5731: foreach my $tryserver (keys(%libserv)) {
5732: if ( ( $hostidflag == 1
5733: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5734: || (!defined($hostidflag)) ) {
5735:
1.918 raeburn 5736: if (($domfilter eq '') ||
5737: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5738: my $rep;
5739: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5740: $rep = &LONCAPA::Lond::dump_course_id_handler(
5741: join(":", (&host_domain($tryserver), $sincefilter,
5742: &escape($descfilter), &escape($instcodefilter),
5743: &escape($ownerfilter), &escape($coursefilter),
5744: &escape($typefilter), &escape($regexp_ok),
5745: $as_hash, &escape($selfenrollonly),
5746: &escape($catfilter), $showhidden, $caller,
5747: &escape($cloner), &escape($cc_clone), $cloneonly,
5748: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5749: &escape($creationcontext),$domcloner,$hasuniquecode,
5750: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5751: } else {
5752: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5753: $sincefilter.':'.&escape($descfilter).':'.
5754: &escape($instcodefilter).':'.&escape($ownerfilter).
5755: ':'.&escape($coursefilter).':'.&escape($typefilter).
5756: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5757: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5758: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5759: &escape($cc_clone).':'.$cloneonly.':'.
5760: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5761: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5762: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5763: }
5764:
1.918 raeburn 5765: my @pairs=split(/\&/,$rep);
5766: foreach my $item (@pairs) {
5767: my ($key,$value)=split(/\=/,$item,2);
5768: $key = &unescape($key);
5769: next if ($key =~ /^error: 2 /);
5770: my $result = &thaw_unescape($value);
5771: if (ref($result) eq 'HASH') {
5772: $returnhash{$key}=$result;
5773: } else {
1.921 raeburn 5774: my @responses = split(/:/,$value);
5775: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5776: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5777: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5778: }
1.1008 raeburn 5779: }
1.353 www 5780: }
5781: }
5782: }
5783: }
5784: return %returnhash;
5785: }
5786:
1.1055 raeburn 5787: sub courselastaccess {
5788: my ($cdom,$cnum,$hostidref) = @_;
5789: my %returnhash;
5790: if ($cdom && $cnum) {
5791: my $chome = &homeserver($cnum,$cdom);
5792: if ($chome ne 'no_host') {
5793: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5794: &extract_lastaccess(\%returnhash,$rep);
5795: }
5796: } else {
5797: if (!$cdom) { $cdom=''; }
5798: my %libserv = &all_library();
5799: foreach my $tryserver (keys(%libserv)) {
5800: if (ref($hostidref) eq 'ARRAY') {
5801: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5802: }
5803: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5804: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5805: &extract_lastaccess(\%returnhash,$rep);
5806: }
5807: }
5808: }
5809: return %returnhash;
5810: }
5811:
5812: sub extract_lastaccess {
5813: my ($returnhash,$rep) = @_;
5814: if (ref($returnhash) eq 'HASH') {
5815: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5816: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5817: $rep eq '') {
5818: my @pairs=split(/\&/,$rep);
5819: foreach my $item (@pairs) {
5820: my ($key,$value)=split(/\=/,$item,2);
5821: $key = &unescape($key);
5822: next if ($key =~ /^error: 2 /);
5823: $returnhash->{$key} = &thaw_unescape($value);
5824: }
5825: }
5826: }
5827: return;
5828: }
5829:
1.658 raeburn 5830: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5831:
5832: sub dcmailput {
1.685 raeburn 5833: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5834: my $status = &Apache::lonnet::critical(
1.740 www 5835: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5836: &escape($message),$server);
1.662 raeburn 5837: return $status;
5838: }
5839:
1.658 raeburn 5840: sub dcmaildump {
5841: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5842: my %returnhash=();
1.846 albertel 5843:
5844: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5845: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5846: &escape($enddate).':';
5847: my @esc_senders=map { &escape($_)} @$senders;
5848: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5849: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5850: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5851: if (($key) && ($value)) {
5852: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5853: }
5854: }
5855: }
5856: return %returnhash;
5857: }
1.662 raeburn 5858: # ---------------------------------------------------------- Domain roles
5859:
5860: sub get_domain_roles {
5861: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5862: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5863: $startdate = '.';
5864: }
1.1018 raeburn 5865: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5866: $enddate = '.';
5867: }
1.922 raeburn 5868: my $rolelist;
5869: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5870: $rolelist = join('&',@{$roles});
1.922 raeburn 5871: }
1.662 raeburn 5872: my %personnel = ();
1.841 albertel 5873:
5874: my %servers = &get_servers($dom,'library');
5875: foreach my $tryserver (keys(%servers)) {
5876: %{$personnel{$tryserver}}=();
5877: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5878: &escape($startdate).':'.
5879: &escape($enddate).':'.
5880: &escape($rolelist), $tryserver))) {
5881: my ($key,$value) = split(/\=/,$line,2);
5882: if (($key) && ($value)) {
5883: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5884: }
5885: }
1.662 raeburn 5886: }
5887: return %personnel;
5888: }
1.658 raeburn 5889:
1.1172.2.89 raeburn 5890: sub get_active_domroles {
5891: my ($dom,$roles) = @_;
5892: return () unless (ref($roles) eq 'ARRAY');
5893: my $now = time;
5894: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5895: my %domroles;
5896: foreach my $server (keys(%dompersonnel)) {
5897: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5898: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5899: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5900: }
5901: }
5902: return %domroles;
5903: }
5904:
1.1057 www 5905: # ----------------------------------------------------------- Interval timing
1.149 www 5906:
1.1153 www 5907: {
5908: # Caches needed for speedup of navmaps
5909: # We don't want to cache this for very long at all (5 seconds at most)
5910: #
5911: # The user for whom we cache
5912: my $cachedkey='';
5913: # The cached times for this user
5914: my %cachedtimes=();
5915: # When this was last done
1.1172.2.66 raeburn 5916: my $cachedtime='';
1.1153 www 5917:
5918: sub load_all_first_access {
1.1172.2.146. .1(raebu 5919:22): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5920: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146. .1(raebu 5921:22): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5922:22): (!$ignorecache)) {
1.1154 raeburn 5923: return;
5924: }
5925: $cachedtime=time;
5926: $cachedkey=$uname.':'.$udom;
5927: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5928: }
5929:
1.504 albertel 5930: sub get_first_access {
1.1172.2.146. .1(raebu 5931:22): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5932: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5933: if ($argsymb) { $symb=$argsymb; }
5934: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5935: if ($argmap) { $map = $argmap; }
1.926 albertel 5936: if ($type eq 'course') {
5937: $res='course';
5938: } elsif ($type eq 'map') {
1.588 albertel 5939: $res=&symbread($map);
5940: } else {
5941: $res=$symb;
5942: }
1.1172.2.146. .1(raebu 5943:22): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5944: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5945: }
5946:
5947: sub set_first_access {
1.1162 raeburn 5948: my ($type,$interval)=@_;
1.790 albertel 5949: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5950: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5951: if ($type eq 'course') {
5952: $res='course';
5953: } elsif ($type eq 'map') {
1.588 albertel 5954: $res=&symbread($map);
5955: } else {
5956: $res=$symb;
5957: }
1.1153 www 5958: $cachedkey='';
1.1162 raeburn 5959: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5960: if ($firstaccess) {
5961: &logthis("First access time already set ($firstaccess) when attempting ".
5962: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5963: "in $courseid");
5964: return 'already_set';
5965: } else {
1.1162 raeburn 5966: my $start = time;
5967: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5968: $udom,$uname);
5969: if ($putres eq 'ok') {
5970: &put('timerinterval',{"$courseid\0$res"=>$interval},
5971: $udom,$uname);
5972: &appenv(
5973: {
5974: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5975: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5976: }
5977: );
1.1172.2.97 raeburn 5978: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5979: $cachedtimes{"$courseid\0$res"} = $start;
5980: }
1.1172.2.102 raeburn 5981: } elsif ($putres ne 'refused') {
5982: &logthis("Result: $putres when attempting to set first access time ".
5983: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5984: }
5985: return $putres;
1.505 albertel 5986: }
5987: return 'already_set';
1.504 albertel 5988: }
1.1153 www 5989: }
1.1172.2.32 raeburn 5990:
5991: sub checkout {
5992: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5993: my $now=time;
5994: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5995: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5996: my $infostr=&escape(
5997: 'CHECKOUTTOKEN&'.
5998: $tuname.'&'.
5999: $tudom.'&'.
6000: $tcrsid.'&'.
6001: $symb.'&'.
1.1172.2.134 raeburn 6002: $now.'&'.$ip);
1.1172.2.32 raeburn 6003: my $token=&reply('tmpput:'.$infostr,$lonhost);
6004: if ($token=~/^error\:/) {
6005: &logthis("<font color=\"blue\">WARNING: ".
6006: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
6007: "</font>");
6008: return '';
6009: }
6010:
6011: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
6012: $token=~tr/a-z/A-Z/;
6013:
6014: my %infohash=('resource.0.outtoken' => $token,
6015: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 6016: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 6017:
6018: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
6019: return '';
6020: } else {
6021: &logthis("<font color=\"blue\">WARNING: ".
6022: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
6023: "</font>");
6024: }
6025:
6026: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
6027: &escape('Checkout '.$infostr.' - '.
6028: $token)) ne 'ok') {
6029: return '';
6030: } else {
6031: &logthis("<font color=\"blue\">WARNING: ".
6032: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
6033: "</font>");
6034: }
6035: return $token;
6036: }
6037:
6038: # ------------------------------------------------------------ Check in an item
6039:
6040: sub checkin {
6041: my $token=shift;
6042: my $now=time;
6043: my ($ta,$tb,$lonhost)=split(/\*/,$token);
6044: $lonhost=~tr/A-Z/a-z/;
6045: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
6046: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 6047: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 6048: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
6049: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
6050:
6051: unless (($tuname) && ($tudom)) {
6052: &logthis('Check in '.$token.' ('.$dtoken.') failed');
6053: return '';
6054: }
6055:
6056: unless (&allowed('mgr',$tcrsid)) {
6057: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
6058: $env{'user.name'}.' - '.$env{'user.domain'});
6059: return '';
6060: }
6061:
6062: my %infohash=('resource.0.intoken' => $token,
6063: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 6064: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 6065:
6066: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
6067: return '';
6068: }
6069:
6070: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
6071: &escape('Checkin - '.$token)) ne 'ok') {
6072: return '';
6073: }
6074:
6075: return ($symb,$tuname,$tudom,$tcrsid);
6076: }
6077:
1.110 www 6078: # --------------------------------------------- Set Expire Date for Spreadsheet
6079:
6080: sub expirespread {
6081: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6082: my $cid=$env{'request.course.id'};
1.110 www 6083: if ($cid) {
6084: my $now=time;
6085: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6086: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6087: $env{'course.'.$cid.'.num'}.
1.110 www 6088: ':nohist_expirationdates:'.
6089: &escape($key).'='.$now,
1.620 albertel 6090: $env{'course.'.$cid.'.home'})
1.110 www 6091: }
6092: return 'ok';
1.14 www 6093: }
6094:
1.109 www 6095: # ----------------------------------------------------- Devalidate Spreadsheets
6096:
6097: sub devalidate {
1.325 www 6098: my ($symb,$uname,$udom)=@_;
1.620 albertel 6099: my $cid=$env{'request.course.id'};
1.109 www 6100: if ($cid) {
1.391 matthew 6101: # delete the stored spreadsheets for
6102: # - the student level sheet of this user in course's homespace
6103: # - the assessment level sheet for this resource
6104: # for this user in user's homespace
1.553 albertel 6105: # - current conditional state info
1.325 www 6106: my $key=$uname.':'.$udom.':';
1.109 www 6107: my $status=
1.299 matthew 6108: &del('nohist_calculatedsheets',
1.391 matthew 6109: [$key.'studentcalc:'],
1.620 albertel 6110: $env{'course.'.$cid.'.domain'},
6111: $env{'course.'.$cid.'.num'})
1.133 albertel 6112: .' '.
6113: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6114: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6115: unless ($status eq 'ok ok') {
6116: &logthis('Could not devalidate spreadsheet '.
1.325 www 6117: $uname.' at '.$udom.' for '.
1.109 www 6118: $symb.': '.$status);
1.133 albertel 6119: }
1.553 albertel 6120: &delenv('user.state.'.$cid);
1.109 www 6121: }
6122: }
6123:
1.265 albertel 6124: sub get_scalar {
6125: my ($string,$end) = @_;
6126: my $value;
6127: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6128: $value = $1;
6129: } elsif ($$string =~ s/^([^&]*?)&//) {
6130: $value = $1;
6131: }
6132: return &unescape($value);
6133: }
6134:
6135: sub array2str {
6136: my (@array) = @_;
6137: my $result=&arrayref2str(\@array);
6138: $result=~s/^__ARRAY_REF__//;
6139: $result=~s/__END_ARRAY_REF__$//;
6140: return $result;
6141: }
6142:
1.204 albertel 6143: sub arrayref2str {
6144: my ($arrayref) = @_;
1.265 albertel 6145: my $result='__ARRAY_REF__';
1.204 albertel 6146: foreach my $elem (@$arrayref) {
1.265 albertel 6147: if(ref($elem) eq 'ARRAY') {
6148: $result.=&arrayref2str($elem).'&';
6149: } elsif(ref($elem) eq 'HASH') {
6150: $result.=&hashref2str($elem).'&';
6151: } elsif(ref($elem)) {
6152: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6153: } else {
6154: $result.=&escape($elem).'&';
6155: }
6156: }
6157: $result=~s/\&$//;
1.265 albertel 6158: $result .= '__END_ARRAY_REF__';
1.204 albertel 6159: return $result;
6160: }
6161:
1.168 albertel 6162: sub hash2str {
1.204 albertel 6163: my (%hash) = @_;
6164: my $result=&hashref2str(\%hash);
1.265 albertel 6165: $result=~s/^__HASH_REF__//;
6166: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6167: return $result;
6168: }
6169:
6170: sub hashref2str {
6171: my ($hashref)=@_;
1.265 albertel 6172: my $result='__HASH_REF__';
1.800 albertel 6173: foreach my $key (sort(keys(%$hashref))) {
6174: if (ref($key) eq 'ARRAY') {
6175: $result.=&arrayref2str($key).'=';
6176: } elsif (ref($key) eq 'HASH') {
6177: $result.=&hashref2str($key).'=';
6178: } elsif (ref($key)) {
1.265 albertel 6179: $result.='=';
1.800 albertel 6180: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6181: } else {
1.1132 raeburn 6182: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6183: }
6184:
1.800 albertel 6185: if(ref($hashref->{$key}) eq 'ARRAY') {
6186: $result.=&arrayref2str($hashref->{$key}).'&';
6187: } elsif(ref($hashref->{$key}) eq 'HASH') {
6188: $result.=&hashref2str($hashref->{$key}).'&';
6189: } elsif(ref($hashref->{$key})) {
1.265 albertel 6190: $result.='&';
1.800 albertel 6191: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6192: } else {
1.800 albertel 6193: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6194: }
6195: }
1.168 albertel 6196: $result=~s/\&$//;
1.265 albertel 6197: $result .= '__END_HASH_REF__';
1.168 albertel 6198: return $result;
6199: }
6200:
6201: sub str2hash {
1.265 albertel 6202: my ($string)=@_;
6203: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6204: return %$hash;
6205: }
6206:
6207: sub str2hashref {
1.168 albertel 6208: my ($string) = @_;
1.265 albertel 6209:
6210: my %hash;
6211:
6212: if($string !~ /^__HASH_REF__/) {
6213: if (! ($string eq '' || !defined($string))) {
6214: $hash{'error'}='Not hash reference';
6215: }
6216: return (\%hash, $string);
6217: }
6218:
6219: $string =~ s/^__HASH_REF__//;
6220:
6221: while($string !~ /^__END_HASH_REF__/) {
6222: #key
6223: my $key='';
6224: if($string =~ /^__HASH_REF__/) {
6225: ($key, $string)=&str2hashref($string);
6226: if(defined($key->{'error'})) {
6227: $hash{'error'}='Bad data';
6228: return (\%hash, $string);
6229: }
6230: } elsif($string =~ /^__ARRAY_REF__/) {
6231: ($key, $string)=&str2arrayref($string);
6232: if($key->[0] eq 'Array reference error') {
6233: $hash{'error'}='Bad data';
6234: return (\%hash, $string);
6235: }
6236: } else {
6237: $string =~ s/^(.*?)=//;
1.267 albertel 6238: $key=&unescape($1);
1.265 albertel 6239: }
6240: $string =~ s/^=//;
6241:
6242: #value
6243: my $value='';
6244: if($string =~ /^__HASH_REF__/) {
6245: ($value, $string)=&str2hashref($string);
6246: if(defined($value->{'error'})) {
6247: $hash{'error'}='Bad data';
6248: return (\%hash, $string);
6249: }
6250: } elsif($string =~ /^__ARRAY_REF__/) {
6251: ($value, $string)=&str2arrayref($string);
6252: if($value->[0] eq 'Array reference error') {
6253: $hash{'error'}='Bad data';
6254: return (\%hash, $string);
6255: }
6256: } else {
6257: $value=&get_scalar(\$string,'__END_HASH_REF__');
6258: }
6259: $string =~ s/^&//;
6260:
6261: $hash{$key}=$value;
1.204 albertel 6262: }
1.265 albertel 6263:
6264: $string =~ s/^__END_HASH_REF__//;
6265:
6266: return (\%hash, $string);
1.204 albertel 6267: }
6268:
6269: sub str2array {
1.265 albertel 6270: my ($string)=@_;
6271: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6272: return @$array;
6273: }
6274:
6275: sub str2arrayref {
1.204 albertel 6276: my ($string) = @_;
1.265 albertel 6277: my @array;
6278:
6279: if($string !~ /^__ARRAY_REF__/) {
6280: if (! ($string eq '' || !defined($string))) {
6281: $array[0]='Array reference error';
6282: }
6283: return (\@array, $string);
6284: }
6285:
6286: $string =~ s/^__ARRAY_REF__//;
6287:
6288: while($string !~ /^__END_ARRAY_REF__/) {
6289: my $value='';
6290: if($string =~ /^__HASH_REF__/) {
6291: ($value, $string)=&str2hashref($string);
6292: if(defined($value->{'error'})) {
6293: $array[0] ='Array reference error';
6294: return (\@array, $string);
6295: }
6296: } elsif($string =~ /^__ARRAY_REF__/) {
6297: ($value, $string)=&str2arrayref($string);
6298: if($value->[0] eq 'Array reference error') {
6299: $array[0] ='Array reference error';
6300: return (\@array, $string);
6301: }
6302: } else {
6303: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6304: }
6305: $string =~ s/^&//;
6306:
6307: push(@array, $value);
1.191 harris41 6308: }
1.265 albertel 6309:
6310: $string =~ s/^__END_ARRAY_REF__//;
6311:
6312: return (\@array, $string);
1.168 albertel 6313: }
6314:
1.167 albertel 6315: # -------------------------------------------------------------------Temp Store
6316:
1.168 albertel 6317: sub tmpreset {
6318: my ($symb,$namespace,$domain,$stuname) = @_;
6319: if (!$symb) {
6320: $symb=&symbread();
1.620 albertel 6321: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6322: }
6323: $symb=escape($symb);
6324:
1.620 albertel 6325: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6326: $namespace=~s/\//\_/g;
6327: $namespace=~s/\W//g;
6328:
1.620 albertel 6329: if (!$domain) { $domain=$env{'user.domain'}; }
6330: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6331: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6332: $stuname=&get_requestor_ip();
1.591 albertel 6333: }
1.1117 foxr 6334: my $path=LONCAPA::tempdir();
1.168 albertel 6335: my %hash;
6336: if (tie(%hash,'GDBM_File',
6337: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6338: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6339: foreach my $key (keys(%hash)) {
1.180 albertel 6340: if ($key=~ /:$symb/) {
1.168 albertel 6341: delete($hash{$key});
6342: }
6343: }
6344: }
6345: }
6346:
1.167 albertel 6347: sub tmpstore {
1.168 albertel 6348: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6349:
6350: if (!$symb) {
6351: $symb=&symbread();
1.620 albertel 6352: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6353: }
6354: $symb=escape($symb);
6355:
6356: if (!$namespace) {
6357: # I don't think we would ever want to store this for a course.
6358: # it seems this will only be used if we don't have a course.
1.620 albertel 6359: #$namespace=$env{'request.course.id'};
1.168 albertel 6360: #if (!$namespace) {
1.620 albertel 6361: $namespace=$env{'request.state'};
1.168 albertel 6362: #}
6363: }
6364: $namespace=~s/\//\_/g;
6365: $namespace=~s/\W//g;
1.620 albertel 6366: if (!$domain) { $domain=$env{'user.domain'}; }
6367: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6368: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6369: $stuname=&get_requestor_ip();
1.591 albertel 6370: }
1.168 albertel 6371: my $now=time;
6372: my %hash;
1.1117 foxr 6373: my $path=LONCAPA::tempdir();
1.168 albertel 6374: if (tie(%hash,'GDBM_File',
6375: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6376: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6377: $hash{"version:$symb"}++;
6378: my $version=$hash{"version:$symb"};
6379: my $allkeys='';
6380: foreach my $key (keys(%$storehash)) {
6381: $allkeys.=$key.':';
1.591 albertel 6382: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6383: }
6384: $hash{"$version:$symb:timestamp"}=$now;
6385: $allkeys.='timestamp';
6386: $hash{"$version:keys:$symb"}=$allkeys;
6387: if (untie(%hash)) {
6388: return 'ok';
6389: } else {
6390: return "error:$!";
6391: }
6392: } else {
6393: return "error:$!";
6394: }
6395: }
1.167 albertel 6396:
1.168 albertel 6397: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6398:
1.168 albertel 6399: sub tmprestore {
6400: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6401:
1.168 albertel 6402: if (!$symb) {
6403: $symb=&symbread();
1.620 albertel 6404: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6405: }
6406: $symb=escape($symb);
6407:
1.620 albertel 6408: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6409:
1.620 albertel 6410: if (!$domain) { $domain=$env{'user.domain'}; }
6411: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6412: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6413: $stuname=&get_requestor_ip();
1.591 albertel 6414: }
1.168 albertel 6415: my %returnhash;
6416: $namespace=~s/\//\_/g;
6417: $namespace=~s/\W//g;
6418: my %hash;
1.1117 foxr 6419: my $path=LONCAPA::tempdir();
1.168 albertel 6420: if (tie(%hash,'GDBM_File',
6421: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6422: &GDBM_READER(),0640)) {
1.168 albertel 6423: my $version=$hash{"version:$symb"};
6424: $returnhash{'version'}=$version;
6425: my $scope;
6426: for ($scope=1;$scope<=$version;$scope++) {
6427: my $vkeys=$hash{"$scope:keys:$symb"};
6428: my @keys=split(/:/,$vkeys);
6429: my $key;
6430: $returnhash{"$scope:keys"}=$vkeys;
6431: foreach $key (@keys) {
1.591 albertel 6432: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6433: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6434: }
6435: }
1.168 albertel 6436: if (!(untie(%hash))) {
6437: return "error:$!";
6438: }
6439: } else {
6440: return "error:$!";
6441: }
6442: return %returnhash;
1.167 albertel 6443: }
6444:
1.9 www 6445: # ----------------------------------------------------------------------- Store
6446:
6447: sub store {
1.1172.2.64 raeburn 6448: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6449: my $home='';
6450:
1.168 albertel 6451: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6452:
1.213 www 6453: $symb=&symbclean($symb);
1.122 albertel 6454: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6455:
1.620 albertel 6456: if (!$domain) { $domain=$env{'user.domain'}; }
6457: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6458:
6459: &devalidate($symb,$stuname,$domain);
1.109 www 6460:
6461: $symb=escape($symb);
1.187 www 6462: if (!$namespace) {
1.620 albertel 6463: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6464: return '';
6465: }
6466: }
1.620 albertel 6467: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6468:
1.1172.2.138 raeburn 6469: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6470: $$storehash{'host'}=$perlvar{'lonHostID'};
6471:
1.12 www 6472: my $namevalue='';
1.800 albertel 6473: foreach my $key (keys(%$storehash)) {
6474: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6475: }
1.12 www 6476: $namevalue=~s/\&$//;
1.187 www 6477: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6478: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6479: }
6480:
1.47 www 6481: # -------------------------------------------------------------- Critical Store
6482:
6483: sub cstore {
1.1172.2.64 raeburn 6484: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6485: my $home='';
6486:
1.168 albertel 6487: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6488:
1.213 www 6489: $symb=&symbclean($symb);
1.122 albertel 6490: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6491:
1.620 albertel 6492: if (!$domain) { $domain=$env{'user.domain'}; }
6493: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6494:
6495: &devalidate($symb,$stuname,$domain);
1.109 www 6496:
6497: $symb=escape($symb);
1.187 www 6498: if (!$namespace) {
1.620 albertel 6499: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6500: return '';
6501: }
6502: }
1.620 albertel 6503: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6504:
1.1172.2.138 raeburn 6505: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6506: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6507:
1.47 www 6508: my $namevalue='';
1.800 albertel 6509: foreach my $key (keys(%$storehash)) {
6510: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6511: }
1.47 www 6512: $namevalue=~s/\&$//;
1.187 www 6513: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6514: return critical
1.1172.2.64 raeburn 6515: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6516: }
6517:
1.9 www 6518: # --------------------------------------------------------------------- Restore
6519:
6520: sub restore {
1.124 www 6521: my ($symb,$namespace,$domain,$stuname) = @_;
6522: my $home='';
6523:
1.168 albertel 6524: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6525:
1.122 albertel 6526: if (!$symb) {
1.1172.2.26 raeburn 6527: return if ($namespace eq 'courserequests');
6528: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6529: } else {
1.1172.2.26 raeburn 6530: unless ($namespace eq 'courserequests') {
6531: $symb=&escape(&symbclean($symb));
6532: }
1.122 albertel 6533: }
1.188 www 6534: if (!$namespace) {
1.620 albertel 6535: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6536: return '';
6537: }
6538: }
1.620 albertel 6539: if (!$domain) { $domain=$env{'user.domain'}; }
6540: if (!$stuname) { $stuname=$env{'user.name'}; }
6541: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6542: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6543:
1.12 www 6544: my %returnhash=();
1.800 albertel 6545: foreach my $line (split(/\&/,$answer)) {
6546: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6547: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6548: }
1.75 www 6549: my $version;
6550: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6551: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6552: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6553: }
1.75 www 6554: }
1.13 www 6555: return %returnhash;
1.34 www 6556: }
6557:
6558: # ---------------------------------------------------------- Course Description
1.1118 foxr 6559: #
6560: #
1.34 www 6561:
6562: sub coursedescription {
1.731 albertel 6563: my ($courseid,$args)=@_;
1.34 www 6564: $courseid=~s/^\///;
1.49 www 6565: $courseid=~s/\_/\//g;
1.34 www 6566: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6567: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6568: my $normalid=$cdomain.'_'.$cnum;
6569: # need to always cache even if we get errors otherwise we keep
6570: # trying and trying and trying to get the course description.
6571: my %envhash=();
6572: my %returnhash=();
1.731 albertel 6573:
6574: my $expiretime=600;
6575: if ($env{'request.course.id'} eq $normalid) {
6576: $expiretime=120;
6577: }
6578:
6579: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6580: if (!$args->{'freshen_cache'}
6581: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6582: foreach my $key (keys(%env)) {
6583: next if ($key !~ /^\Q$prefix\E(.*)/);
6584: my ($setting) = $1;
6585: $returnhash{$setting} = $env{$key};
6586: }
6587: return %returnhash;
6588: }
6589:
1.1118 foxr 6590: # get the data again
6591:
1.731 albertel 6592: if (!$args->{'one_time'}) {
6593: $envhash{'course.'.$normalid.'.last_cache'}=time;
6594: }
1.811 albertel 6595:
1.34 www 6596: if ($chome ne 'no_host') {
1.302 albertel 6597: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6598: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6599: my $username = $env{'user.name'}; # Defult username
6600: if(defined $args->{'user'}) {
6601: $username = $args->{'user'};
6602: }
1.129 albertel 6603: $returnhash{'home'}= $chome;
6604: $returnhash{'domain'} = $cdomain;
6605: $returnhash{'num'} = $cnum;
1.741 raeburn 6606: if (!defined($returnhash{'type'})) {
6607: $returnhash{'type'} = 'Course';
6608: }
1.130 albertel 6609: while (my ($name,$value) = each %returnhash) {
1.53 www 6610: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6611: }
1.270 www 6612: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6613: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6614: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6615: $envhash{'course.'.$normalid.'.home'}=$chome;
6616: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6617: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6618: }
6619: }
1.731 albertel 6620: if (!$args->{'one_time'}) {
1.949 raeburn 6621: &appenv(\%envhash);
1.731 albertel 6622: }
1.302 albertel 6623: return %returnhash;
1.461 www 6624: }
6625:
1.1080 raeburn 6626: sub update_released_required {
6627: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6628: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6629: $cid = $env{'request.course.id'};
6630: $cdom = $env{'course.'.$cid.'.domain'};
6631: $cnum = $env{'course.'.$cid.'.num'};
6632: $chome = $env{'course.'.$cid.'.home'};
6633: }
6634: if ($needsrelease) {
6635: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6636: my $needsupdate;
6637: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6638: $needsupdate = 1;
6639: } else {
6640: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6641: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6642: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6643: $needsupdate = 1;
6644: }
6645: }
6646: if ($needsupdate) {
6647: my %needshash = (
6648: 'internal.releaserequired' => $needsrelease,
6649: );
6650: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6651: if ($putresult eq 'ok') {
6652: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6653: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6654: if (ref($crsinfo{$cid}) eq 'HASH') {
6655: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6656: &courseidput($cdom,\%crsinfo,$chome,'notime');
6657: }
6658: }
6659: }
6660: }
6661: return;
6662: }
6663:
1.461 www 6664: # -------------------------------------------------See if a user is privileged
6665:
6666: sub privileged {
1.1172.2.23 raeburn 6667: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6668: my $now = time;
1.1172.2.23 raeburn 6669: my $roles;
6670: if (ref($possroles) eq 'ARRAY') {
6671: $roles = $possroles;
6672: } else {
6673: $roles = ['dc','su'];
6674: }
6675: if (ref($possdomains) eq 'ARRAY') {
6676: my %privileged = &privileged_by_domain($possdomains,$roles);
6677: foreach my $dom (@{$possdomains}) {
6678: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6679: (ref($privileged{$dom}) eq 'HASH')) {
6680: foreach my $role (@{$roles}) {
6681: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6682: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6683: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6684: return 1 unless (($end && $end < $now) ||
6685: ($start && $start > $now));
6686: }
6687: }
6688: }
6689: }
6690: }
6691: } else {
6692: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6693: my $now = time;
1.1170 droeschl 6694:
1.1172.2.58 raeburn 6695: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6696: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6697: if (grep(/^\Q$trole\E$/,@{$roles})) {
6698: return 1 unless ($tend && $tend < $now)
6699: or ($tstart && $tstart > $now);
1.1170 droeschl 6700: }
1.1172.2.23 raeburn 6701: }
6702: }
1.461 www 6703: return 0;
1.9 www 6704: }
1.1 albertel 6705:
1.1172.2.23 raeburn 6706: sub privileged_by_domain {
6707: my ($domains,$roles) = @_;
6708: my %privileged = ();
6709: my $cachetime = 60*60*24;
6710: my $now = time;
6711: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6712: return %privileged;
6713: }
6714: foreach my $dom (@{$domains}) {
6715: next if (ref($privileged{$dom}) eq 'HASH');
6716: my $needroles;
6717: foreach my $role (@{$roles}) {
6718: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6719: if (defined($cached)) {
6720: if (ref($result) eq 'HASH') {
6721: $privileged{$dom}{$role} = $result;
6722: }
6723: } else {
6724: $needroles = 1;
6725: }
6726: }
6727: if ($needroles) {
6728: my %dompersonnel = &get_domain_roles($dom,$roles);
6729: $privileged{$dom} = {};
6730: foreach my $server (keys(%dompersonnel)) {
6731: if (ref($dompersonnel{$server}) eq 'HASH') {
6732: foreach my $item (keys(%{$dompersonnel{$server}})) {
6733: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6734: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6735: next if ($end && $end < $now);
6736: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6737: $dompersonnel{$server}{$item};
6738: }
6739: }
6740: }
6741: if (ref($privileged{$dom}) eq 'HASH') {
6742: foreach my $role (@{$roles}) {
6743: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6744: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6745: } else {
6746: my %hash = ();
6747: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6748: }
6749: }
6750: }
6751: }
6752: }
6753: return %privileged;
6754: }
6755:
1.103 harris41 6756: # -------------------------------------------------------- Get user privileges
1.11 www 6757:
6758: sub rolesinit {
1.1169 droeschl 6759: my ($domain, $username) = @_;
6760: my %userroles = ('user.login.time' => time);
6761: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6762:
6763: # firstaccess and timerinterval are related to timed maps/resources.
6764: # also, blocking can be triggered by an activating timer
6765: # it's saved in the user's %env.
6766: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6767: my %timerinterval = &dump('timerinterval', $domain, $username);
6768: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1172.2.146. .18(raeb 6769:-24): %timerintchk, %timerintenv,%coauthorenv);
1.1169 droeschl 6770:
1.1162 raeburn 6771: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6772: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6773: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6774: }
1.1169 droeschl 6775:
1.1162 raeburn 6776: foreach my $key (keys(%timerinterval)) {
6777: my ($cid,$rest) = split(/\0/,$key);
6778: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6779: }
1.1169 droeschl 6780:
1.11 www 6781: my %allroles=();
1.1162 raeburn 6782: my %allgroups=();
1.1172.2.146. .18(raeb 6783:-24): my %gotcoauconfig=();
.20(raeb 6784:-24): my %domdefaults=();
1.11 www 6785:
1.1172.2.58 raeburn 6786: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6787: my $role = $rolesdump{$area};
6788: $area =~ s/\_\w\w$//;
6789:
6790: my ($trole, $tend, $tstart, $group_privs);
6791:
6792: if ($role =~ /^cr/) {
6793: # Custom role, defined by a user
6794: # e.g., user.role.cr/msu/smith/mynewrole
6795: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6796: $trole = $1;
6797: ($tend, $tstart) = split('_', $2);
6798: } else {
6799: $trole = $role;
6800: }
6801: } elsif ($role =~ m|^gr/|) {
6802: # Role of member in a group, defined within a course/community
6803: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6804: ($trole, $tend, $tstart) = split(/_/, $role);
6805: next if $tstart eq '-1';
6806: ($trole, $group_privs) = split(/\//, $trole);
6807: $group_privs = &unescape($group_privs);
6808: } else {
6809: # Just a normal role, defined in roles.tab
6810: ($trole, $tend, $tstart) = split(/_/,$role);
6811: }
6812:
6813: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6814: $username);
6815: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6816:
6817: # role expired or not available yet?
6818: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6819: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6820:
6821: next if $area eq '' or $trole eq '';
6822:
6823: my $spec = "$trole.$area";
6824: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6825:
6826: if ($trole =~ /^cr\//) {
6827: # Custom role, defined by a user
6828: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6829: } elsif ($trole eq 'gr') {
6830: # Role of a member in a group, defined within a course/community
6831: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6832: next;
6833: } else {
6834: # Normal role, defined in roles.tab
6835: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1172.2.146. .18(raeb 6836:-24): if (($trole eq 'ca') || ($trole eq 'aa')) {
6837:-24): (undef,my ($audom,$auname)) = split(/\//,$area);
6838:-24): unless ($gotcoauconfig{$area}) {
.22(raeb 6839:-24): my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
.18(raeb 6840:-24): my %info = &userenvironment($audom,$auname,@ca_settings);
6841:-24): $gotcoauconfig{$area} = 1;
6842:-24): foreach my $item (@ca_settings) {
6843:-24): if (exists($info{$item})) {
6844:-24): my $name = $item;
6845:-24): if ($item eq 'authoreditors') {
6846:-24): $name = 'editors';
.20(raeb 6847:-24): unless ($info{'authoreditors'}) {
6848:-24): my %domdefs;
6849:-24): if (ref($domdefaults{$audom}) eq 'HASH') {
6850:-24): %domdefs = %{$domdefaults{$audom}};
6851:-24): } else {
6852:-24): %domdefs = &get_domain_defaults($audom);
6853:-24): $domdefaults{$audom} = \%domdefs;
6854:-24): }
6855:-24): if ($domdefs{$name} ne '') {
6856:-24): $info{'authoreditors'} = $domdefs{$name};
6857:-24): } else {
6858:-24): $info{'authoreditors'} = 'edit,xml';
6859:-24): }
6860:-24): }
.18(raeb 6861:-24): }
6862:-24): $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
6863:-24): }
6864:-24): }
6865:-24): }
6866:-24): }
1.1169 droeschl 6867: }
6868:
6869: my $cid = $tdomain.'_'.$trest;
6870: unless ($firstaccchk{$cid}) {
6871: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6872: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6873: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6874: $coursetimerstarts{$cid}{$item};
6875: }
6876: }
6877: $firstaccchk{$cid} = 1;
6878: }
6879: unless ($timerintchk{$cid}) {
6880: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6881: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6882: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6883: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6884: }
1.12 www 6885: }
1.1169 droeschl 6886: $timerintchk{$cid} = 1;
1.191 harris41 6887: }
1.11 www 6888: }
1.1169 droeschl 6889:
1.1172.2.91 raeburn 6890: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6891: \%allroles, \%allgroups);
1.1169 droeschl 6892: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6893: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6894:
1.1172.2.146. .18(raeb 6895:-24): return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11 www 6896: }
6897:
1.567 raeburn 6898: sub set_arearole {
1.1172.2.19 raeburn 6899: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6900: unless ($nolog) {
1.567 raeburn 6901: # log the associated role with the area
1.1172.2.19 raeburn 6902: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6903: }
1.743 albertel 6904: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6905: }
6906:
6907: sub custom_roleprivs {
6908: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6909: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6910: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6911: if (&hostname($homsvr) ne '') {
1.567 raeburn 6912: my ($rdummy,$roledef)=
6913: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6914: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6915: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6916: if (defined($syspriv)) {
1.1043 raeburn 6917: if ($trest =~ /^$match_community$/) {
6918: $syspriv =~ s/bre\&S//;
6919: }
1.567 raeburn 6920: $$allroles{'cm./'}.=':'.$syspriv;
6921: $$allroles{$spec.'./'}.=':'.$syspriv;
6922: }
6923: if ($tdomain ne '') {
6924: if (defined($dompriv)) {
6925: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6926: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6927: }
6928: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6929: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6930: my $rolename = $1;
6931: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6932: }
1.567 raeburn 6933: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6934: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6935: }
6936: }
6937: }
6938: }
6939: }
6940:
1.1172.2.89 raeburn 6941: sub course_adhocrole_privs {
6942: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6943: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6944: if ($overrides{"internal.adhocpriv.$rolename"}) {
6945: my (%currprivs,%storeprivs);
6946: foreach my $item (split(/:/,$coursepriv)) {
6947: my ($priv,$restrict) = split(/\&/,$item);
6948: $currprivs{$priv} = $restrict;
6949: }
6950: my (%possadd,%possremove,%full);
6951: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6952: my ($priv,$restrict)=split(/\&/,$item);
6953: $full{$priv} = $restrict;
6954: }
6955: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146. .6(raebu 6956:22): next if ($item eq '');
6957:22): my ($rule,$rest) = split(/=/,$item);
6958:22): next unless (($rule eq 'off') || ($rule eq 'on'));
6959:22): foreach my $priv (split(/:/,$rest)) {
6960:22): if ($priv ne '') {
6961:22): if ($rule eq 'off') {
6962:22): $possremove{$priv} = 1;
6963:22): } else {
6964:22): $possadd{$priv} = 1;
6965:22): }
6966:22): }
6967:22): }
6968:22): }
6969:22): foreach my $priv (sort(keys(%full))) {
6970:22): if (exists($currprivs{$priv})) {
6971:22): unless (exists($possremove{$priv})) {
6972:22): $storeprivs{$priv} = $currprivs{$priv};
6973:22): }
6974:22): } elsif (exists($possadd{$priv})) {
6975:22): $storeprivs{$priv} = $full{$priv};
6976:22): }
6977:22): }
6978:22): $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6979:22): }
6980:22): return $coursepriv;
1.1172.2.89 raeburn 6981: }
6982:
1.678 raeburn 6983: sub group_roleprivs {
6984: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6985: my $access = 1;
6986: my $now = time;
6987: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6988: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6989: if ($access) {
1.811 albertel 6990: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6991: $$allgroups{$course}{$group} .=':'.$group_privs;
6992: }
6993: }
1.567 raeburn 6994:
6995: sub standard_roleprivs {
6996: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6997: if (defined($pr{$trole.':s'})) {
6998: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6999: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
7000: }
7001: if ($tdomain ne '') {
7002: if (defined($pr{$trole.':d'})) {
7003: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7004: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7005: }
7006: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
7007: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
7008: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
7009: }
7010: }
7011: }
7012:
7013: sub set_userprivs {
1.1064 raeburn 7014: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 7015: my $author=0;
7016: my $adv=0;
1.1172.2.91 raeburn 7017: my $rar=0;
1.678 raeburn 7018: my %grouproles = ();
7019: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 7020: my @groupkeys;
1.1000 raeburn 7021: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 7022: push(@groupkeys,$role);
7023: }
7024: if (ref($groups_roles) eq 'HASH') {
7025: foreach my $key (keys(%{$groups_roles})) {
7026: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7027: push(@groupkeys,$key);
7028: }
7029: }
7030: }
7031: if (@groupkeys > 0) {
7032: foreach my $role (@groupkeys) {
7033: my ($trole,$area,$sec,$extendedarea);
7034: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7035: $trole = $1;
7036: $area = $2;
7037: $sec = $3;
7038: $extendedarea = $area.$sec;
7039: if (exists($$allgroups{$area})) {
7040: foreach my $group (keys(%{$$allgroups{$area}})) {
7041: my $spec = $trole.'.'.$extendedarea;
7042: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7043: $$allgroups{$area}{$group};
1.1064 raeburn 7044: }
1.678 raeburn 7045: }
7046: }
7047: }
7048: }
7049: }
1.800 albertel 7050: foreach my $group (keys(%grouproles)) {
7051: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7052: }
1.800 albertel 7053: foreach my $role (keys(%{$allroles})) {
7054: my %thesepriv;
1.941 raeburn 7055: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7056: foreach my $item (split(/:/,$$allroles{$role})) {
7057: if ($item ne '') {
7058: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7059: if ($restrictions eq '') {
7060: $thesepriv{$privilege}='F';
7061: } elsif ($thesepriv{$privilege} ne 'F') {
7062: $thesepriv{$privilege}.=$restrictions;
7063: }
7064: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 7065: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7066: }
7067: }
7068: my $thesestr='';
1.1104 raeburn 7069: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7070: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7071: }
7072: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7073: }
1.1172.2.91 raeburn 7074: return ($author,$adv,$rar);
1.567 raeburn 7075: }
7076:
1.994 raeburn 7077: sub role_status {
1.1104 raeburn 7078: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7079: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 7080: my ($one,$two) = split(m{\./},$rolekey,2);
7081: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7082: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 7083: $$where = '/'.$two;
1.994 raeburn 7084: $$trolecode=$$role.'.'.$$where;
7085: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7086: $$tstatus='is';
1.1104 raeburn 7087: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7088: $$tstatus='future';
1.1034 raeburn 7089: if ($$tstart<$now) {
7090: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7091: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7092: my (%allroles,%allgroups,$group_privs,
7093: %groups_roles,@rolecodes);
1.1002 raeburn 7094: my %userroles = (
7095: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7096: );
1.1064 raeburn 7097: @rolecodes = ('cm');
1.1002 raeburn 7098: my $spec=$$role.'.'.$$where;
7099: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7100: if ($$role =~ /^cr\//) {
7101: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7102: push(@rolecodes,'cr');
1.1002 raeburn 7103: } elsif ($$role eq 'gr') {
1.1064 raeburn 7104: push(@rolecodes,$$role);
1.1002 raeburn 7105: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7106: $env{'user.name'});
1.1064 raeburn 7107: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7108: (undef,my $group_privs) = split(/\//,$trole);
7109: $group_privs = &unescape($group_privs);
7110: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7111: 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 7112: &get_groups_roles($tdomain,$trest,
7113: \%course_roles,\@rolecodes,
7114: \%groups_roles);
1.1002 raeburn 7115: } else {
1.1064 raeburn 7116: push(@rolecodes,$$role);
1.1002 raeburn 7117: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7118: }
1.1172.2.91 raeburn 7119: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7120: \%groups_roles);
1.1064 raeburn 7121: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 7122: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7123: }
7124: }
1.1034 raeburn 7125: $$tstatus = 'is';
1.1002 raeburn 7126: }
1.994 raeburn 7127: }
7128: if ($$tend) {
1.1104 raeburn 7129: if ($$tend<$update) {
1.994 raeburn 7130: $$tstatus='expired';
7131: } elsif ($$tend<$now) {
7132: $$tstatus='will_not';
7133: }
7134: }
7135: }
7136: }
7137: }
7138:
1.1104 raeburn 7139: sub get_groups_roles {
7140: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7141: return unless((ref($cdom_courseroles) eq 'HASH') &&
7142: (ref($rolecodes) eq 'ARRAY') &&
7143: (ref($groups_roles) eq 'HASH'));
7144: if (keys(%{$cdom_courseroles}) > 0) {
7145: my ($cnum) = ($rest =~ /^($match_courseid)/);
7146: if ($cdom ne '' && $cnum ne '') {
7147: foreach my $key (keys(%{$cdom_courseroles})) {
7148: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7149: my $crsrole = $1;
7150: my $crssec = $2;
7151: if ($crsrole =~ /^cr/) {
7152: unless (grep(/^cr$/,@{$rolecodes})) {
7153: push(@{$rolecodes},'cr');
7154: }
7155: } else {
7156: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7157: push(@{$rolecodes},$crsrole);
7158: }
7159: }
7160: my $rolekey = "$crsrole./$cdom/$cnum";
7161: if ($crssec ne '') {
7162: $rolekey .= "/$crssec";
7163: }
7164: $rolekey .= './';
7165: $groups_roles->{$rolekey} = $rolecodes;
7166: }
7167: }
7168: }
7169: }
7170: return;
7171: }
7172:
7173: sub delete_env_groupprivs {
7174: my ($where,$courseroles,$possroles) = @_;
7175: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7176: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7177: unless (ref($courseroles->{$udom}) eq 'HASH') {
7178: %{$courseroles->{$udom}} =
7179: &get_my_roles('','','userroles',['active'],
7180: $possroles,[$udom],1);
7181: }
7182: if (ref($courseroles->{$udom}) eq 'HASH') {
7183: foreach my $item (keys(%{$courseroles->{$udom}})) {
7184: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7185: my $area = '/'.$cdom.'/'.$cnum;
7186: my $privkey = "user.priv.$crsrole.$area";
7187: if ($crssec ne '') {
7188: $privkey .= '/'.$crssec;
7189: }
7190: $privkey .= ".$area/$group";
7191: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7192: }
7193: }
7194: return;
7195: }
7196:
1.994 raeburn 7197: sub check_adhoc_privs {
1.1172.2.86 raeburn 7198: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7199: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 7200: if ($sec) {
7201: $cckey .= '/'.$sec;
7202: }
1.1172.2.9 raeburn 7203: my $setprivs;
1.994 raeburn 7204: if ($env{$cckey}) {
7205: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7206: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7207: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 7208: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 7209: $setprivs = 1;
1.994 raeburn 7210: }
7211: } else {
1.1172.2.87 raeburn 7212: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 7213: $setprivs = 1;
1.994 raeburn 7214: }
1.1172.2.9 raeburn 7215: return $setprivs;
1.994 raeburn 7216: }
7217:
7218: sub set_adhoc_privileges {
1.1172.2.84 raeburn 7219: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 7220: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7221: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 7222: if ($sec ne '') {
7223: $area .= '/'.$sec;
7224: }
1.994 raeburn 7225: my $spec = $role.'.'.$area;
7226: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 7227: $env{'user.name'},1);
1.1172.2.84 raeburn 7228: my %rolehash = ();
1.1172.2.89 raeburn 7229: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7230: my $rolename = $1;
1.1172.2.84 raeburn 7231: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 7232: my %domdef = &get_domain_defaults($dcdom);
7233: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7234: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7235: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7236: }
7237: }
1.1172.2.84 raeburn 7238: } else {
7239: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7240: }
1.1172.2.91 raeburn 7241: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7242: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 7243: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146. .1(raebu 7244:22): unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7245:22): ($caller eq 'tiny')) {
1.1088 raeburn 7246: &appenv( {'request.role' => $spec,
7247: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 7248: 'request.course.sec' => $sec,
1.1088 raeburn 7249: }
7250: );
7251: my $tadv=0;
7252: if (&allowed('adv') eq 'F') { $tadv=1; }
7253: &appenv({'request.role.adv' => $tadv});
7254: }
1.994 raeburn 7255: }
7256:
1.12 www 7257: # --------------------------------------------------------------- get interface
7258:
7259: sub get {
1.131 albertel 7260: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7261: my $items='';
1.800 albertel 7262: foreach my $item (@$storearr) {
7263: $items.=&escape($item).'&';
1.191 harris41 7264: }
1.12 www 7265: $items=~s/\&$//;
1.620 albertel 7266: if (!$udomain) { $udomain=$env{'user.domain'}; }
7267: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7268: my $uhome=&homeserver($uname,$udomain);
7269:
1.133 albertel 7270: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7271: my @pairs=split(/\&/,$rep);
1.273 albertel 7272: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7273: return @pairs;
7274: }
1.15 www 7275: my %returnhash=();
1.42 www 7276: my $i=0;
1.800 albertel 7277: foreach my $item (@$storearr) {
7278: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7279: $i++;
1.191 harris41 7280: }
1.15 www 7281: return %returnhash;
1.27 www 7282: }
7283:
7284: # --------------------------------------------------------------- del interface
7285:
7286: sub del {
1.133 albertel 7287: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7288: my $items='';
1.800 albertel 7289: foreach my $item (@$storearr) {
7290: $items.=&escape($item).'&';
1.191 harris41 7291: }
1.984 neumanie 7292:
1.27 www 7293: $items=~s/\&$//;
1.620 albertel 7294: if (!$udomain) { $udomain=$env{'user.domain'}; }
7295: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7296: my $uhome=&homeserver($uname,$udomain);
7297: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7298: }
7299:
7300: # -------------------------------------------------------------- dump interface
7301:
1.1172.2.22 raeburn 7302: sub unserialize {
7303: my ($rep, $escapedkeys) = @_;
7304:
7305: return {} if $rep =~ /^error/;
7306:
7307: my %returnhash=();
7308: foreach my $item (split(/\&/,$rep)) {
7309: my ($key, $value) = split(/=/, $item, 2);
7310: $key = unescape($key) unless $escapedkeys;
7311: next if $key =~ /^error: 2 /;
7312: $returnhash{$key} = &thaw_unescape($value);
7313: }
7314: return \%returnhash;
7315: }
7316:
7317: # see Lond::dump_with_regexp
7318: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7319: sub dump {
1.1172.2.146. .1(raebu 7320:22): my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7321: if (!$udomain) { $udomain=$env{'user.domain'}; }
7322: if (!$uname) { $uname=$env{'user.name'}; }
7323: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7324:
1.1172.2.55 raeburn 7325: if ($regexp) {
7326: $regexp=&escape($regexp);
7327: } else {
7328: $regexp='.';
7329: }
1.1172.2.22 raeburn 7330: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
7331: # user is hosted on this machine
1.1172.2.55 raeburn 7332: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 7333: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 7334: return %{&unserialize($reply, $escapedkeys)};
7335: }
1.1172.2.146. .1(raebu 7336:22): my $rep;
7337:22): if ($encrypt) {
7338:22): $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7339:22): } else {
7340:22): $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7341:22): }
1.755 albertel 7342: my @pairs=split(/\&/,$rep);
7343: my %returnhash=();
1.1098 foxr 7344: if (!($rep =~ /^error/ )) {
7345: foreach my $item (@pairs) {
7346: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 7347: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 7348: next if ($key =~ /^error: 2 /);
7349: $returnhash{$key}=&thaw_unescape($value);
7350: }
1.755 albertel 7351: }
7352: return %returnhash;
1.407 www 7353: }
7354:
1.1098 foxr 7355:
1.717 albertel 7356: # --------------------------------------------------------- dumpstore interface
7357:
7358: sub dumpstore {
7359: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 7360: # same as dump but keys must be escaped. They may contain colon separated
7361: # lists of values that may themself contain colons (e.g. symbs).
7362: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7363: }
7364:
1.407 www 7365: # -------------------------------------------------------------- keys interface
7366:
7367: sub getkeys {
7368: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7369: if (!$udomain) { $udomain=$env{'user.domain'}; }
7370: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7371: my $uhome=&homeserver($uname,$udomain);
7372: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7373: my @keyarray=();
1.800 albertel 7374: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7375: next if ($key =~ /^error: 2 /);
1.800 albertel 7376: push(@keyarray,&unescape($key));
1.407 www 7377: }
7378: return @keyarray;
1.318 matthew 7379: }
7380:
1.319 matthew 7381: # --------------------------------------------------------------- currentdump
7382: sub currentdump {
1.328 matthew 7383: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7384: $courseid = $env{'request.course.id'} if (! defined($courseid));
7385: $sdom = $env{'user.domain'} if (! defined($sdom));
7386: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7387: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 7388: my $rep;
7389:
7390: if (grep { $_ eq $uhome } current_machine_ids()) {
7391: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7392: $courseid)));
7393: } else {
7394: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7395: }
7396:
1.318 matthew 7397: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7398: #
1.318 matthew 7399: my %returnhash=();
1.319 matthew 7400: #
7401: if ($rep eq "unknown_cmd") {
7402: # an old lond will not know currentdump
7403: # Do a dump and make it look like a currentdump
1.822 albertel 7404: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7405: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7406: my %hash = @tmp;
7407: @tmp=();
1.424 matthew 7408: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7409: } else {
7410: my @pairs=split(/\&/,$rep);
1.800 albertel 7411: foreach my $pair (@pairs) {
7412: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7413: my ($symb,$param) = split(/:/,$key);
7414: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7415: &thaw_unescape($value);
1.319 matthew 7416: }
1.191 harris41 7417: }
1.12 www 7418: return %returnhash;
1.424 matthew 7419: }
7420:
7421: sub convert_dump_to_currentdump{
7422: my %hash = %{shift()};
7423: my %returnhash;
7424: # Code ripped from lond, essentially. The only difference
7425: # here is the unescaping done by lonnet::dump(). Conceivably
7426: # we might run in to problems with parameter names =~ /^v\./
7427: while (my ($key,$value) = each(%hash)) {
7428: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7429: $symb = &unescape($symb);
7430: $param = &unescape($param);
1.424 matthew 7431: next if ($v eq 'version' || $symb eq 'keys');
7432: next if (exists($returnhash{$symb}) &&
7433: exists($returnhash{$symb}->{$param}) &&
7434: $returnhash{$symb}->{'v.'.$param} > $v);
7435: $returnhash{$symb}->{$param}=$value;
7436: $returnhash{$symb}->{'v.'.$param}=$v;
7437: }
7438: #
7439: # Remove all of the keys in the hashes which keep track of
7440: # the version of the parameter.
7441: while (my ($symb,$param_hash) = each(%returnhash)) {
7442: # use a foreach because we are going to delete from the hash.
7443: foreach my $key (keys(%$param_hash)) {
7444: delete($param_hash->{$key}) if ($key =~ /^v\./);
7445: }
7446: }
7447: return \%returnhash;
1.12 www 7448: }
7449:
1.627 albertel 7450: # ------------------------------------------------------ critical inc interface
7451:
7452: sub cinc {
7453: return &inc(@_,'critical');
7454: }
7455:
1.449 matthew 7456: # --------------------------------------------------------------- inc interface
7457:
7458: sub inc {
1.627 albertel 7459: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7460: if (!$udomain) { $udomain=$env{'user.domain'}; }
7461: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7462: my $uhome=&homeserver($uname,$udomain);
7463: my $items='';
7464: if (! ref($store)) {
7465: # got a single value, so use that instead
7466: $items = &escape($store).'=&';
7467: } elsif (ref($store) eq 'SCALAR') {
7468: $items = &escape($$store).'=&';
7469: } elsif (ref($store) eq 'ARRAY') {
7470: $items = join('=&',map {&escape($_);} @{$store});
7471: } elsif (ref($store) eq 'HASH') {
7472: while (my($key,$value) = each(%{$store})) {
7473: $items.= &escape($key).'='.&escape($value).'&';
7474: }
7475: }
7476: $items=~s/\&$//;
1.627 albertel 7477: if ($critical) {
7478: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7479: } else {
7480: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7481: }
1.449 matthew 7482: }
7483:
1.12 www 7484: # --------------------------------------------------------------- put interface
7485:
7486: sub put {
1.1172.2.146. .1(raebu 7487:22): my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7488: if (!$udomain) { $udomain=$env{'user.domain'}; }
7489: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7490: my $uhome=&homeserver($uname,$udomain);
1.12 www 7491: my $items='';
1.800 albertel 7492: foreach my $item (keys(%$storehash)) {
7493: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7494: }
1.12 www 7495: $items=~s/\&$//;
1.1172.2.146. .1(raebu 7496:22): if ($encrypt) {
7497:22): return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7498:22): } else {
7499:22): return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7500:22): }
1.47 www 7501: }
7502:
1.631 albertel 7503: # ------------------------------------------------------------ newput interface
7504:
7505: sub newput {
7506: my ($namespace,$storehash,$udomain,$uname)=@_;
7507: if (!$udomain) { $udomain=$env{'user.domain'}; }
7508: if (!$uname) { $uname=$env{'user.name'}; }
7509: my $uhome=&homeserver($uname,$udomain);
7510: my $items='';
7511: foreach my $key (keys(%$storehash)) {
7512: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7513: }
7514: $items=~s/\&$//;
7515: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7516: }
7517:
7518: # --------------------------------------------------------- putstore interface
7519:
1.524 raeburn 7520: sub putstore {
1.1172.2.59 raeburn 7521: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7522: if (!$udomain) { $udomain=$env{'user.domain'}; }
7523: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7524: my $uhome=&homeserver($uname,$udomain);
7525: my $items='';
1.715 albertel 7526: foreach my $key (keys(%$storehash)) {
7527: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7528: }
1.715 albertel 7529: $items=~s/\&$//;
1.716 albertel 7530: my $esc_symb=&escape($symb);
7531: my $esc_v=&escape($version);
1.715 albertel 7532: my $reply =
1.716 albertel 7533: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7534: $uhome);
1.1172.2.59 raeburn 7535: if (($tolog) && ($reply eq 'ok')) {
7536: my $namevalue='';
7537: foreach my $key (keys(%{$storehash})) {
7538: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7539: }
1.1172.2.134 raeburn 7540: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7541: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7542: '&host='.&escape($perlvar{'lonHostID'}).
7543: '&version='.$esc_v.
7544: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7545: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7546: }
1.715 albertel 7547: if ($reply eq 'unknown_cmd') {
1.716 albertel 7548: # gfall back to way things use to be done
1.715 albertel 7549: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7550: $uname);
1.524 raeburn 7551: }
1.715 albertel 7552: return $reply;
7553: }
7554:
7555: sub old_putstore {
1.716 albertel 7556: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7557: if (!$udomain) { $udomain=$env{'user.domain'}; }
7558: if (!$uname) { $uname=$env{'user.name'}; }
7559: my $uhome=&homeserver($uname,$udomain);
7560: my %newstorehash;
1.800 albertel 7561: foreach my $item (keys(%$storehash)) {
7562: my $key = $version.':'.&escape($symb).':'.$item;
7563: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7564: }
7565: my $items='';
7566: my %allitems = ();
1.800 albertel 7567: foreach my $item (keys(%newstorehash)) {
7568: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7569: my $key = $1.':keys:'.$2;
7570: $allitems{$key} .= $3.':';
7571: }
1.800 albertel 7572: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7573: }
1.800 albertel 7574: foreach my $item (keys(%allitems)) {
7575: $allitems{$item} =~ s/\:$//;
7576: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7577: }
7578: $items=~s/\&$//;
7579: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7580: }
7581:
1.47 www 7582: # ------------------------------------------------------ critical put interface
7583:
7584: sub cput {
1.134 albertel 7585: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7586: if (!$udomain) { $udomain=$env{'user.domain'}; }
7587: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7588: my $uhome=&homeserver($uname,$udomain);
1.47 www 7589: my $items='';
1.800 albertel 7590: foreach my $item (keys(%$storehash)) {
7591: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7592: }
1.47 www 7593: $items=~s/\&$//;
1.134 albertel 7594: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7595: }
7596:
7597: # -------------------------------------------------------------- eget interface
7598:
7599: sub eget {
1.133 albertel 7600: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7601: my $items='';
1.800 albertel 7602: foreach my $item (@$storearr) {
7603: $items.=&escape($item).'&';
1.191 harris41 7604: }
1.12 www 7605: $items=~s/\&$//;
1.620 albertel 7606: if (!$udomain) { $udomain=$env{'user.domain'}; }
7607: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7608: my $uhome=&homeserver($uname,$udomain);
7609: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7610: my @pairs=split(/\&/,$rep);
7611: my %returnhash=();
1.42 www 7612: my $i=0;
1.800 albertel 7613: foreach my $item (@$storearr) {
7614: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7615: $i++;
1.191 harris41 7616: }
1.12 www 7617: return %returnhash;
7618: }
7619:
1.667 albertel 7620: # ------------------------------------------------------------ tmpput interface
7621: sub tmpput {
1.802 raeburn 7622: my ($storehash,$server,$context)=@_;
1.667 albertel 7623: my $items='';
1.800 albertel 7624: foreach my $item (keys(%$storehash)) {
7625: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7626: }
7627: $items=~s/\&$//;
1.802 raeburn 7628: if (defined($context)) {
7629: $items .= ':'.&escape($context);
7630: }
1.667 albertel 7631: return &reply("tmpput:$items",$server);
7632: }
7633:
7634: # ------------------------------------------------------------ tmpget interface
7635: sub tmpget {
1.688 albertel 7636: my ($token,$server)=@_;
7637: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7638: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7639: my %returnhash;
1.1172.2.85 raeburn 7640: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7641: return %returnhash;
7642: }
1.667 albertel 7643: foreach my $item (split(/\&/,$rep)) {
7644: my ($key,$value)=split(/=/,$item);
7645: $returnhash{&unescape($key)}=&thaw_unescape($value);
7646: }
7647: return %returnhash;
7648: }
7649:
1.1113 raeburn 7650: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7651: sub tmpdel {
7652: my ($token,$server)=@_;
7653: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7654: return &reply("tmpdel:$token",$server);
7655: }
7656:
1.1172.2.13 raeburn 7657: # ------------------------------------------------------------ get_timebased_id
7658:
7659: sub get_timebased_id {
7660: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7661: $maxtries) = @_;
7662: my ($newid,$error,$dellock);
7663: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7664: return ('','ok','invalid call to get suffix');
7665: }
7666:
7667: # set defaults for any optional args for which values were not supplied
7668: if ($who eq '') {
7669: $who = $env{'user.name'}.':'.$env{'user.domain'};
7670: }
7671: if (!$locktries) {
7672: $locktries = 3;
7673: }
7674: if (!$maxtries) {
7675: $maxtries = 10;
7676: }
7677:
7678: if (($cdom eq '') || ($cnum eq '')) {
7679: if ($env{'request.course.id'}) {
7680: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7681: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7682: }
7683: if (($cdom eq '') || ($cnum eq '')) {
7684: return ('','ok','call to get suffix not in course context');
7685: }
7686: }
7687:
7688: # construct locking item
7689: my $lockhash = {
7690: $prefix."\0".'locked_'.$keyid => $who,
7691: };
7692: my $tries = 0;
7693:
7694: # attempt to get lock on nohist_$namespace file
7695: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7696: while (($gotlock ne 'ok') && $tries <$locktries) {
7697: $tries ++;
7698: sleep 1;
7699: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7700: }
7701:
7702: # attempt to get unique identifier, based on current timestamp
7703: if ($gotlock eq 'ok') {
7704: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7705: my $id = time;
7706: $newid = $id;
1.1172.2.56 raeburn 7707: if ($idtype eq 'addcode') {
7708: $newid .= &sixnum_code();
7709: }
1.1172.2.13 raeburn 7710: my $idtries = 0;
7711: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7712: if ($idtype eq 'concat') {
7713: $newid = $id.$idtries;
1.1172.2.56 raeburn 7714: } elsif ($idtype eq 'addcode') {
7715: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7716: } else {
7717: $newid ++;
7718: }
7719: $idtries ++;
7720: }
7721: if (!exists($inuse{$prefix."\0".$newid})) {
7722: my %new_item = (
7723: $prefix."\0".$newid => $who,
7724: );
7725: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7726: $cdom,$cnum);
7727: if ($putresult ne 'ok') {
7728: undef($newid);
7729: $error = 'error saving new item: '.$putresult;
7730: }
7731: } else {
1.1172.2.56 raeburn 7732: undef($newid);
1.1172.2.13 raeburn 7733: $error = ('error: no unique suffix available for the new item ');
7734: }
7735: # remove lock
7736: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7737: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7738: } else {
7739: $error = "error: could not obtain lockfile\n";
7740: $dellock = 'ok';
1.1172.2.58 raeburn 7741: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7742: $dellock = 'nolock';
7743: }
1.1172.2.13 raeburn 7744: }
7745: return ($newid,$dellock,$error);
7746: }
7747:
1.1172.2.56 raeburn 7748: sub sixnum_code {
7749: my $code;
7750: for (0..6) {
7751: $code .= int( rand(9) );
7752: }
7753: return $code;
7754: }
7755:
1.765 albertel 7756: # -------------------------------------------------- portfolio access checking
7757:
7758: sub portfolio_access {
1.1172.2.77 raeburn 7759: my ($requrl,$clientip) = @_;
1.765 albertel 7760: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7761: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7762: if ($result) {
7763: my %setters;
7764: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7765: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7766: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7767: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7768: return 'B';
7769: }
7770: } else {
1.1172.2.142 raeburn 7771: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7772: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7773: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7774: return 'B';
7775: }
7776: }
7777: }
1.765 albertel 7778: if ($result eq 'ok') {
1.766 albertel 7779: return 'F';
1.765 albertel 7780: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7781: return 'A';
1.765 albertel 7782: }
1.766 albertel 7783: return '';
1.765 albertel 7784: }
7785:
7786: sub get_portfolio_access {
1.1172.2.77 raeburn 7787: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7788:
7789: if (!ref($access_hash)) {
7790: my $current_perms = &get_portfile_permissions($udom,$unum);
7791: my %access_controls = &get_access_controls($current_perms,$group,
7792: $file_name);
7793: $access_hash = $access_controls{$file_name};
7794: }
7795:
1.1172.2.77 raeburn 7796: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7797: my $now = time;
7798: if (ref($access_hash) eq 'HASH') {
7799: foreach my $key (keys(%{$access_hash})) {
7800: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7801: if ($start > $now) {
7802: next;
7803: }
7804: if ($end && $end<$now) {
7805: next;
7806: }
7807: if ($scope eq 'public') {
7808: $public = $key;
7809: last;
7810: } elsif ($scope eq 'guest') {
7811: $guest = $key;
7812: } elsif ($scope eq 'domains') {
7813: push(@domains,$key);
7814: } elsif ($scope eq 'users') {
7815: push(@users,$key);
7816: } elsif ($scope eq 'course') {
7817: push(@courses,$key);
7818: } elsif ($scope eq 'group') {
7819: push(@groups,$key);
1.1172.2.77 raeburn 7820: } elsif ($scope eq 'ip') {
7821: push(@ips,$key);
1.765 albertel 7822: }
7823: }
7824: if ($public) {
7825: return 'ok';
1.1172.2.77 raeburn 7826: } elsif (@ips > 0) {
7827: my $allowed;
7828: foreach my $ipkey (@ips) {
7829: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7830: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7831: $allowed = 1;
7832: last;
7833: }
7834: }
7835: }
7836: if ($allowed) {
7837: return 'ok';
7838: }
1.765 albertel 7839: }
7840: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7841: if ($guest) {
7842: return $guest;
7843: }
7844: } else {
7845: if (@domains > 0) {
7846: foreach my $domkey (@domains) {
7847: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7848: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7849: return 'ok';
7850: }
7851: }
7852: }
7853: }
7854: if (@users > 0) {
7855: foreach my $userkey (@users) {
1.865 raeburn 7856: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7857: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7858: if (ref($item) eq 'HASH') {
7859: if (($item->{'uname'} eq $env{'user.name'}) &&
7860: ($item->{'udom'} eq $env{'user.domain'})) {
7861: return 'ok';
7862: }
7863: }
7864: }
7865: }
1.765 albertel 7866: }
7867: }
7868: my %roleshash;
7869: my @courses_and_groups = @courses;
7870: push(@courses_and_groups,@groups);
7871: if (@courses_and_groups > 0) {
7872: my (%allgroups,%allroles);
7873: my ($start,$end,$role,$sec,$group);
7874: foreach my $envkey (%env) {
1.1060 raeburn 7875: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7876: my $cid = $2.'_'.$3;
7877: if ($1 eq 'gr') {
7878: $group = $4;
7879: $allgroups{$cid}{$group} = $env{$envkey};
7880: } else {
7881: if ($4 eq '') {
7882: $sec = 'none';
7883: } else {
7884: $sec = $4;
7885: }
7886: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7887: }
1.811 albertel 7888: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7889: my $cid = $2.'_'.$3;
7890: if ($4 eq '') {
7891: $sec = 'none';
7892: } else {
7893: $sec = $4;
7894: }
7895: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7896: }
7897: }
7898: if (keys(%allroles) == 0) {
7899: return;
7900: }
7901: foreach my $key (@courses_and_groups) {
7902: my %content = %{$$access_hash{$key}};
7903: my $cnum = $content{'number'};
7904: my $cdom = $content{'domain'};
7905: my $cid = $cdom.'_'.$cnum;
7906: if (!exists($allroles{$cid})) {
7907: next;
7908: }
7909: foreach my $role_id (keys(%{$content{'roles'}})) {
7910: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7911: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7912: my @status = @{$content{'roles'}{$role_id}{'access'}};
7913: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7914: foreach my $role (keys(%{$allroles{$cid}})) {
7915: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7916: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7917: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7918: if (grep/^all$/,@sections) {
7919: return 'ok';
7920: } else {
7921: if (grep/^$sec$/,@sections) {
7922: return 'ok';
7923: }
7924: }
7925: }
7926: }
7927: if (keys(%{$allgroups{$cid}}) == 0) {
7928: if (grep/^none$/,@groups) {
7929: return 'ok';
7930: }
7931: } else {
7932: if (grep/^all$/,@groups) {
7933: return 'ok';
7934: }
7935: foreach my $group (keys(%{$allgroups{$cid}})) {
7936: if (grep/^$group$/,@groups) {
7937: return 'ok';
7938: }
7939: }
7940: }
7941: }
7942: }
7943: }
7944: }
7945: }
7946: if ($guest) {
7947: return $guest;
7948: }
7949: }
7950: }
7951: return;
7952: }
7953:
7954: sub course_group_datechecker {
7955: my ($dates,$now,$status) = @_;
7956: my ($start,$end) = split(/\./,$dates);
7957: if (!$start && !$end) {
7958: return 'ok';
7959: }
7960: if (grep/^active$/,@{$status}) {
7961: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7962: return 'ok';
7963: }
7964: }
7965: if (grep/^previous$/,@{$status}) {
7966: if ($end > $now ) {
7967: return 'ok';
7968: }
7969: }
7970: if (grep/^future$/,@{$status}) {
7971: if ($start > $now) {
7972: return 'ok';
7973: }
7974: }
7975: return;
7976: }
7977:
7978: sub parse_portfolio_url {
7979: my ($url) = @_;
7980:
7981: my ($type,$udom,$unum,$group,$file_name);
7982:
1.823 albertel 7983: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7984: $type = 1;
7985: $udom = $1;
7986: $unum = $2;
7987: $file_name = $3;
1.823 albertel 7988: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7989: $type = 2;
7990: $udom = $1;
7991: $unum = $2;
7992: $group = $3;
7993: $file_name = $3.'/'.$4;
7994: }
7995: if (wantarray) {
7996: return ($type,$udom,$unum,$file_name,$group);
7997: }
7998: return $type;
7999: }
8000:
8001: sub is_portfolio_url {
8002: my ($url) = @_;
8003: return scalar(&parse_portfolio_url($url));
8004: }
8005:
1.798 raeburn 8006: sub is_portfolio_file {
8007: my ($file) = @_;
1.820 raeburn 8008: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 8009: return 1;
8010: }
8011: return;
8012: }
8013:
1.1172.2.146. .13(raeb 8014:-23): sub is_coursetool_logo {
8015:-23): my ($uri) = @_;
8016:-23): if ($env{'request.course.id'}) {
8017:-23): my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8018:-23): if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
8019:-23): return 1;
8020:-23): }
8021:-23): }
8022:-23): return;
8023:-23): }
8024:-23):
1.976 raeburn 8025: sub usertools_access {
1.1084 raeburn 8026: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8027: my ($access,%tools);
8028: if ($context eq '') {
8029: $context = 'tools';
8030: }
8031: if ($context eq 'requestcourses') {
8032: %tools = (
8033: official => 1,
8034: unofficial => 1,
1.1006 raeburn 8035: community => 1,
1.1172.2.37 raeburn 8036: textbook => 1,
1.1172.2.146. .13(raeb 8037:-23): lti => 1,
1.985 raeburn 8038: );
1.1172.2.9 raeburn 8039: } elsif ($context eq 'requestauthor') {
8040: %tools = (
8041: requestauthor => 1,
8042: );
1.1172.2.146. .18(raeb 8043:-24): } elsif ($context eq 'authordefaults') {
8044:-24): %tools = (
8045:-24): webdav => 1,
8046:-24): );
1.985 raeburn 8047: } else {
8048: %tools = (
8049: aboutme => 1,
8050: blog => 1,
8051: portfolio => 1,
1.1172.2.146. .22(raeb 8052:-24): portaccess => 1,
.6(raebu 8053:22): timezone => 1,
1.985 raeburn 8054: );
8055: }
1.976 raeburn 8056: return if (!defined($tools{$tool}));
8057:
1.1172.2.35 raeburn 8058: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8059: $udom = $env{'user.domain'};
8060: $uname = $env{'user.name'};
8061: }
8062:
1.978 raeburn 8063: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8064: if ($action ne 'reload') {
1.985 raeburn 8065: if ($context eq 'requestcourses') {
8066: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 8067: } elsif ($context eq 'requestauthor') {
8068: return $env{'environment.canrequest.author'};
1.1172.2.146. .18(raeb 8069:-24): } elsif ($context eq 'authordefaults') {
8070:-24): if ($tool eq 'webdav') {
8071:-24): return $env{'environment.availabletools.'.$tool};
8072:-24): }
1.985 raeburn 8073: } else {
8074: return $env{'environment.availabletools.'.$tool};
8075: }
8076: }
1.976 raeburn 8077: }
8078:
1.1172.2.9 raeburn 8079: my ($toolstatus,$inststatus,$envkey);
8080: if ($context eq 'requestauthor') {
8081: $envkey = $context;
1.1172.2.146. .18(raeb 8082:-24): } elsif ($context eq 'authordefaults') {
8083:-24): if ($tool eq 'webdav') {
8084:-24): $envkey = 'tools.'.$tool;
8085:-24): }
1.1172.2.9 raeburn 8086: } else {
8087: $envkey = $context.'.'.$tool;
8088: }
1.976 raeburn 8089:
1.985 raeburn 8090: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8091: ($action ne 'reload')) {
1.1172.2.9 raeburn 8092: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8093: $inststatus = $env{'environment.inststatus'};
8094: } else {
1.1084 raeburn 8095: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 8096: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8097: $inststatus = $userenvref->{'inststatus'};
8098: } else {
1.1172.2.9 raeburn 8099: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8100: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8101: $inststatus = $userenv{'inststatus'};
8102: }
1.976 raeburn 8103: }
8104:
8105: if ($toolstatus ne '') {
8106: if ($toolstatus) {
8107: $access = 1;
8108: } else {
8109: $access = 0;
8110: }
8111: return $access;
8112: }
8113:
1.1084 raeburn 8114: my ($is_adv,%domdef);
8115: if (ref($is_advref) eq 'HASH') {
8116: $is_adv = $is_advref->{'is_adv'};
8117: } else {
8118: $is_adv = &is_advanced_user($udom,$uname);
8119: }
8120: if (ref($domdefref) eq 'HASH') {
8121: %domdef = %{$domdefref};
8122: } else {
8123: %domdef = &get_domain_defaults($udom);
8124: }
1.976 raeburn 8125: if (ref($domdef{$tool}) eq 'HASH') {
8126: if ($is_adv) {
8127: if ($domdef{$tool}{'_LC_adv'} ne '') {
8128: if ($domdef{$tool}{'_LC_adv'}) {
8129: $access = 1;
8130: } else {
8131: $access = 0;
8132: }
8133: return $access;
8134: }
8135: }
8136: if ($inststatus ne '') {
8137: my ($hasaccess,$hasnoaccess);
8138: foreach my $affiliation (split(/:/,$inststatus)) {
8139: if ($domdef{$tool}{$affiliation} ne '') {
8140: if ($domdef{$tool}{$affiliation}) {
8141: $hasaccess = 1;
8142: } else {
8143: $hasnoaccess = 1;
8144: }
8145: }
8146: }
8147: if ($hasaccess || $hasnoaccess) {
8148: if ($hasaccess) {
8149: $access = 1;
8150: } elsif ($hasnoaccess) {
8151: $access = 0;
8152: }
8153: return $access;
8154: }
8155: } else {
8156: if ($domdef{$tool}{'default'} ne '') {
8157: if ($domdef{$tool}{'default'}) {
8158: $access = 1;
8159: } elsif ($domdef{$tool}{'default'} == 0) {
8160: $access = 0;
8161: }
8162: return $access;
8163: }
8164: }
8165: } else {
1.1172.2.6 raeburn 8166: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8167: $access = 1;
8168: } else {
8169: $access = 0;
8170: }
1.976 raeburn 8171: return $access;
8172: }
8173: }
8174:
1.1050 raeburn 8175: sub is_course_owner {
8176: my ($cdom,$cnum,$udom,$uname) = @_;
8177: if (($udom eq '') || ($uname eq '')) {
8178: $udom = $env{'user.domain'};
8179: $uname = $env{'user.name'};
8180: }
8181: unless (($udom eq '') || ($uname eq '')) {
8182: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8183: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8184: return 1;
8185: } else {
8186: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
8187: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8188: return 1;
8189: }
8190: }
8191: }
8192: }
8193: return;
8194: }
8195:
1.976 raeburn 8196: sub is_advanced_user {
8197: my ($udom,$uname) = @_;
1.1085 raeburn 8198: if ($udom ne '' && $uname ne '') {
8199: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8200: if (wantarray) {
8201: return ($env{'user.adv'},$env{'user.author'});
8202: } else {
8203: return $env{'user.adv'};
8204: }
1.1085 raeburn 8205: }
8206: }
1.976 raeburn 8207: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8208: my %allroles;
1.1128 raeburn 8209: my ($is_adv,$is_author);
1.976 raeburn 8210: foreach my $role (keys(%roleshash)) {
8211: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8212: my $area = '/'.$tdomain.'/'.$trest;
8213: if ($sec ne '') {
8214: $area .= '/'.$sec;
8215: }
8216: if (($area ne '') && ($trole ne '')) {
8217: my $spec=$trole.'.'.$area;
8218: if ($trole =~ /^cr\//) {
8219: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8220: } elsif ($trole ne 'gr') {
8221: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8222: }
1.1128 raeburn 8223: if ($trole eq 'au') {
8224: $is_author = 1;
8225: }
1.976 raeburn 8226: }
8227: }
8228: foreach my $role (keys(%allroles)) {
8229: last if ($is_adv);
8230: foreach my $item (split(/:/,$allroles{$role})) {
8231: if ($item ne '') {
8232: my ($privilege,$restrictions)=split(/&/,$item);
8233: if ($privilege eq 'adv') {
8234: $is_adv = 1;
8235: last;
8236: }
8237: }
8238: }
8239: }
1.1128 raeburn 8240: if (wantarray) {
8241: return ($is_adv,$is_author);
8242: }
1.976 raeburn 8243: return $is_adv;
8244: }
1.798 raeburn 8245:
1.1035 raeburn 8246: sub check_can_request {
1.1172.2.146. .13(raeb 8247:-23): my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8248: my $canreq = 0;
1.1172.2.146. .13(raeb 8249:-23): if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8250:-23): $uname = $env{'user.name'};
8251:-23): $udom = $env{'user.domain'};
8252:-23): }
1.1035 raeburn 8253: my ($types,$typename) = &Apache::loncommon::course_types();
8254: my @options = ('approval','validate','autolimit');
8255: my $optregex = join('|',@options);
8256: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8257: foreach my $type (@{$types}) {
1.1172.2.146. .13(raeb 8258:-23): if (&usertools_access($uname,$udom,$type,undef,
8259:-23): 'requestcourses')) {
1.1035 raeburn 8260: $canreq ++;
1.1036 raeburn 8261: if (ref($request_domains) eq 'HASH') {
1.1172.2.146. .13(raeb 8262:-23): push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8263: }
1.1172.2.146. .13(raeb 8264:-23): if ($dom eq $udom) {
1.1035 raeburn 8265: $can_request->{$type} = 1;
8266: }
8267: }
1.1172.2.146. .13(raeb 8268:-23): if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8269:-23): ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8270: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8271: if (@curr > 0) {
1.1036 raeburn 8272: foreach my $item (@curr) {
8273: if (ref($request_domains) eq 'HASH') {
8274: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8275: if ($otherdom ne '') {
8276: if (ref($request_domains->{$type}) eq 'ARRAY') {
8277: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8278: push(@{$request_domains->{$type}},$otherdom);
8279: }
8280: } else {
8281: push(@{$request_domains->{$type}},$otherdom);
8282: }
8283: }
8284: }
8285: }
1.1172.2.146. .13(raeb 8286:-23): unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8287: $canreq ++;
1.1035 raeburn 8288: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8289: $can_request->{$type} = 1;
8290: }
8291: }
8292: }
8293: }
8294: }
8295: }
8296: return $canreq;
8297: }
8298:
1.341 www 8299: # ---------------------------------------------- Custom access rule evaluation
8300:
8301: sub customaccess {
8302: my ($priv,$uri)=@_;
1.807 albertel 8303: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8304: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8305: $udom = &LONCAPA::clean_domain($udom);
8306: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8307: my $access=0;
1.800 albertel 8308: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8309: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8310: if ($type eq 'user') {
8311: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8312: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8313: if ($tdom) {
8314: if ($tdom ne $env{'user.domain'}) { next; }
8315: }
1.896 albertel 8316: if ($tuname) {
8317: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8318: }
8319: $access=($effect eq 'allow');
8320: last;
8321: }
8322: } else {
8323: if ($role) {
8324: if ($role ne $urole) { next; }
8325: }
8326: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8327: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8328: if ($tdom) {
8329: if ($tdom ne $udom) { next; }
8330: }
8331: if ($tcrs) {
8332: if ($tcrs ne $ucrs) { next; }
8333: }
8334: if ($tsec) {
8335: if ($tsec ne $usec) { next; }
8336: }
8337: $access=($effect eq 'allow');
8338: last;
8339: }
8340: if ($realm eq '' && $role eq '') {
8341: $access=($effect eq 'allow');
8342: }
1.402 bowersj2 8343: }
1.341 www 8344: }
8345: return $access;
8346: }
8347:
1.103 harris41 8348: # ------------------------------------------------- Check for a user privilege
1.12 www 8349:
8350: sub allowed {
1.1172.2.146. .1(raebu 8351:22): my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8352: my $ver_orguri=$uri;
1.439 www 8353: $uri=&deversion($uri);
1.152 www 8354: my $orguri=$uri;
1.52 www 8355: $uri=&declutter($uri);
1.809 raeburn 8356:
1.810 raeburn 8357: if ($priv eq 'evb') {
1.1172.2.146. .3(raebu 8358:22): # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8359: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8360: return $1;
8361: } else {
8362: return;
8363: }
8364: }
8365:
1.620 albertel 8366: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8367: # Free bre access to adm and meta resources
1.1172.2.146. .1(raebu 8368:22): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8369: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8370: && ($priv eq 'bre')) {
1.14 www 8371: return 'F';
1.159 www 8372: }
8373:
1.545 banghart 8374: # Free bre access to user's own portfolio contents
1.714 raeburn 8375: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8376: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8377: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8378: my %setters;
1.1172.2.142 raeburn 8379: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8380: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8381: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8382: return 'B';
8383: } else {
8384: return 'F';
8385: }
1.545 banghart 8386: }
8387:
1.762 raeburn 8388: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8389: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8390: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8391: if (exists($env{'request.course.id'})) {
8392: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8393: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8394: if (($domain eq $cdom) && ($name eq $cnum)) {
8395: my $courseprivid=$env{'request.course.id'};
8396: $courseprivid=~s/\_/\//;
8397: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8398: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8399: return $1;
1.762 raeburn 8400: } else {
8401: if ($env{'request.course.sec'}) {
8402: $courseprivid.='/'.$env{'request.course.sec'};
8403: }
8404: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8405: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8406: return $2;
8407: }
1.714 raeburn 8408: }
8409: }
8410: }
8411: }
8412:
1.159 www 8413: # Free bre to public access
8414:
8415: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8416:22): my $copyright;
8417:22): unless ($uri =~ /ext\.tool/) {
8418:22): $copyright=&metadata($uri,'copyright');
8419:22): }
1.620 albertel 8420: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8421: return 'F';
8422: }
1.238 www 8423: if ($copyright eq 'priv') {
8424: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8425: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8426: return '';
8427: }
8428: }
8429: if ($copyright eq 'domain') {
8430: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8431: unless (($env{'user.domain'} eq $1) ||
8432: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8433: return '';
8434: }
1.262 matthew 8435: }
1.620 albertel 8436: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8437: # Library role, so allow browsing of resources in this domain.
8438: return 'F';
1.238 www 8439: }
1.341 www 8440: if ($copyright eq 'custom') {
8441: unless (&customaccess($priv,$uri)) { return ''; }
8442: }
1.14 www 8443: }
1.264 matthew 8444: # Domain coordinator is trying to create a course
1.620 albertel 8445: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8446: # uri is the requested domain in this case.
8447: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8448: # a role of dc for the domain in question.
1.620 albertel 8449: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8450: }
1.29 www 8451:
1.52 www 8452: my $thisallowed='';
8453: my $statecond=0;
8454: my $courseprivid='';
8455:
1.1039 raeburn 8456: my $ownaccess;
1.1043 raeburn 8457: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8458: if (($priv eq 'bro') && ($env{'user.author'})) {
8459: if ($uri eq '') {
8460: $ownaccess = 1;
8461: } else {
8462: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8463: my $udom = $env{'user.domain'};
8464: my $uname = $env{'user.name'};
8465: if ($uri =~ m{^\Q$udom\E/?$}) {
8466: $ownaccess = 1;
1.1040 raeburn 8467: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8468: unless ($uri =~ m{\.\./}) {
8469: $ownaccess = 1;
8470: }
8471: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8472: my $now = time;
8473: if ($uri =~ m{^([^/]+)/?$}) {
8474: my $adom = $1;
8475: foreach my $key (keys(%env)) {
1.1042 raeburn 8476: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8477: my ($start,$end) = split(/\./,$env{$key});
8478: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8479: $ownaccess = 1;
8480: last;
8481: }
8482: }
8483: }
8484: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8485: my $adom = $1;
8486: my $aname = $2;
1.1042 raeburn 8487: foreach my $role ('ca','aa') {
8488: if ($env{"user.role.$role./$adom/$aname"}) {
8489: my ($start,$end) =
1.1172.2.142 raeburn 8490: split(/\./,$env{"user.role.$role./$adom/$aname"});
8491: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8492: $ownaccess = 1;
8493: last;
8494: }
1.1039 raeburn 8495: }
8496: }
8497: }
8498: }
8499: }
8500: }
8501: }
8502:
1.52 www 8503: # Course
8504:
1.620 albertel 8505: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8506: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8507: $thisallowed.=$1;
8508: }
1.52 www 8509: }
1.29 www 8510:
1.52 www 8511: # Domain
8512:
1.620 albertel 8513: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8514: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8515: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8516: $thisallowed.=$1;
8517: }
1.12 www 8518: }
1.52 www 8519:
1.1141 raeburn 8520: # User who is not author or co-author might still be able to edit
8521: # resource of an author in the domain (e.g., if Domain Coordinator).
8522: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8523: (&allowed('mdc',$env{'request.course.id'}))) {
8524: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8525: $thisallowed.=$1;
8526: }
8527: }
8528:
1.52 www 8529: # Course: uri itself is a course
1.66 www 8530: my $courseuri=$uri;
8531: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8532: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8533:
1.620 albertel 8534: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8535: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8536: if ($priv eq 'mip') {
8537: my $rem = $1;
8538: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8539: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8540: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8541: if ($cdom ne '') {
8542: my %passwdconf = &get_passwdconf($cdom);
8543: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8544: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8545: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8546: my @inststatuses = split(':',$env{'environment.inststatus'});
8547: unless (@inststatuses) {
8548: @inststatuses = ('default');
8549: }
8550: foreach my $status (@inststatuses) {
8551: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8552: $thisallowed.=$rem;
8553: }
8554: }
8555: }
8556: }
8557: }
8558: }
8559: }
8560: } else {
8561: unless (($priv eq 'bro') && (!$ownaccess)) {
8562: $thisallowed.=$1;
8563: }
1.1039 raeburn 8564: }
1.12 www 8565: }
1.29 www 8566:
1.665 albertel 8567: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8568: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8569: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8570: $thisallowed='';
1.671 raeburn 8571: my ($match)=&is_on_map($uri);
8572: if ($match) {
8573: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8574: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8575: my $value = $1;
1.1172.2.146. .1(raebu 8576:22): my $deeplinkblock;
8577:22): unless ($nodeeplinkcheck) {
8578:22): $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8579:22): }
8580:22): if ($deeplinkblock) {
8581:22): $thisallowed='D';
8582:22): } elsif ($noblockcheck) {
1.1172.2.65 raeburn 8583: $thisallowed.=$value;
1.1162 raeburn 8584: } else {
1.1172.2.126 raeburn 8585: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8586: if (@blockers > 0) {
8587: $thisallowed = 'B';
8588: } else {
8589: $thisallowed.=$value;
8590: }
1.1162 raeburn 8591: }
1.671 raeburn 8592: }
8593: } else {
1.705 albertel 8594: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8595: if ($refuri) {
8596: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8597: $thisallowed='F';
1.671 raeburn 8598: } else {
8599: $refuri=&declutter($refuri);
8600: my ($match) = &is_on_map($refuri);
8601: if ($match) {
1.1172.2.146. .1(raebu 8602:22): my $deeplinkblock;
8603:22): unless ($nodeeplinkcheck) {
8604:22): $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8605:22): }
8606:22): if ($deeplinkblock) {
8607:22): $thisallowed='D';
8608:22): } elsif ($noblockcheck) {
1.1162 raeburn 8609: $thisallowed='F';
1.1172.2.65 raeburn 8610: } else {
1.1172.2.127 raeburn 8611: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8612: if (@blockers > 0) {
8613: $thisallowed = 'B';
8614: } else {
8615: $thisallowed='F';
8616: }
1.1162 raeburn 8617: }
1.671 raeburn 8618: }
1.669 raeburn 8619: }
1.671 raeburn 8620: }
8621: }
1.314 www 8622: }
1.492 albertel 8623:
1.766 albertel 8624: if ($priv eq 'bre'
8625: && $thisallowed ne 'F'
8626: && $thisallowed ne '2'
8627: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8628: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8629: }
8630:
1.52 www 8631: # Full access at system, domain or course-wide level? Exit.
1.29 www 8632: if ($thisallowed=~/F/) {
8633: return 'F';
8634: }
8635:
1.52 www 8636: # If this is generating or modifying users, exit with special codes
1.29 www 8637:
1.1172.2.146. .22(raeb 8638:-24): if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa::vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643 www 8639: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8640: my ($audom,$auname)=split('/',$uri);
1.643 www 8641: # no author name given, so this just checks on the general right to make a co-author in this domain
8642: unless ($auname) { return $thisallowed; }
8643: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8644: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8645: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8646: ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1172.2.146. .22(raeb 8647:-24): } elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
8648:-24): my ($audom,$auname)=split('/',$uri);
8649:-24): unless ($auname) { return $thisallowed; }
8650:-24): unless (($env{'request.role'} eq "dc./$audom") ||
8651:-24): ($env{'request.role'} eq "ca./$uri")) {
8652:-24): return '';
8653:-24): }
1.642 albertel 8654: }
1.52 www 8655: return $thisallowed;
8656: }
8657: #
1.103 harris41 8658: # Gathered so far: system, domain and course wide privileges
1.52 www 8659: #
8660: # Course: See if uri or referer is an individual resource that is part of
8661: # the course
8662:
1.620 albertel 8663: if ($env{'request.course.id'}) {
1.232 www 8664:
1.1172.2.146. .13(raeb 8665:-23): if ($priv eq 'bre') {
8666:-23): if (&is_coursetool_logo($uri)) {
8667:-23): return 'F';
8668:-23): }
8669:-23): }
8670:-23):
1.1172.2.115 raeburn 8671: # If this is modifying password (internal auth) domains must match for user and user's role.
8672:
8673: if ($priv eq 'mip') {
8674: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8675: return $thisallowed;
8676: } else {
8677: return '';
8678: }
8679: }
8680:
1.620 albertel 8681: $courseprivid=$env{'request.course.id'};
8682: if ($env{'request.course.sec'}) {
8683: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8684: }
8685: $courseprivid=~s/\_/\//;
8686: my $checkreferer=1;
1.232 www 8687: my ($match,$cond)=&is_on_map($uri);
8688: if ($match) {
8689: $statecond=$cond;
1.620 albertel 8690: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8691: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8692: my $value = $1;
8693: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8694:22): my $deeplinkblock;
8695:22): unless ($nodeeplinkcheck) {
8696:22): $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8697:22): }
8698:22): if ($deeplinkblock) {
8699:22): $thisallowed = 'D';
8700:22): } elsif ($noblockcheck) {
1.1162 raeburn 8701: $thisallowed.=$value;
1.1172.2.65 raeburn 8702: } else {
1.1172.2.126 raeburn 8703: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8704: if (@blockers > 0) {
8705: $thisallowed = 'B';
8706: } else {
8707: $thisallowed.=$value;
8708: }
1.1162 raeburn 8709: }
8710: } else {
8711: $thisallowed.=$value;
8712: }
1.52 www 8713: $checkreferer=0;
8714: }
1.29 www 8715: }
1.1172.2.126 raeburn 8716:
1.148 www 8717: if ($checkreferer) {
1.620 albertel 8718: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8719: unless ($refuri) {
1.800 albertel 8720: foreach my $key (keys(%env)) {
8721: if ($key=~/^httpref\..*\*/) {
8722: my $pattern=$key;
1.156 www 8723: $pattern=~s/^httpref\.\/res\///;
1.148 www 8724: $pattern=~s/\*/\[\^\/\]\+/g;
8725: $pattern=~s/\//\\\//g;
1.152 www 8726: if ($orguri=~/$pattern/) {
1.800 albertel 8727: $refuri=$env{$key};
1.148 www 8728: }
8729: }
1.191 harris41 8730: }
1.148 www 8731: }
1.232 www 8732:
1.148 www 8733: if ($refuri) {
1.152 www 8734: $refuri=&declutter($refuri);
1.232 www 8735: my ($match,$cond)=&is_on_map($refuri);
8736: if ($match) {
8737: my $refstatecond=$cond;
1.620 albertel 8738: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8739: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8740: my $value = $1;
8741: if ($priv eq 'bre') {
1.1172.2.146. .1(raebu 8742:22): my $deeplinkblock;
8743:22): unless ($nodeeplinkcheck) {
8744:22): $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8745:22): }
8746:22): if ($deeplinkblock) {
8747:22): $thisallowed = 'D';
8748:22): } elsif ($noblockcheck) {
1.1162 raeburn 8749: $thisallowed.=$value;
1.1172.2.65 raeburn 8750: } else {
1.1172.2.127 raeburn 8751: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8752: if (@blockers > 0) {
8753: $thisallowed = 'B';
8754: } else {
8755: $thisallowed.=$value;
8756: }
1.1162 raeburn 8757: }
8758: } else {
8759: $thisallowed.=$value;
8760: }
1.53 www 8761: $uri=$refuri;
8762: $statecond=$refstatecond;
1.52 www 8763: }
8764: }
1.148 www 8765: }
1.29 www 8766: }
1.52 www 8767: }
1.29 www 8768:
1.52 www 8769: #
1.103 harris41 8770: # Gathered now: all privileges that could apply, and condition number
1.52 www 8771: #
8772: #
8773: # Full or no access?
8774: #
1.29 www 8775:
1.52 www 8776: if ($thisallowed=~/F/) {
8777: return 'F';
8778: }
1.29 www 8779:
1.52 www 8780: unless ($thisallowed) {
8781: return '';
8782: }
1.29 www 8783:
1.52 www 8784: # Restrictions exist, deal with them
8785: #
8786: # C:according to course preferences
8787: # R:according to resource settings
8788: # L:unless locked
8789: # X:according to user session state
8790: #
8791:
8792: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8793: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8794: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8795: # courses, and 2 minutes for current course, in which user has st or ta role
8796: # which is neither expired nor a future role (unless current course).
1.52 www 8797:
1.1172.2.142 raeburn 8798: my ($needlockcheck,$now,$crsonly);
1.52 www 8799: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8800: $now = time;
8801: if ($priv eq 'bre') {
8802: if ($uri ne '') {
8803: if ($orguri =~ m{^/+res/}) {
8804: if ($uri =~ m{^lib/templates/}) {
8805: if ($env{'request.course.id'}) {
8806: $crsonly = 1;
8807: $needlockcheck = 1;
8808: }
8809: } else {
8810: $needlockcheck = 1;
8811: }
8812: } elsif ($env{'request.course.id'}) {
8813: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8814: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8815: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8816: $crsonly = 1;
8817: }
8818: $needlockcheck = 1;
8819: }
8820: }
8821: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8822: $needlockcheck = 1;
8823: }
8824: }
8825: if ($needlockcheck) {
8826: foreach my $envkey (keys(%env)) {
1.54 www 8827: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8828: my $courseid=$2;
8829: my $roleid=$1.'.'.$2;
1.92 www 8830: $courseid=~s/^\///;
1.1172.2.142 raeburn 8831: unless ($env{'request.role'} eq $roleid) {
8832: my ($start,$end) = split(/\./,$env{$envkey});
8833: next unless (($now >= $start) && (!$end || $end > $now));
8834: }
1.54 www 8835: my $expiretime=600;
1.620 albertel 8836: if ($env{'request.role'} eq $roleid) {
1.54 www 8837: $expiretime=120;
8838: }
8839: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8840: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8841: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8842: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8843: }
1.620 albertel 8844: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8845: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8846: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8847: &log($env{'user.domain'},$env{'user.name'},
8848: $env{'user.home'},
1.57 www 8849: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8850: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8851: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8852: return '';
8853: }
8854: }
1.620 albertel 8855: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8856: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8857: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8858: &log($env{'user.domain'},$env{'user.name'},
8859: $env{'user.home'},
1.57 www 8860: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8861: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8862: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8863: return '';
8864: }
8865: }
8866: }
1.29 www 8867: }
1.52 www 8868: }
1.1172.2.126 raeburn 8869:
1.52 www 8870: #
8871: # Rest of the restrictions depend on selected course
8872: #
8873:
1.620 albertel 8874: unless ($env{'request.course.id'}) {
1.766 albertel 8875: if ($thisallowed eq 'A') {
8876: return 'A';
1.814 raeburn 8877: } elsif ($thisallowed eq 'B') {
8878: return 'B';
1.766 albertel 8879: } else {
8880: return '1';
8881: }
1.52 www 8882: }
1.29 www 8883:
1.52 www 8884: #
8885: # Now user is definitely in a course
8886: #
1.53 www 8887:
8888:
8889: # Course preferences
8890:
8891: if ($thisallowed=~/C/) {
1.620 albertel 8892: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8893: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8894: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8895: =~/\Q$rolecode\E/) {
1.1103 raeburn 8896: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8897: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8898: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8899: $env{'request.course.id'});
8900: }
1.237 www 8901: return '';
8902: }
8903:
1.620 albertel 8904: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8905: =~/\Q$unamedom\E/) {
1.1103 raeburn 8906: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8907: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8908: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8909: $env{'request.course.id'});
8910: }
1.54 www 8911: return '';
8912: }
1.53 www 8913: }
8914:
8915: # Resource preferences
8916:
8917: if ($thisallowed=~/R/) {
1.620 albertel 8918: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8919: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8920: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8921: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8922: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8923: }
8924: return '';
1.54 www 8925: }
1.53 www 8926: }
1.30 www 8927:
1.1172.2.146. .1(raebu 8928:22): # Restricted for deeplinked session?
8929:22):
8930:22): if ($env{'request.deeplink.login'}) {
8931:22): if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8932:22): if (!$symb) { $symb=&symbread($uri,1); }
8933:22): if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8934:22): return '';
8935:22): }
8936:22): }
8937:22): }
8938:22):
1.246 www 8939: # Restricted by state or randomout?
1.30 www 8940:
1.52 www 8941: if ($thisallowed=~/X/) {
1.620 albertel 8942: if ($env{'acc.randomout'}) {
1.579 albertel 8943: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8944: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8945: return '';
8946: }
1.247 www 8947: }
8948: if (&condval($statecond)) {
1.52 www 8949: return '2';
8950: } else {
8951: return '';
8952: }
8953: }
1.30 www 8954:
1.766 albertel 8955: if ($thisallowed eq 'A') {
8956: return 'A';
1.814 raeburn 8957: } elsif ($thisallowed eq 'B') {
8958: return 'B';
1.1172.2.146. .1(raebu 8959:22): } elsif ($thisallowed eq 'D') {
8960:22): return 'D';
1.766 albertel 8961: }
1.52 www 8962: return 'F';
1.232 www 8963: }
1.1162 raeburn 8964:
1.1172.2.13 raeburn 8965: # ------------------------------------------- Check construction space access
8966:
8967: sub constructaccess {
8968: my ($url,$setpriv)=@_;
8969:
8970: # We do not allow editing of previous versions of files
8971: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8972:
8973: # Get username and domain from URL
8974: my ($ownername,$ownerdomain,$ownerhome);
8975:
8976: ($ownerdomain,$ownername) =
1.1172.2.146. .19(raeb 8977:-24): ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8978:
8979: # The URL does not really point to any authorspace, forget it
8980: unless (($ownername) && ($ownerdomain)) { return ''; }
8981:
8982: # Now we need to see if the user has access to the authorspace of
8983: # $ownername at $ownerdomain
8984:
8985: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8986: # Real author for this?
8987: $ownerhome = $env{'user.home'};
8988: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8989: return ($ownername,$ownerdomain,$ownerhome);
8990: }
8991: } else {
8992: # Co-author for this?
8993: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8994: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8995: $ownerhome = &homeserver($ownername,$ownerdomain);
8996: return ($ownername,$ownerdomain,$ownerhome);
8997: }
8998: }
8999:
9000: # We don't have any access right now. If we are not possibly going to do anything about this,
9001: # we might as well leave
9002: unless ($setpriv) { return ''; }
9003:
9004: # Backdoor access?
9005: my $allowed=&allowed('eco',$ownerdomain);
9006: # Nope
9007: unless ($allowed) { return ''; }
9008: # Looks like we may have access, but could be locked by the owner of the construction space
9009: if ($allowed eq 'U') {
9010: my %blocked=&get('environment',['domcoord.author'],
9011: $ownerdomain,$ownername);
9012: # Is blocked by owner
9013: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
9014: }
9015: if (($allowed eq 'F') || ($allowed eq 'U')) {
9016: # Grant temporary access
9017: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 9018: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 9019: if (!$update) { $update = $then; }
9020: my $refresh=$env{'user.refresh.time'};
9021: if (!$refresh) { $refresh = $update; }
9022: my $now = time;
9023: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
9024: $now,'ca','constructaccess');
9025: $ownerhome = &homeserver($ownername,$ownerdomain);
9026: return($ownername,$ownerdomain,$ownerhome);
9027: }
9028: # No business here
9029: return '';
9030: }
9031:
1.1172.2.66 raeburn 9032: # ----------------------------------------------------------- Content Blocking
9033:
9034: {
9035: # Caches for faster Course Contents display where content blocking
9036: # is in operation (i.e., interval param set) for timed quiz.
9037: #
9038: # User for whom data are being temporarily cached.
9039: my $cacheduser='';
1.1172.2.126 raeburn 9040: # Course for which data are being temporarily cached.
9041: my $cachedcid='';
1.1172.2.66 raeburn 9042: # Cached blockers for this user (a hash of blocking items).
9043: my %cachedblockers=();
9044: # When the data were last cached.
9045: my $cachedlast='';
9046:
9047: sub load_all_blockers {
1.1172.2.128 raeburn 9048: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 9049: if (($uname ne '') && ($udom ne '')) {
9050: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 9051: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 9052: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 9053: return;
9054: }
9055: }
9056: $cachedlast=time;
9057: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 9058: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 9059: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 9060: return;
1.1172.2.66 raeburn 9061: }
9062:
1.1162 raeburn 9063: sub get_comm_blocks {
9064: my ($cdom,$cnum) = @_;
9065: if ($cdom eq '' || $cnum eq '') {
9066: return unless ($env{'request.course.id'});
9067: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9068: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9069: }
9070: my %commblocks;
9071: my $hashid=$cdom.'_'.$cnum;
9072: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9073: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9074: %commblocks = %{$blocksref};
9075: } else {
9076: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
9077: my $cachetime = 600;
9078: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9079: }
9080: return %commblocks;
9081: }
9082:
1.1172.2.66 raeburn 9083: sub get_commblock_resources {
9084: my ($blocks) = @_;
9085: my %blockers = ();
9086: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 9087: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9088: if ($env{'request.course.sec'}) {
9089: $courseurl .= '/'.$env{'request.course.sec'};
9090: }
9091: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9092: my %commblocks;
9093: if (ref($blocks) eq 'HASH') {
9094: %commblocks = %{$blocks};
9095: } else {
9096: %commblocks = &get_comm_blocks();
9097: }
1.1172.2.66 raeburn 9098: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 9099: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 9100: return %blockers unless (ref($navmap));
9101: my $now = time;
1.1162 raeburn 9102: foreach my $block (keys(%commblocks)) {
9103: if ($block =~ /^(\d+)____(\d+)$/) {
9104: my ($start,$end) = ($1,$2);
9105: if ($start <= $now && $end >= $now) {
9106: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9107: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9108: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 9109: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9110: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9111: }
9112: }
9113: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 9114: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9115: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9116: }
9117: }
9118: }
9119: }
9120: }
9121: } elsif ($block =~ /^firstaccess____(.+)$/) {
9122: my $item = $1;
9123: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9124: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 9125: my (@interval,$mapname);
1.1172.2.66 raeburn 9126: my $type = 'map';
9127: if ($item eq 'course') {
9128: $type = 'course';
9129: @interval=&EXT("resource.0.interval");
9130: } else {
9131: if ($item =~ /___\d+___/) {
9132: $type = 'resource';
9133: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9134: } else {
1.1172.2.142 raeburn 9135: $mapname = &deversion($item);
9136: if (ref($navmap)) {
9137: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9138: @interval = ($timelimit,'map');
1.1162 raeburn 9139: }
9140: }
1.1172.2.66 raeburn 9141: }
1.1172.2.146. .1(raebu 9142:22): if ($interval[0] =~ /^(\d+)/) {
9143:22): my $timelimit = $1;
1.1172.2.66 raeburn 9144: my $first_access;
9145: if ($type eq 'resource') {
9146: $first_access=&get_first_access($interval[1],$item);
9147: } elsif ($type eq 'map') {
9148: $first_access=&get_first_access($interval[1],undef,$item);
9149: } else {
9150: $first_access=&get_first_access($interval[1]);
9151: }
9152: if ($first_access) {
1.1172.2.146. .1(raebu 9153:22): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 9154: if ($timesup > $now) {
9155: my $activeblock;
1.1172.2.142 raeburn 9156: if ($type eq 'resource') {
9157: if (ref($navmap)) {
9158: my $res = $navmap->getBySymb($item);
9159: if ($res->answerable()) {
9160: $activeblock = 1;
9161: }
9162: }
9163: } elsif ($type eq 'map') {
9164: my $mapsymb = &symbread($mapname,1);
9165: if (($mapsymb) && (ref($navmap))) {
9166: my $mapres = $navmap->getBySymb($mapsymb);
9167: if (ref($mapres)) {
9168: my $first = $mapres->map_start();
9169: my $finish = $mapres->map_finish();
9170: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9171: if (ref($it)) {
9172: my $res;
9173: while ($res = $it->next(undef,1)) {
9174: next unless (ref($res));
9175: my $symb = $res->symb();
9176: next if (($symb eq $mapsymb) || ($symb eq ''));
9177: @interval=&EXT("resource.0.interval",$symb);
9178: if ($interval[1] eq 'map') {
9179: if ($res->answerable()) {
9180: $activeblock = 1;
9181: last;
9182: }
9183: }
9184: }
9185: }
9186: }
1.1172.2.66 raeburn 9187: }
9188: }
9189: if ($activeblock) {
9190: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9191: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9192: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9193: }
9194: }
9195: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9196: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9197: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9198: }
1.1162 raeburn 9199: }
9200: }
9201: }
9202: }
9203: }
9204: }
9205: }
9206: }
9207: }
1.1172.2.66 raeburn 9208: return %blockers;
1.1162 raeburn 9209: }
9210:
1.1172.2.66 raeburn 9211: sub has_comm_blocking {
1.1172.2.128 raeburn 9212: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 9213: my @blockers;
9214: return unless ($env{'request.course.id'});
9215: return unless ($priv eq 'bre');
9216: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 9217: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9218: if ($env{'request.course.sec'}) {
9219: $courseurl .= '/'.$env{'request.course.sec'};
9220: }
9221: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 9222: my %blockinfo;
9223: if (ref($blocks) eq 'HASH') {
9224: %blockinfo = &get_commblock_resources($blocks);
9225: } else {
9226: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9227: %blockinfo = %cachedblockers;
9228: }
9229: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 9230: my (%possibles,@symbs);
9231: if (!$symb) {
1.1172.2.128 raeburn 9232: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9233: }
1.1172.2.66 raeburn 9234: if ($symb) {
9235: @symbs = ($symb);
9236: } elsif (keys(%possibles)) {
9237: @symbs = keys(%possibles);
9238: }
9239: my $noblock;
9240: foreach my $symb (@symbs) {
9241: last if ($noblock);
9242: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 9243: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 9244: if ($block =~ /^firstaccess____(.+)$/) {
9245: my $item = $1;
1.1172.2.126 raeburn 9246: unless ($blocked) {
9247: if (($item eq $map) || ($item eq $symb)) {
9248: $noblock = 1;
9249: last;
9250: }
1.1172.2.66 raeburn 9251: }
1.1162 raeburn 9252: }
1.1172.2.128 raeburn 9253: if (ref($blockinfo{$block}) eq 'HASH') {
9254: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9255: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 9256: unless (grep(/^\Q$block\E$/,@blockers)) {
9257: push(@blockers,$block);
9258: }
9259: }
9260: }
1.1172.2.128 raeburn 9261: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9262: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 9263: unless (grep(/^\Q$block\E$/,@blockers)) {
9264: push(@blockers,$block);
9265: }
1.1172.2.66 raeburn 9266: }
9267: }
1.1162 raeburn 9268: }
9269: }
9270: }
1.1172.2.126 raeburn 9271: unless ($noblock) {
9272: return @blockers;
9273: }
9274: return;
1.1172.2.66 raeburn 9275: }
1.1162 raeburn 9276: }
9277:
1.1172.2.146. .1(raebu 9278:22): sub deeplink_check {
9279:22): my ($priv,$symb,$uri) = @_;
9280:22): return unless ($env{'request.course.id'});
9281:22): return unless ($priv eq 'bre');
9282:22): return if ($env{'request.state'} eq 'construct');
9283:22): return if ($env{'request.role.adv'});
9284:22): my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9285:22): my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9286:22): my (%possibles,@symbs);
9287:22): if (!$symb) {
9288:22): $symb = &symbread($uri,1,1,1,\%possibles);
9289:22): }
9290:22): if ($symb) {
9291:22): @symbs = ($symb);
9292:22): } elsif (keys(%possibles)) {
9293:22): @symbs = keys(%possibles);
9294:22): }
9295:22):
9296:22): my ($deeplink_symb,$allow);
9297:22): if ($env{'request.deeplink.login'}) {
9298:22): $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
9299:22): }
9300:22): foreach my $symb (@symbs) {
9301:22): last if ($allow);
9302:22): my $deeplink = &EXT("resource.0.deeplink",$symb);
9303:22): if ($deeplink eq '') {
9304:22): $allow = 1;
9305:22): } else {
9306:22): my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9307:22): if ($state ne 'only') {
9308:22): $allow = 1;
9309:22): } else {
9310:22): my $check_deeplink_entry;
9311:22): if ($protect ne 'none') {
9312:22): my ($acctype,$item) = split(/:/,$protect);
9313:22): if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9314:22): if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9315:22): $check_deeplink_entry = 1
9316:22): }
9317:22): } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9318:22): if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9319:22): $check_deeplink_entry = 1;
9320:22): }
9321:22): } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9322:22): if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9323:22): $check_deeplink_entry = 1;
9324:22): }
9325:22): }
9326:22): }
9327:22): if (($protect eq 'none') || ($check_deeplink_entry)) {
9328:22): if ($scope eq 'res') {
9329:22): if ($symb eq $deeplink_symb) {
9330:22): $allow = 1;
9331:22): }
9332:22): } elsif (($scope eq 'map') || ($scope eq 'rec')) {
9333:22): my ($map_from_symb,$map_from_login);
9334:22): $map_from_symb = &deversion((&decode_symb($symb))[0]);
9335:22): if ($deeplink_symb =~ /\.(page|sequence)$/) {
9336:22): $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9337:22): } else {
9338:22): $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9339:22): }
9340:22): if (($map_from_symb) && ($map_from_login)) {
9341:22): if ($map_from_symb eq $map_from_login) {
9342:22): $allow = 1;
9343:22): } elsif ($scope eq 'rec') {
9344:22): my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9345:22): if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9346:22): $allow = 1;
9347:22): }
9348:22): }
9349:22): }
9350:22): }
9351:22): }
9352:22): }
9353:22): }
9354:22): }
9355:22): return if ($allow);
9356:22): return 1;
9357:22): }
9358:22):
1.1172.2.66 raeburn 9359: # -------------------------------- Deversion and split uri into path an filename
9360:
1.1133 foxr 9361: #
1.1172.2.66 raeburn 9362: # Removes the version from a URI and
1.1133 foxr 9363: # splits it in to its filename and path to the filename.
9364: # Seems like File::Basename could have done this more clearly.
9365: # Parameters:
9366: # $uri - input URI
9367: # Returns:
9368: # Two element list consisting of
9369: # $pathname - the URI up to and excluding the trailing /
9370: # $filename - The part of the URI following the last /
9371: # NOTE:
9372: # Another realization of this is simply:
9373: # use File::Basename;
9374: # ...
9375: # $uri = shift;
9376: # $filename = basename($uri);
9377: # $path = dirname($uri);
9378: # return ($filename, $path);
9379: #
9380: # The implementation below is probably faster however.
9381: #
1.710 albertel 9382: sub split_uri_for_cond {
9383: my $uri=&deversion(&declutter(shift));
9384: my @uriparts=split(/\//,$uri);
9385: my $filename=pop(@uriparts);
9386: my $pathname=join('/',@uriparts);
9387: return ($pathname,$filename);
9388: }
1.232 www 9389: # --------------------------------------------------- Is a resource on the map?
9390:
9391: sub is_on_map {
1.710 albertel 9392: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9393: #Trying to find the conditional for the file
1.620 albertel 9394: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9395: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9396: if ($match) {
1.289 bowersj2 9397: return (1,$1);
9398: } else {
1.434 www 9399: return (0,0);
1.289 bowersj2 9400: }
1.12 www 9401: }
9402:
1.427 www 9403: # --------------------------------------------------------- Get symb from alias
9404:
9405: sub get_symb_from_alias {
9406: my $symb=shift;
9407: my ($map,$resid,$url)=&decode_symb($symb);
9408: # Already is a symb
9409: if ($url) { return $symb; }
9410: # Must be an alias
9411: my $aliassymb='';
9412: my %bighash;
1.620 albertel 9413: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9414: &GDBM_READER(),0640)) {
9415: my $rid=$bighash{'mapalias_'.$symb};
9416: if ($rid) {
9417: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9418: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9419: $resid,$bighash{'src_'.$rid});
1.427 www 9420: }
9421: untie %bighash;
9422: }
9423: return $aliassymb;
9424: }
9425:
1.12 www 9426: # ----------------------------------------------------------------- Define Role
9427:
9428: sub definerole {
9429: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 9430: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9431: foreach my $role (split(':',$sysrole)) {
9432: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9433: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9434: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9435: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9436: return "refused:s:$crole&$cqual";
9437: }
9438: }
1.191 harris41 9439: }
1.800 albertel 9440: foreach my $role (split(':',$domrole)) {
9441: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9442: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9443: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9444: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9445: return "refused:d:$crole&$cqual";
9446: }
9447: }
1.191 harris41 9448: }
1.800 albertel 9449: foreach my $role (split(':',$courole)) {
9450: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9451: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9452: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9453: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9454: return "refused:c:$crole&$cqual";
9455: }
9456: }
1.191 harris41 9457: }
1.1172.2.84 raeburn 9458: my $uhome;
9459: if (($uname ne '') && ($udom ne '')) {
9460: $uhome = &homeserver($uname,$udom);
9461: return $uhome if ($uhome eq 'no_host');
9462: } else {
9463: $uname = $env{'user.name'};
9464: $udom = $env{'user.domain'};
9465: $uhome = $env{'user.home'};
9466: }
1.620 albertel 9467: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 9468: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9469: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 9470: return reply($command,$uhome);
1.12 www 9471: } else {
9472: return 'refused';
9473: }
1.105 harris41 9474: }
9475:
9476: # ---------------- Make a metadata query against the network of library servers
9477:
9478: sub metadata_query {
1.1172.2.33 raeburn 9479: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9480: my %rhash;
1.845 albertel 9481: my %libserv = &all_library();
1.244 matthew 9482: my @server_list = (defined($server_array) ? @$server_array
9483: : keys(%libserv) );
9484: for my $server (@server_list) {
1.1172.2.33 raeburn 9485: my $domains = '';
9486: if (ref($domains_hash) eq 'HASH') {
9487: $domains = $domains_hash->{$server};
9488: }
1.118 harris41 9489: unless ($custom or $customshow) {
1.1172.2.33 raeburn 9490: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9491: $rhash{$server}=$reply;
9492: }
9493: else {
9494: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 9495: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9496: $server);
9497: $rhash{$server}=$reply;
9498: }
1.112 harris41 9499: }
1.118 harris41 9500: return \%rhash;
1.240 www 9501: }
9502:
9503: # ----------------------------------------- Send log queries and wait for reply
9504:
9505: sub log_query {
9506: my ($uname,$udom,$query,%filters)=@_;
9507: my $uhome=&homeserver($uname,$udom);
9508: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9509: my $uhost=&hostname($uhome);
1.800 albertel 9510: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9511: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9512: $uhome);
1.479 albertel 9513: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9514: return get_query_reply($queryid);
9515: }
9516:
1.818 raeburn 9517: # -------------------------- Update MySQL table for portfolio file
9518:
9519: sub update_portfolio_table {
1.821 raeburn 9520: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9521: if ($group ne '') {
9522: $file_name =~s /^\Q$group\E//;
9523: }
1.818 raeburn 9524: my $homeserver = &homeserver($uname,$udom);
9525: my $queryid=
1.821 raeburn 9526: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9527: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9528: my $reply = &get_query_reply($queryid);
9529: return $reply;
9530: }
9531:
1.899 raeburn 9532: # -------------------------- Update MySQL allusers table
9533:
9534: sub update_allusers_table {
9535: my ($uname,$udom,$names) = @_;
9536: my $homeserver = &homeserver($uname,$udom);
9537: my $queryid=
9538: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9539: 'lastname='.&escape($names->{'lastname'}).'%%'.
9540: 'firstname='.&escape($names->{'firstname'}).'%%'.
9541: 'middlename='.&escape($names->{'middlename'}).'%%'.
9542: 'generation='.&escape($names->{'generation'}).'%%'.
9543: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9544: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9545: return;
1.899 raeburn 9546: }
9547:
1.508 raeburn 9548: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9549:
9550: sub fetch_enrollment_query {
1.511 raeburn 9551: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 9552: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9553: my $maxtries = 1;
1.508 raeburn 9554: if ($context eq 'automated') {
9555: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 9556: $sleep = 2;
9557: $loopmax = 100;
1.547 raeburn 9558: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9559: } else {
9560: $homeserver = &homeserver($cnum,$dom);
9561: }
1.838 albertel 9562: my $host=&hostname($homeserver);
1.506 raeburn 9563: my $cmd = '';
1.1000 raeburn 9564: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9565: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9566: }
9567: $cmd =~ s/%%$//;
9568: $cmd = &escape($cmd);
9569: my $query = 'fetchenrollment';
1.620 albertel 9570: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9571: unless ($queryid=~/^\Q$host\E\_/) {
9572: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9573: return 'error: '.$queryid;
9574: }
1.1172.2.93 raeburn 9575: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9576: my $tries = 1;
9577: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 9578: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9579: $tries ++;
9580: }
1.526 raeburn 9581: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9582: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9583: } else {
1.901 albertel 9584: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 9585: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9586: foreach my $line (@responses) {
9587: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9588: $$replyref{$key} = $value;
9589: }
9590: } else {
1.1117 foxr 9591: my $pathname = LONCAPA::tempdir();
1.800 albertel 9592: foreach my $line (@responses) {
9593: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9594: $$replyref{$key} = $value;
9595: if ($value > 0) {
1.800 albertel 9596: foreach my $item (@{$$affiliatesref{$key}}) {
9597: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9598: my $destname = $pathname.'/'.$filename;
9599: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9600: if ($xml_classlist =~ /^error/) {
9601: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9602: } else {
1.1172.2.96 raeburn 9603: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9604: print FILE &unescape($xml_classlist);
9605: close(FILE);
1.526 raeburn 9606: } else {
9607: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9608: }
9609: }
9610: }
9611: }
9612: }
9613: }
9614: return 'ok';
9615: }
9616: return 'error';
9617: }
9618:
1.242 www 9619: sub get_query_reply {
1.1172.2.79 raeburn 9620: my ($queryid,$sleep,$loopmax) = @_;
9621: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9622: $sleep = 0.2;
9623: }
9624: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9625: $loopmax = 100;
9626: }
1.1117 foxr 9627: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9628: my $reply='';
1.1172.2.79 raeburn 9629: for (1..$loopmax) {
9630: sleep($sleep);
1.240 www 9631: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9632: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9633: $reply = join('',<$fh>);
9634: close($fh);
1.240 www 9635: } else { return 'error: reply_file_error'; }
1.242 www 9636: return &unescape($reply);
9637: }
1.240 www 9638: }
1.242 www 9639: return 'timeout:'.$queryid;
1.240 www 9640: }
9641:
9642: sub courselog_query {
1.241 www 9643: #
9644: # possible filters:
9645: # url: url or symb
9646: # username
9647: # domain
9648: # action: view, submit, grade
9649: # start: timestamp
9650: # end: timestamp
9651: #
1.240 www 9652: my (%filters)=@_;
1.620 albertel 9653: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9654: if ($filters{'url'}) {
9655: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9656: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9657: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9658: }
1.620 albertel 9659: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9660: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9661: return &log_query($cname,$cdom,'courselog',%filters);
9662: }
9663:
9664: sub userlog_query {
1.858 raeburn 9665: #
9666: # possible filters:
9667: # action: log check role
9668: # start: timestamp
9669: # end: timestamp
9670: #
1.240 www 9671: my ($uname,$udom,%filters)=@_;
9672: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9673: }
9674:
1.506 raeburn 9675: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9676:
9677: sub auto_run {
1.508 raeburn 9678: my ($cnum,$cdom) = @_;
1.876 raeburn 9679: my $response = 0;
9680: my $settings;
9681: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9682: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9683: $settings = $domconfig{'autoenroll'};
9684: if ($settings->{'run'} eq '1') {
9685: $response = 1;
9686: }
9687: } else {
1.934 raeburn 9688: my $homeserver;
9689: if (&is_course($cdom,$cnum)) {
9690: $homeserver = &homeserver($cnum,$cdom);
9691: } else {
9692: $homeserver = &domain($cdom,'primary');
9693: }
9694: if ($homeserver ne 'no_host') {
9695: $response = &reply('autorun:'.$cdom,$homeserver);
9696: }
1.876 raeburn 9697: }
1.506 raeburn 9698: return $response;
9699: }
1.776 albertel 9700:
1.506 raeburn 9701: sub auto_get_sections {
1.508 raeburn 9702: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9703: my $homeserver;
9704: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9705: $homeserver = &homeserver($cnum,$cdom);
9706: }
9707: if (!defined($homeserver)) {
9708: if ($cdom =~ /^$match_domain$/) {
9709: $homeserver = &domain($cdom,'primary');
9710: }
9711: }
9712: my @secs;
9713: if (defined($homeserver)) {
9714: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9715: unless ($response eq 'refused') {
9716: @secs = split(/:/,$response);
9717: }
1.506 raeburn 9718: }
9719: return @secs;
9720: }
1.776 albertel 9721:
1.506 raeburn 9722: sub auto_new_course {
1.1099 raeburn 9723: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9724: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9725: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9726: return $response;
9727: }
1.776 albertel 9728:
1.506 raeburn 9729: sub auto_validate_courseID {
1.508 raeburn 9730: my ($cnum,$cdom,$inst_course_id) = @_;
9731: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9732: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9733: return $response;
9734: }
1.776 albertel 9735:
1.1007 raeburn 9736: sub auto_validate_instcode {
1.1020 raeburn 9737: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9738: my ($homeserver,$response);
9739: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9740: $homeserver = &homeserver($cnum,$cdom);
9741: }
9742: if (!defined($homeserver)) {
9743: if ($cdom =~ /^$match_domain$/) {
9744: $homeserver = &domain($cdom,'primary');
9745: }
9746: }
1.1065 raeburn 9747: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9748: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9749: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9750: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9751: }
9752:
1.1172.2.141 raeburn 9753: sub auto_validate_inst_crosslist {
9754: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9755: my ($homeserver,$response);
9756: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9757: $homeserver = &homeserver($cnum,$cdom);
9758: }
9759: if (!defined($homeserver)) {
9760: if ($cdom =~ /^$match_domain$/) {
9761: $homeserver = &domain($cdom,'primary');
9762: }
9763: }
9764: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9765: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9766: &escape($instcode).':'.&escape($inst_xlist).':'.
9767: &escape($coowner),$homeserver);
9768: }
9769: return $response;
9770: }
9771:
1.506 raeburn 9772: sub auto_create_password {
1.873 raeburn 9773: my ($cnum,$cdom,$authparam,$udom) = @_;
9774: my ($homeserver,$response);
1.506 raeburn 9775: my $create_passwd = 0;
9776: my $authchk = '';
1.873 raeburn 9777: if ($udom =~ /^$match_domain$/) {
9778: $homeserver = &domain($udom,'primary');
9779: }
9780: if ($homeserver eq '') {
9781: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9782: $homeserver = &homeserver($cnum,$cdom);
9783: }
9784: }
9785: if ($homeserver eq '') {
9786: $authchk = 'nodomain';
1.506 raeburn 9787: } else {
1.873 raeburn 9788: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9789: if ($response eq 'refused') {
9790: $authchk = 'refused';
9791: } else {
1.901 albertel 9792: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9793: }
1.506 raeburn 9794: }
9795: return ($authparam,$create_passwd,$authchk);
9796: }
9797:
1.706 raeburn 9798: sub auto_photo_permission {
9799: my ($cnum,$cdom,$students) = @_;
9800: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9801: my ($outcome,$perm_reqd,$conditions) =
9802: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9803: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9804: return (undef,undef);
9805: }
1.706 raeburn 9806: return ($outcome,$perm_reqd,$conditions);
9807: }
9808:
9809: sub auto_checkphotos {
9810: my ($uname,$udom,$pid) = @_;
9811: my $homeserver = &homeserver($uname,$udom);
9812: my ($result,$resulttype);
9813: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9814: &escape($uname).':'.&escape($pid),
9815: $homeserver));
1.709 albertel 9816: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9817: return (undef,undef);
9818: }
1.706 raeburn 9819: if ($outcome) {
9820: ($result,$resulttype) = split(/:/,$outcome);
9821: }
9822: return ($result,$resulttype);
9823: }
9824:
9825: sub auto_photochoice {
9826: my ($cnum,$cdom) = @_;
9827: my $homeserver = &homeserver($cnum,$cdom);
9828: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9829: &escape($cdom),
9830: $homeserver)));
1.709 albertel 9831: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9832: return (undef,undef);
9833: }
1.706 raeburn 9834: return ($update,$comment);
9835: }
9836:
9837: sub auto_photoupdate {
9838: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9839: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9840: my $host=&hostname($homeserver);
1.706 raeburn 9841: my $cmd = '';
9842: my $maxtries = 1;
1.800 albertel 9843: foreach my $affiliate (keys(%{$affiliatesref})) {
9844: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9845: }
9846: $cmd =~ s/%%$//;
9847: $cmd = &escape($cmd);
9848: my $query = 'institutionalphotos';
9849: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9850: unless ($queryid=~/^\Q$host\E\_/) {
9851: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9852: return 'error: '.$queryid;
9853: }
9854: my $reply = &get_query_reply($queryid);
9855: my $tries = 1;
9856: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9857: $reply = &get_query_reply($queryid);
9858: $tries ++;
9859: }
9860: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9861: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9862: } else {
9863: my @responses = split(/:/,$reply);
9864: my $outcome = shift(@responses);
9865: foreach my $item (@responses) {
9866: my ($key,$value) = split(/=/,$item);
9867: $$photo{$key} = $value;
9868: }
9869: return $outcome;
9870: }
9871: return 'error';
9872: }
9873:
1.521 raeburn 9874: sub auto_instcode_format {
1.793 albertel 9875: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9876: $cat_order) = @_;
1.521 raeburn 9877: my $courses = '';
1.772 raeburn 9878: my @homeservers;
1.521 raeburn 9879: if ($caller eq 'global') {
1.841 albertel 9880: my %servers = &get_servers($codedom,'library');
9881: foreach my $tryserver (keys(%servers)) {
9882: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9883: push(@homeservers,$tryserver);
9884: }
1.584 raeburn 9885: }
1.1022 raeburn 9886: } elsif ($caller eq 'requests') {
9887: if ($codedom =~ /^$match_domain$/) {
9888: my $chome = &domain($codedom,'primary');
9889: unless ($chome eq 'no_host') {
9890: push(@homeservers,$chome);
9891: }
9892: }
1.521 raeburn 9893: } else {
1.772 raeburn 9894: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9895: }
1.793 albertel 9896: foreach my $code (keys(%{$instcodes})) {
9897: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9898: }
9899: chop($courses);
1.772 raeburn 9900: my $ok_response = 0;
9901: my $response;
9902: while (@homeservers > 0 && $ok_response == 0) {
9903: my $server = shift(@homeservers);
9904: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9905: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9906: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9907: split(/:/,$response);
1.772 raeburn 9908: %{$codes} = (%{$codes},&str2hash($codes_str));
9909: push(@{$codetitles},&str2array($codetitles_str));
9910: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9911: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9912: $ok_response = 1;
9913: }
9914: }
9915: if ($ok_response) {
1.521 raeburn 9916: return 'ok';
1.772 raeburn 9917: } else {
9918: return $response;
1.521 raeburn 9919: }
9920: }
9921:
1.792 raeburn 9922: sub auto_instcode_defaults {
9923: my ($domain,$returnhash,$code_order) = @_;
9924: my @homeservers;
1.841 albertel 9925:
9926: my %servers = &get_servers($domain,'library');
9927: foreach my $tryserver (keys(%servers)) {
9928: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9929: push(@homeservers,$tryserver);
9930: }
1.792 raeburn 9931: }
1.841 albertel 9932:
1.792 raeburn 9933: my $response;
1.841 albertel 9934: foreach my $server (@homeservers) {
1.792 raeburn 9935: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9936: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9937:
9938: foreach my $pair (split(/\&/,$response)) {
9939: my ($name,$value)=split(/\=/,$pair);
9940: if ($name eq 'code_order') {
9941: @{$code_order} = split(/\&/,&unescape($value));
9942: } else {
9943: $returnhash->{&unescape($name)}=&unescape($value);
9944: }
9945: }
9946: return 'ok';
1.792 raeburn 9947: }
1.841 albertel 9948:
9949: return $response;
1.1003 raeburn 9950: }
9951:
9952: sub auto_possible_instcodes {
1.1007 raeburn 9953: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9954: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9955: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9956: return;
9957: }
1.1003 raeburn 9958: my (@homeservers,$uhome);
9959: if (defined(&domain($domain,'primary'))) {
9960: $uhome=&domain($domain,'primary');
9961: push(@homeservers,&domain($domain,'primary'));
9962: } else {
9963: my %servers = &get_servers($domain,'library');
9964: foreach my $tryserver (keys(%servers)) {
9965: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9966: push(@homeservers,$tryserver);
9967: }
9968: }
9969: }
9970: my $response;
9971: foreach my $server (@homeservers) {
9972: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9973: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9974: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9975: split(':',$response);
9976: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9977: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9978: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9979: my ($name,$value)=split('=',$item);
9980: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9981: }
9982: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9983: my ($name,$value)=split('=',$item);
9984: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9985: }
9986: return 'ok';
9987: }
9988: return $response;
9989: }
1.792 raeburn 9990:
1.1010 raeburn 9991: sub auto_courserequest_checks {
9992: my ($dom) = @_;
1.1020 raeburn 9993: my ($homeserver,%validations);
9994: if ($dom =~ /^$match_domain$/) {
9995: $homeserver = &domain($dom,'primary');
9996: }
9997: unless ($homeserver eq 'no_host') {
9998: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9999: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10000: my @items = split(/&/,$response);
10001: foreach my $item (@items) {
10002: my ($key,$value) = split('=',$item);
10003: $validations{&unescape($key)} = &thaw_unescape($value);
10004: }
10005: }
10006: }
1.1010 raeburn 10007: return %validations;
10008: }
10009:
1.1020 raeburn 10010: sub auto_courserequest_validation {
1.1172.2.43 raeburn 10011: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 10012: my ($homeserver,$response);
10013: if ($dom =~ /^$match_domain$/) {
10014: $homeserver = &domain($dom,'primary');
10015: }
1.1172.2.43 raeburn 10016: unless ($homeserver eq 'no_host') {
10017: my $customdata;
10018: if (ref($custominfo) eq 'HASH') {
10019: $customdata = &freeze_escape($custominfo);
10020: }
1.1020 raeburn 10021: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 10022: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 10023: ':'.&escape($instcode).':'.&escape($instseclist).':'.
10024: $customdata,$homeserver));
1.1020 raeburn 10025: }
10026: return $response;
10027: }
10028:
1.777 albertel 10029: sub auto_validate_class_sec {
1.918 raeburn 10030: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10031: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10032: my $ownerlist;
10033: if (ref($owners) eq 'ARRAY') {
10034: $ownerlist = join(',',@{$owners});
10035: } else {
10036: $ownerlist = $owners;
10037: }
1.773 raeburn 10038: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10039: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10040: return $response;
10041: }
10042:
1.1172.2.141 raeburn 10043: sub auto_instsec_reformat {
10044: my ($cdom,$action,$instsecref) = @_;
10045: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10046: my @homeservers;
10047: if (defined(&domain($cdom,'primary'))) {
10048: push(@homeservers,&domain($cdom,'primary'));
10049: } else {
10050: my %servers = &get_servers($cdom,'library');
10051: foreach my $tryserver (keys(%servers)) {
10052: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10053: push(@homeservers,$tryserver);
10054: }
10055: }
10056: }
10057: my $response;
10058: my %reformatted = %{$instsecref};
10059: foreach my $server (@homeservers) {
10060: if (ref($instsecref) eq 'HASH') {
10061: my $info = &freeze_escape($instsecref);
10062: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10063: $action.':'.$info,$server);
10064: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10065: my @items = split(/&/,$response);
10066: foreach my $item (@items) {
10067: my ($key,$value) = split(/=/,$item);
10068: $reformatted{&unescape($key)} = &thaw_unescape($value);
10069: }
10070: }
10071: }
10072: return %reformatted;
10073: }
10074:
1.1172.2.94 raeburn 10075: sub auto_validate_instclasses {
10076: my ($cdom,$cnum,$owners,$classesref) = @_;
10077: my ($homeserver,%validations);
10078: $homeserver = &homeserver($cnum,$cdom);
10079: unless ($homeserver eq 'no_host') {
10080: my $ownerlist;
10081: if (ref($owners) eq 'ARRAY') {
10082: $ownerlist = join(',',@{$owners});
10083: } else {
10084: $ownerlist = $owners;
10085: }
10086: if (ref($classesref) eq 'HASH') {
10087: my $classes = &freeze_escape($classesref);
10088: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10089: ':'.$cdom.':'.$classes,$homeserver);
10090: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10091: my @items = split(/&/,$response);
10092: foreach my $item (@items) {
10093: my ($key,$value) = split('=',$item);
10094: $validations{&unescape($key)} = &thaw_unescape($value);
10095: }
10096: }
10097: }
10098: }
10099: return %validations;
10100: }
10101:
1.1172.2.38 raeburn 10102: sub auto_crsreq_update {
10103: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 10104: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 10105: my ($homeserver,%crsreqresponse);
10106: if ($cdom =~ /^$match_domain$/) {
10107: $homeserver = &domain($cdom,'primary');
10108: }
10109: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10110: my $info;
10111: if (ref($inbound) eq 'HASH') {
10112: $info = &freeze_escape($inbound);
10113: }
10114: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10115: ':'.&escape($action).':'.&escape($ownername).':'.
10116: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 10117: &escape($title).':'.&escape($code).':'.
10118: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 10119: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10120: my @items = split(/&/,$response);
10121: foreach my $item (@items) {
10122: my ($key,$value) = split('=',$item);
10123: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10124: }
10125: }
10126: }
10127: return \%crsreqresponse;
10128: }
10129:
1.1172.2.78 raeburn 10130: sub auto_export_grades {
10131: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10132: my ($homeserver,%exportresponse);
10133: if ($cdom =~ /^$match_domain$/) {
10134: $homeserver = &domain($cdom,'primary');
10135: }
10136: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10137: my $info;
10138: if (ref($inforef) eq 'HASH') {
10139: $info = &freeze_escape($inforef);
10140: }
10141: if (ref($gradesref) eq 'HASH') {
10142: my $grades = &freeze_escape($gradesref);
10143: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10144: $info.':'.$grades,$homeserver);
10145: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10146: my @items = split(/&/,$response);
10147: foreach my $item (@items) {
10148: my ($key,$value) = split('=',$item);
10149: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10150: }
10151: }
10152: }
10153: }
10154: return \%exportresponse;
10155: }
10156:
1.1172.2.68 raeburn 10157: sub check_instcode_cloning {
10158: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10159: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10160: return;
10161: }
10162: my $canclone;
10163: if (@{$code_order} > 0) {
10164: my $instcoderegexp ='^';
10165: my @clonecodes = split(/\&/,$cloner);
10166: foreach my $item (@{$code_order}) {
10167: if (grep(/^\Q$item\E=/,@clonecodes)) {
10168: foreach my $pair (@clonecodes) {
10169: my ($key,$val) = split(/\=/,$pair,2);
10170: $val = &unescape($val);
10171: if ($key eq $item) {
10172: $instcoderegexp .= '('.$val.')';
10173: last;
10174: }
10175: }
10176: } else {
10177: $instcoderegexp .= $codedefaults->{$item};
10178: }
10179: }
10180: $instcoderegexp .= '$';
10181: my (@from,@to);
10182: eval {
10183: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10184: (@to) = ($clonetocode =~ /$instcoderegexp/);
10185: };
10186: if ((@from > 0) && (@to > 0)) {
10187: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10188: if (!@diffs) {
10189: $canclone = 1;
10190: }
10191: }
10192: }
10193: return $canclone;
10194: }
10195:
10196: sub default_instcode_cloning {
10197: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10198: my (%codedefaults,@code_order,$canclone);
10199: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10200: %codedefaults = %{$codedefaultsref};
10201: @code_order = @{$codeorderref};
10202: } elsif ($clonedom) {
10203: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10204: }
10205: if (($domdefclone) && (@code_order)) {
10206: my @clonecodes = split(/\+/,$domdefclone);
10207: my $instcoderegexp ='^';
10208: foreach my $item (@code_order) {
10209: if (grep(/^\Q$item\E$/,@clonecodes)) {
10210: $instcoderegexp .= '('.$codedefaults{$item}.')';
10211: } else {
10212: $instcoderegexp .= $codedefaults{$item};
10213: }
10214: }
10215: $instcoderegexp .= '$';
10216: my (@from,@to);
10217: eval {
10218: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10219: (@to) = ($clonetocode =~ /$instcoderegexp/);
10220: };
10221: if ((@from > 0) && (@to > 0)) {
10222: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10223: if (!@diffs) {
10224: $canclone = 1;
10225: }
10226: }
10227: }
10228: return $canclone;
10229: }
10230:
1.679 raeburn 10231: # ------------------------------------------------------- Course Group routines
10232:
10233: sub get_coursegroups {
1.809 raeburn 10234: my ($cdom,$cnum,$group,$namespace) = @_;
10235: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10236: }
10237:
1.679 raeburn 10238: sub modify_coursegroup {
10239: my ($cdom,$cnum,$groupsettings) = @_;
10240: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10241: }
10242:
1.809 raeburn 10243: sub toggle_coursegroup_status {
10244: my ($cdom,$cnum,$group,$action) = @_;
10245: my ($from_namespace,$to_namespace);
10246: if ($action eq 'delete') {
10247: $from_namespace = 'coursegroups';
10248: $to_namespace = 'deleted_groups';
10249: } else {
10250: $from_namespace = 'deleted_groups';
10251: $to_namespace = 'coursegroups';
10252: }
10253: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10254: if (my $tmp = &error(%curr_group)) {
10255: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10256: return ('read error',$tmp);
10257: } else {
10258: my %savedsettings = %curr_group;
1.809 raeburn 10259: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10260: my $deloutcome;
10261: if ($result eq 'ok') {
1.809 raeburn 10262: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10263: } else {
10264: return ('write error',$result);
10265: }
10266: if ($deloutcome eq 'ok') {
10267: return 'ok';
10268: } else {
10269: return ('delete error',$deloutcome);
10270: }
10271: }
10272: }
10273:
1.679 raeburn 10274: sub modify_group_roles {
1.957 raeburn 10275: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10276: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10277: my $role = 'gr/'.&escape($userprivs);
10278: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10279: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10280: if ($result eq 'ok') {
10281: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10282: }
1.679 raeburn 10283: return $result;
10284: }
10285:
10286: sub modify_coursegroup_membership {
10287: my ($cdom,$cnum,$membership) = @_;
10288: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10289: return $result;
10290: }
10291:
1.682 raeburn 10292: sub get_active_groups {
10293: my ($udom,$uname,$cdom,$cnum) = @_;
10294: my $now = time;
10295: my %groups = ();
10296: foreach my $key (keys(%env)) {
1.811 albertel 10297: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10298: my ($start,$end) = split(/\./,$env{$key});
10299: if (($end!=0) && ($end<$now)) { next; }
10300: if (($start!=0) && ($start>$now)) { next; }
10301: if ($1 eq $cdom && $2 eq $cnum) {
10302: $groups{$3} = $env{$key} ;
10303: }
10304: }
10305: }
10306: return %groups;
10307: }
10308:
1.683 raeburn 10309: sub get_group_membership {
10310: my ($cdom,$cnum,$group) = @_;
10311: return(&dump('groupmembership',$cdom,$cnum,$group));
10312: }
10313:
10314: sub get_users_groups {
10315: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10316: my @usersgroups;
1.683 raeburn 10317: my $cachetime=1800;
10318:
10319: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10320: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10321: if (defined($cached)) {
1.734 albertel 10322: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10323: } else {
10324: $grouplist = '';
1.816 raeburn 10325: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10326: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10327: my $access_end = $env{'course.'.$courseid.
10328: '.default_enrollment_end_date'};
10329: my $now = time;
10330: foreach my $key (keys(%roleshash)) {
10331: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10332: my $group = $1;
10333: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10334: my $start = $2;
10335: my $end = $1;
10336: if ($start == -1) { next; } # deleted from group
10337: if (($start!=0) && ($start>$now)) { next; }
10338: if (($end!=0) && ($end<$now)) {
10339: if ($access_end && $access_end < $now) {
10340: if ($access_end - $end < 86400) {
10341: push(@usersgroups,$group);
1.733 raeburn 10342: }
10343: }
1.817 raeburn 10344: next;
1.733 raeburn 10345: }
1.817 raeburn 10346: push(@usersgroups,$group);
1.683 raeburn 10347: }
10348: }
10349: }
1.817 raeburn 10350: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10351: $grouplist = join(':',@usersgroups);
10352: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10353: }
1.733 raeburn 10354: return @usersgroups;
1.683 raeburn 10355: }
10356:
10357: sub devalidate_getgroups_cache {
10358: my ($udom,$uname,$cdom,$cnum)=@_;
10359: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10360:
1.683 raeburn 10361: my $hashid="$udom:$uname:$courseid";
10362: &devalidate_cache_new('getgroups',$hashid);
10363: }
10364:
1.12 www 10365: # ------------------------------------------------------------------ Plain Text
10366:
10367: sub plaintext {
1.988 raeburn 10368: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10369: if ($short =~ m{^cr/}) {
1.758 albertel 10370: return (split('/',$short))[-1];
10371: }
1.742 raeburn 10372: if (!defined($cid)) {
10373: $cid = $env{'request.course.id'};
10374: }
10375: my %rolenames = (
1.1008 raeburn 10376: Course => 'std',
10377: Community => 'alt1',
1.742 raeburn 10378: );
1.1037 raeburn 10379: if ($cid ne '') {
10380: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10381: unless ($forcedefault) {
10382: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10383: &Apache::lonlocal::mt_escape(\$roletext);
10384: return &Apache::lonlocal::mt($roletext);
10385: }
10386: }
10387: }
10388: if ((defined($type)) && (defined($rolenames{$type})) &&
10389: (defined($rolenames{$type})) &&
10390: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10391: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10392: } elsif ($cid ne '') {
10393: my $crstype = $env{'course.'.$cid.'.type'};
10394: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10395: (defined($prp{$short}{$rolenames{$crstype}}))) {
10396: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10397: }
1.742 raeburn 10398: }
1.1037 raeburn 10399: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10400: }
10401:
10402: # ----------------------------------------------------------------- Assign Role
10403:
10404: sub assignrole {
1.957 raeburn 10405: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10406: $context)=@_;
1.1172.2.146. .22(raeb 10407:-24): my ($mrole,$rolelogcontext);
1.21 www 10408: if ($role =~ /^cr\//) {
1.393 www 10409: my $cwosec=$url;
1.811 albertel 10410: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10411: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10412: my $refused = 1;
10413: if ($context eq 'requestcourses') {
10414: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10415: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10416: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10417: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10418: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10419: if ($crsenv{'internal.courseowner'} eq
10420: $env{'user.name'}.':'.$env{'user.domain'}) {
10421: $refused = '';
10422: }
10423: }
10424: }
10425: }
10426: }
10427: if ($refused) {
10428: &logthis('Refused custom assignrole: '.
10429: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10430: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10431: return 'refused';
10432: }
1.104 www 10433: }
1.21 www 10434: $mrole='cr';
1.678 raeburn 10435: } elsif ($role =~ /^gr\//) {
10436: my $cwogrp=$url;
1.811 albertel 10437: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10438: unless (&allowed('mdg',$cwogrp)) {
10439: &logthis('Refused group assignrole: '.
10440: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10441: $env{'user.name'}.' at '.$env{'user.domain'});
10442: return 'refused';
10443: }
10444: $mrole='gr';
1.21 www 10445: } else {
1.82 www 10446: my $cwosec=$url;
1.811 albertel 10447: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10448: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10449: my $refused;
10450: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10451: if (!(&allowed('c'.$role,$url))) {
10452: $refused = 1;
10453: }
10454: } else {
10455: $refused = 1;
10456: }
1.947 raeburn 10457: if ($refused) {
1.1045 raeburn 10458: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10459: if (!$selfenroll && $context eq 'course') {
10460: my %crsenv;
10461: if ($role eq 'cc' || $role eq 'co') {
10462: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10463: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10464: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10465: if ($crsenv{'internal.courseowner'} eq
10466: $env{'user.name'}.':'.$env{'user.domain'}) {
10467: $refused = '';
10468: }
10469: }
10470: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10471: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10472: if ($crsenv{'internal.courseowner'} eq
10473: $env{'user.name'}.':'.$env{'user.domain'}) {
10474: $refused = '';
10475: }
10476: }
10477: }
10478: }
1.1172.2.146. .13(raeb 10479:-23): } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10480:-23): if ($role eq 'st') {
10481:-23): $refused = '';
10482:-23): } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10483:-23): $refused = '';
10484:-23): }
1.1017 raeburn 10485: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10486: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10487: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10488: my $wrongcc;
10489: if ($cnum =~ /^$match_community$/) {
10490: $wrongcc = 1 if ($role eq 'cc');
10491: } else {
10492: $wrongcc = 1 if ($role eq 'co');
10493: }
10494: unless ($wrongcc) {
10495: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10496: if ($crsenv{'internal.courseowner'} eq
10497: $env{'user.name'}.':'.$env{'user.domain'}) {
10498: $refused = '';
10499: }
1.1017 raeburn 10500: }
10501: }
1.1172.2.9 raeburn 10502: } elsif ($context eq 'requestauthor') {
10503: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10504: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10505: if ($env{'environment.requestauthor'} eq 'automatic') {
10506: $refused = '';
10507: } else {
10508: my %domdefaults = &get_domain_defaults($udom);
10509: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10510: my $checkbystatus;
10511: if ($env{'user.adv'}) {
10512: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10513: if ($disposition eq 'automatic') {
10514: $refused = '';
10515: } elsif ($disposition eq '') {
10516: $checkbystatus = 1;
10517: }
10518: } else {
10519: $checkbystatus = 1;
10520: }
10521: if ($checkbystatus) {
10522: if ($env{'environment.inststatus'}) {
10523: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10524: foreach my $type (@inststatuses) {
10525: if (($type ne '') &&
10526: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10527: $refused = '';
10528: }
10529: }
10530: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10531: $refused = '';
10532: }
10533: }
10534: }
10535: }
10536: }
1.1172.2.146. .22(raeb 10537:-24): } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10538:-24): if ($url =~ m{^/($match_domain)/($match_username)$}) {
10539:-24): my ($audom,$auname) = ($1,$2);
10540:-24): if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10541:-24): ($env{"environment.internal.manager.$url"})) {
10542:-24): $refused = '';
10543:-24): $rolelogcontext = 'coauthor';
10544:-24): }
10545:-24): }
1.1017 raeburn 10546: }
10547: if ($refused) {
1.947 raeburn 10548: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10549: ' '.$role.' '.$end.' '.$start.' by '.
10550: $env{'user.name'}.' at '.$env{'user.domain'});
10551: return 'refused';
10552: }
1.932 raeburn 10553: }
1.1131 raeburn 10554: } elsif ($role eq 'au') {
10555: if ($url ne '/'.$udom.'/') {
10556: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10557: ' to assign author role for '.$uname.':'.$udom.
10558: ' in domain: '.$url.' refused (wrong domain).');
10559: return 'refused';
10560: }
1.104 www 10561: }
1.21 www 10562: $mrole=$role;
10563: }
1.620 albertel 10564: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10565: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10566: if ($end) { $command.='_'.$end; }
1.21 www 10567: if ($start) {
10568: if ($end) {
1.81 www 10569: $command.='_'.$start;
1.21 www 10570: } else {
1.81 www 10571: $command.='_0_'.$start;
1.21 www 10572: }
10573: }
1.739 raeburn 10574: my $origstart = $start;
10575: my $origend = $end;
1.957 raeburn 10576: my $delflag;
1.357 www 10577: # actually delete
10578: if ($deleteflag) {
1.373 www 10579: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10580: # modify command to delete the role
1.620 albertel 10581: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10582: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10583: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10584: # set start and finish to negative values for userrolelog
10585: $start=-1;
10586: $end=-1;
1.957 raeburn 10587: $delflag = 1;
1.357 www 10588: }
10589: }
10590: # send command
1.349 www 10591: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10592: # log new user role if status is ok
1.349 www 10593: if ($answer eq 'ok') {
1.663 raeburn 10594: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 10595: if (($role eq 'cc') || ($role eq 'in') ||
10596: ($role eq 'ep') || ($role eq 'ad') ||
10597: ($role eq 'ta') || ($role eq 'st') ||
10598: ($role=~/^cr/) || ($role eq 'gr') ||
10599: ($role eq 'co')) {
1.1172.2.13 raeburn 10600: # for course roles, perform group memberships changes triggered by role change.
10601: unless ($role =~ /^gr/) {
10602: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10603: $origstart,$selfenroll,$context);
10604: }
1.1172.2.9 raeburn 10605: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10606: $selfenroll,$context);
10607: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10608: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10609: ($role eq 'da')) {
1.1172.2.9 raeburn 10610: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10611: $context);
10612: } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1172.2.146. .22(raeb 10613:-24): if ($rolelogcontext eq '') {
10614:-24): $rolelogcontext = $context;
10615:-24): }
1.1172.2.9 raeburn 10616: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1172.2.146. .22(raeb 10617:-24): $rolelogcontext);
1.1172.2.9 raeburn 10618: }
1.1053 raeburn 10619: if ($role eq 'cc') {
10620: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10621: }
1.349 www 10622: }
10623: return $answer;
1.169 harris41 10624: }
10625:
1.1053 raeburn 10626: sub autoupdate_coowners {
10627: my ($url,$end,$start,$uname,$udom) = @_;
10628: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10629: if (($cdom ne '') && ($cnum ne '')) {
10630: my $now = time;
10631: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10632: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10633: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10634: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10635: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10636: if ($instcode ne '') {
1.1056 raeburn 10637: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10638: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10639: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10640: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10641: unless ($result eq 'valid') {
10642: if ($xlists ne '') {
10643: foreach my $xlist (split(',',$xlists)) {
10644: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10645: $result =
10646: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10647: $inst_crosslist,$uname.':'.$udom);
10648: last if ($result eq 'valid');
10649: }
10650: }
10651: }
1.1056 raeburn 10652: if ($result eq 'valid') {
10653: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10654: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10655: push(@newcoowners,$coowner);
10656: }
10657: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10658: push(@newcoowners,$uname.':'.$udom);
10659: }
10660: @newcoowners = sort(@newcoowners);
10661: } else {
10662: push(@newcoowners,$uname.':'.$udom);
10663: }
1.1172.2.141 raeburn 10664: } elsif ($coursehash{'internal.co-owners'}) {
10665: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10666: unless ($coowner eq $uname.':'.$udom) {
10667: push(@newcoowners,$coowner);
1.1053 raeburn 10668: }
10669: }
1.1172.2.141 raeburn 10670: unless (@newcoowners > 0) {
10671: $delcoowners = 1;
10672: $coowners = '';
10673: }
1.1053 raeburn 10674: }
10675: if (@newcoowners || $delcoowners) {
10676: &store_coowners($cdom,$cnum,$coursehash{'home'},
10677: $delcoowners,@newcoowners);
10678: }
10679: }
10680: }
10681: }
10682: }
10683: }
10684: }
10685:
10686: sub store_coowners {
10687: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10688: my $cid = $cdom.'_'.$cnum;
10689: my ($coowners,$delresult,$putresult);
10690: if (@newcoowners) {
10691: $coowners = join(',',@newcoowners);
10692: my %coownershash = (
10693: 'internal.co-owners' => $coowners,
10694: );
10695: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10696: if ($putresult eq 'ok') {
10697: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10698: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10699: }
10700: }
10701: }
10702: if ($delcoowners) {
10703: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10704: if ($delresult eq 'ok') {
10705: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10706: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10707: }
10708: }
10709: }
10710: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10711: my %crsinfo =
10712: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10713: if (ref($crsinfo{$cid}) eq 'HASH') {
10714: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10715: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10716: }
10717: }
10718: }
10719:
1.169 harris41 10720: # -------------------------------------------------- Modify user authentication
1.197 www 10721: # Overrides without validation
10722:
1.169 harris41 10723: sub modifyuserauth {
10724: my ($udom,$uname,$umode,$upass)=@_;
10725: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10726: my $allowed;
10727: if (&allowed('mau',$udom)) {
10728: $allowed = 1;
10729: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10730: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10731: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10732: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10733: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10734: if (($cdom ne '') && ($cnum ne '')) {
10735: my $is_owner = &is_course_owner($cdom,$cnum);
10736: if ($is_owner) {
10737: $allowed = 1;
10738: }
10739: }
10740: }
10741: unless ($allowed) { return 'refused'; }
1.197 www 10742: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10743: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10744: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10745: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10746: &escape($upass),$uhome);
1.1172.2.134 raeburn 10747: my $ip = &get_requestor_ip();
1.620 albertel 10748: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10749: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10750: '(Remote '.$ip.'): '.$reply);
1.197 www 10751: &log($udom,,$uname,$uhome,
1.620 albertel 10752: 'Authentication changed by '.$env{'user.domain'}.', '.
10753: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10754: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10755: unless ($reply eq 'ok') {
1.197 www 10756: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10757: return 'error: '.$reply;
10758: }
1.170 harris41 10759: return 'ok';
1.80 www 10760: }
10761:
1.81 www 10762: # --------------------------------------------------------------- Modify a user
1.80 www 10763:
1.81 www 10764: sub modifyuser {
1.206 matthew 10765: my ($udom, $uname, $uid,
10766: $umode, $upass, $first,
10767: $middle, $last, $gene,
1.1058 raeburn 10768: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10769: $udom= &LONCAPA::clean_domain($udom);
10770: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10771: my $showcandelete = 'none';
10772: if (ref($candelete) eq 'ARRAY') {
10773: if (@{$candelete} > 0) {
10774: $showcandelete = join(', ',@{$candelete});
10775: }
10776: }
1.81 www 10777: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10778: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10779: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10780: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10781: ' desiredhome not specified').
1.620 albertel 10782: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10783: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10784: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10785: my $newuser;
10786: if ($uhome eq 'no_host') {
10787: $newuser = 1;
1.1172.2.146. .13(raeb 10788:-23): unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10789:-23): ($umode eq 'lti')) {
10790:-23): return 'error: more information needed to create new user';
10791:-23): }
1.1075 raeburn 10792: }
1.80 www 10793: # ----------------------------------------------------------------- Create User
1.406 albertel 10794: if (($uhome eq 'no_host') &&
1.1172.2.146. .13(raeb 10795:-23): (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10796: my $unhome='';
1.844 albertel 10797: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10798: $unhome = $desiredhome;
1.620 albertel 10799: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10800: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10801: } else { # load balancing routine for determining $unhome
1.81 www 10802: my $loadm=10000000;
1.841 albertel 10803: my %servers = &get_servers($udom,'library');
10804: foreach my $tryserver (keys(%servers)) {
10805: my $answer=reply('load',$tryserver);
10806: if (($answer=~/\d+/) && ($answer<$loadm)) {
10807: $loadm=$answer;
10808: $unhome=$tryserver;
10809: }
1.80 www 10810: }
10811: }
10812: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10813: return 'error: unable to find a home server for '.$uname.
10814: ' in domain '.$udom;
1.80 www 10815: }
10816: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10817: &escape($upass),$unhome);
10818: unless ($reply eq 'ok') {
10819: return 'error: '.$reply;
10820: }
1.230 stredwic 10821: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10822: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10823: return 'error: unable verify users home machine.';
1.80 www 10824: }
1.209 matthew 10825: } # End of creation of new user
1.80 www 10826: # ---------------------------------------------------------------------- Add ID
10827: if ($uid) {
10828: $uid=~tr/A-Z/a-z/;
10829: my %uidhash=&idrget($udom,$uname);
1.196 www 10830: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10831: && (!$forceid)) {
1.80 www 10832: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10833: return 'error: user id "'.$uid.'" does not match '.
10834: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10835: }
10836: } else {
10837: &idput($udom,($uname => $uid));
10838: }
10839: }
10840: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10841: my @tmp=&get('environment',
1.899 raeburn 10842: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10843: 'permanentemail','inststatus'],
1.134 albertel 10844: $udom,$uname);
1.1075 raeburn 10845: my (%names,%oldnames);
1.313 matthew 10846: if ($tmp[0] =~ m/^error:.*/) {
10847: %names=();
10848: } else {
10849: %names = @tmp;
1.1075 raeburn 10850: %oldnames = %names;
1.313 matthew 10851: }
1.388 www 10852: #
1.1058 raeburn 10853: # If name, email and/or uid are blank (e.g., because an uploaded file
10854: # of users did not contain them), do not overwrite existing values
10855: # unless field is in $candelete array ref.
10856: #
10857:
10858: my @fields = ('firstname','middlename','lastname','generation',
10859: 'permanentemail','id');
10860: my %newvalues;
10861: if (ref($candelete) eq 'ARRAY') {
10862: foreach my $field (@fields) {
10863: if (grep(/^\Q$field\E$/,@{$candelete})) {
10864: if ($field eq 'firstname') {
10865: $names{$field} = $first;
10866: } elsif ($field eq 'middlename') {
10867: $names{$field} = $middle;
10868: } elsif ($field eq 'lastname') {
10869: $names{$field} = $last;
10870: } elsif ($field eq 'generation') {
10871: $names{$field} = $gene;
10872: } elsif ($field eq 'permanentemail') {
10873: $names{$field} = $email;
10874: } elsif ($field eq 'id') {
10875: $names{$field} = $uid;
10876: }
10877: }
10878: }
10879: }
1.388 www 10880: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10881: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10882: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10883: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10884: if ($email) {
10885: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10886: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10887: }
1.899 raeburn 10888: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10889: if (defined($inststatus)) {
10890: $names{'inststatus'} = '';
10891: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10892: if (ref($usertypes) eq 'HASH') {
10893: my @okstatuses;
10894: foreach my $item (split(/:/,$inststatus)) {
10895: if (defined($usertypes->{$item})) {
10896: push(@okstatuses,$item);
10897: }
10898: }
10899: if (@okstatuses) {
10900: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10901: }
10902: }
10903: }
1.1075 raeburn 10904: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10905: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10906: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10907: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10908: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10909: } else {
10910: $logmsg .= ' during self creation';
10911: }
1.1075 raeburn 10912: my $changed;
10913: if ($newuser) {
10914: $changed = 1;
10915: } else {
10916: foreach my $field (@fields) {
10917: if ($names{$field} ne $oldnames{$field}) {
10918: $changed = 1;
10919: last;
10920: }
10921: }
10922: }
10923: unless ($changed) {
10924: $logmsg = 'No changes in user information needed for: '.$logmsg;
10925: &logthis($logmsg);
10926: return 'ok';
10927: }
10928: my $reply = &put('environment', \%names, $udom,$uname);
10929: if ($reply ne 'ok') {
10930: return 'error: '.$reply;
10931: }
1.1087 raeburn 10932: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10933: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10934: }
1.1075 raeburn 10935: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10936: &devalidate_cache_new('namescache',$uname.':'.$udom);
10937: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10938: &logthis($logmsg);
1.134 albertel 10939: return 'ok';
1.80 www 10940: }
10941:
1.81 www 10942: # -------------------------------------------------------------- Modify student
1.80 www 10943:
1.81 www 10944: sub modifystudent {
10945: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10946: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10947: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10948: if (!$cid) {
1.620 albertel 10949: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10950: return 'not_in_class';
10951: }
1.80 www 10952: }
10953: # --------------------------------------------------------------- Make the user
1.81 www 10954: my $reply=&modifyuser
1.209 matthew 10955: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10956: $desiredhome,$email,$inststatus);
1.80 www 10957: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10958: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10959: # student's environment
1.297 matthew 10960: $uid = undef if (!$forceid);
1.455 albertel 10961: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10962: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10963: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10964: return $reply;
10965: }
10966:
10967: sub modify_student_enrollment {
1.1172.2.23 raeburn 10968: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10969: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10970: my ($cdom,$cnum,$chome);
10971: if (!$cid) {
1.620 albertel 10972: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10973: return 'not_in_class';
10974: }
1.620 albertel 10975: $cdom=$env{'course.'.$cid.'.domain'};
10976: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10977: } else {
10978: ($cdom,$cnum)=split(/_/,$cid);
10979: }
1.620 albertel 10980: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10981: if (!$chome) {
1.457 raeburn 10982: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10983: }
1.455 albertel 10984: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10985: # Make sure the user exists
1.81 www 10986: my $uhome=&homeserver($uname,$udom);
10987: if (($uhome eq '') || ($uhome eq 'no_host')) {
10988: return 'error: no such user';
10989: }
1.297 matthew 10990: # Get student data if we were not given enough information
10991: if (!defined($first) || $first eq '' ||
10992: !defined($last) || $last eq '' ||
10993: !defined($uid) || $uid eq '' ||
10994: !defined($middle) || $middle eq '' ||
10995: !defined($gene) || $gene eq '') {
1.294 matthew 10996: # They did not supply us with enough data to enroll the student, so
10997: # we need to pick up more information.
1.297 matthew 10998: my %tmp = &get('environment',
1.294 matthew 10999: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 11000: ,$udom,$uname);
11001:
1.800 albertel 11002: #foreach my $key (keys(%tmp)) {
11003: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 11004: #}
1.294 matthew 11005: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
11006: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11007: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 11008: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 11009: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
11010: }
1.556 albertel 11011: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 11012: my $user = "$uname:$udom";
11013: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 11014: my $reply=cput('classlist',
1.1148 raeburn 11015: {$user =>
1.1172.2.76 raeburn 11016: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 11017: $cdom,$cnum);
1.1148 raeburn 11018: if (($reply eq 'ok') || ($reply eq 'delayed')) {
11019: &devalidate_getsection_cache($udom,$uname,$cid);
11020: } else {
1.81 www 11021: return 'error: '.$reply;
11022: }
1.297 matthew 11023: # Add student role to user
1.83 www 11024: my $uurl='/'.$cid;
1.81 www 11025: $uurl=~s/\_/\//g;
11026: if ($usec) {
11027: $uurl.='/'.$usec;
11028: }
1.1148 raeburn 11029: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11030: $selfenroll,$context);
11031: if ($result ne 'ok') {
11032: if ($old_entry{$user} ne '') {
11033: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11034: } else {
11035: $reply = &del('classlist',[$user],$cdom,$cnum);
11036: }
11037: }
11038: return $result;
1.21 www 11039: }
11040:
1.556 albertel 11041: sub format_name {
11042: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11043: my $name;
11044: if ($first ne 'lastname') {
11045: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11046: } else {
11047: if ($lastname=~/\S/) {
11048: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11049: $name=~s/\s+,/,/;
11050: } else {
11051: $name.= $firstname.' '.$middlename.' '.$generation;
11052: }
11053: }
11054: $name=~s/^\s+//;
11055: $name=~s/\s+$//;
11056: $name=~s/\s+/ /g;
11057: return $name;
11058: }
11059:
1.84 www 11060: # ------------------------------------------------- Write to course preferences
11061:
11062: sub writecoursepref {
11063: my ($courseid,%prefs)=@_;
11064: $courseid=~s/^\///;
11065: $courseid=~s/\_/\//g;
11066: my ($cdomain,$cnum)=split(/\//,$courseid);
11067: my $chome=homeserver($cnum,$cdomain);
11068: if (($chome eq '') || ($chome eq 'no_host')) {
11069: return 'error: no such course';
11070: }
11071: my $cstring='';
1.800 albertel 11072: foreach my $pref (keys(%prefs)) {
11073: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11074: }
1.84 www 11075: $cstring=~s/\&$//;
11076: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11077: }
11078:
11079: # ---------------------------------------------------------- Make/modify course
11080:
11081: sub createcourse {
1.741 raeburn 11082: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146. .1(raebu 11083:22): $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11084: $url=&declutter($url);
11085: my $cid='';
1.1028 raeburn 11086: if ($context eq 'requestcourses') {
11087: my $can_create = 0;
11088: my ($ownername,$ownerdom) = split(':',$course_owner);
11089: if ($udom eq $ownerdom) {
1.1172.2.146. .1(raebu 11090:22): my $reload;
11091:22): if (($callercontext eq 'auto') &&
11092:22): ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11093:22): $reload = 'reload';
11094:22): }
11095:22): if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11096: $context)) {
11097: $can_create = 1;
11098: }
11099: } else {
11100: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11101: $category);
11102: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11103: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11104: if (@curr > 0) {
11105: my @options = qw(approval validate autolimit);
11106: my $optregex = join('|',@options);
11107: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11108: $can_create = 1;
11109: }
11110: }
11111: }
11112: }
11113: if ($can_create) {
11114: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11115: unless (&allowed('ccc',$udom)) {
11116: return 'refused';
11117: }
1.1017 raeburn 11118: }
11119: } else {
11120: return 'refused';
11121: }
1.1028 raeburn 11122: } elsif (!&allowed('ccc',$udom)) {
11123: return 'refused';
1.84 www 11124: }
1.1011 raeburn 11125: # --------------------------------------------------------------- Get Unique ID
11126: my $uname;
11127: if ($cnum =~ /^$match_courseid$/) {
11128: my $chome=&homeserver($cnum,$udom,'true');
11129: if (($chome eq '') || ($chome eq 'no_host')) {
11130: $uname = $cnum;
11131: } else {
1.1038 raeburn 11132: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11133: }
11134: } else {
1.1038 raeburn 11135: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11136: }
11137: return $uname if ($uname =~ /^error/);
11138: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11139: if (!defined($course_server)) {
11140: if (defined(&domain($udom,'primary'))) {
11141: $course_server = &domain($udom,'primary');
11142: } else {
11143: $course_server = $env{'user.home'};
11144: }
11145: }
11146: my %host_servers =
11147: &Apache::lonnet::get_servers($udom,'library');
11148: unless ($host_servers{$course_server}) {
11149: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11150: }
1.84 www 11151: # ------------------------------------------------------------- Make the course
11152: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11153: $course_server);
1.84 www 11154: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11155: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11156: if (($uhome eq '') || ($uhome eq 'no_host')) {
11157: return 'error: no such course';
11158: }
1.271 www 11159: # ----------------------------------------------------------------- Course made
1.516 raeburn 11160: # log existence
1.1029 raeburn 11161: my $now = time;
1.918 raeburn 11162: my $newcourse = {
11163: $udom.'_'.$uname => {
1.921 raeburn 11164: description => $description,
11165: inst_code => $inst_code,
11166: owner => $course_owner,
11167: type => $crstype,
1.1029 raeburn 11168: creator => $env{'user.name'}.':'.
11169: $env{'user.domain'},
11170: created => $now,
11171: context => $context,
1.918 raeburn 11172: },
11173: };
1.921 raeburn 11174: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11175: # set toplevel url
1.271 www 11176: my $topurl=$url;
11177: unless ($nonstandard) {
11178: # ------------------------------------------ For standard courses, make top url
11179: my $mapurl=&clutter($url);
1.278 www 11180: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11181: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11182: <map>
11183: <resource id="1" type="start"></resource>
11184: <resource id="2" src="$mapurl"></resource>
11185: <resource id="3" type="finish"></resource>
11186: <link index="1" from="1" to="2"></link>
11187: <link index="2" from="2" to="3"></link>
11188: </map>
11189: ENDINITMAP
11190: $topurl=&declutter(
1.638 albertel 11191: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11192: );
11193: }
11194: # ----------------------------------------------------------- Write preferences
1.84 www 11195: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11196: ('description' => $description,
11197: 'url' => $topurl,
11198: 'internal.creator' => $env{'user.name'}.':'.
11199: $env{'user.domain'},
11200: 'internal.created' => $now,
11201: 'internal.creationcontext' => $context)
11202: );
1.84 www 11203: return '/'.$udom.'/'.$uname;
11204: }
11205:
1.1011 raeburn 11206: # ------------------------------------------------------------------- Create ID
11207: sub generate_coursenum {
1.1038 raeburn 11208: my ($udom,$crstype) = @_;
1.1011 raeburn 11209: my $domdesc = &domain($udom);
11210: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11211: my $first;
11212: if ($crstype eq 'Community') {
11213: $first = '0';
11214: } else {
11215: $first = int(1+rand(9));
11216: }
11217: my $uname=$first.
1.1011 raeburn 11218: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11219: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11220: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11221: # ----------------------------------------------- Make sure that does not exist
11222: my $uhome=&homeserver($uname,$udom,'true');
11223: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11224: if ($crstype eq 'Community') {
11225: $first = '0';
11226: } else {
11227: $first = int(1+rand(9));
11228: }
11229: $uname=$first.
1.1011 raeburn 11230: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11231: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11232: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11233: $uhome=&homeserver($uname,$udom,'true');
11234: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11235: return 'error: unable to generate unique course-ID';
11236: }
11237: }
11238: return $uname;
11239: }
11240:
1.813 albertel 11241: sub is_course {
1.1167 droeschl 11242: my ($cdom, $cnum) = scalar(@_) == 1 ?
11243: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 11244: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11245: my $uhome=&homeserver($cnum,$cdom);
11246: my $iscourse;
11247: if (grep { $_ eq $uhome } current_machine_ids()) {
11248: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11249: } else {
11250: my $hashid = $cdom.':'.$cnum;
11251: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11252: unless (defined($cached)) {
11253: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11254: $cnum,undef,undef,'.');
11255: $iscourse = 0;
11256: if (exists($courses{$cdom.'_'.$cnum})) {
11257: $iscourse = 1;
11258: }
11259: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11260: }
11261: }
11262: return unless($iscourse);
1.1167 droeschl 11263: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11264: }
11265:
1.1015 raeburn 11266: sub store_userdata {
11267: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11268: my $result;
1.1016 raeburn 11269: if ($datakey ne '') {
1.1013 raeburn 11270: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11271: if ($udom eq '' || $uname eq '') {
11272: $udom = $env{'user.domain'};
11273: $uname = $env{'user.name'};
11274: }
11275: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11276: if (($uhome eq '') || ($uhome eq 'no_host')) {
11277: $result = 'error: no_host';
11278: } else {
1.1172.2.138 raeburn 11279: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11280: $storehash->{'host'} = $perlvar{'lonHostID'};
11281:
11282: my $namevalue='';
11283: foreach my $key (keys(%{$storehash})) {
11284: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11285: }
11286: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 11287: unless ($namespace eq 'courserequests') {
11288: $datakey = &escape($datakey);
11289: }
1.1105 raeburn 11290: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11291: $namevalue,$uhome);
1.1013 raeburn 11292: }
11293: } else {
11294: $result = 'error: data to store was not a hash reference';
11295: }
11296: } else {
11297: $result= 'error: invalid requestkey';
11298: }
11299: return $result;
11300: }
11301:
1.21 www 11302: # ---------------------------------------------------------- Assign Custom Role
11303:
11304: sub assigncustomrole {
1.957 raeburn 11305: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11306: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11307: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11308: }
11309:
11310: # ----------------------------------------------------------------- Revoke Role
11311:
11312: sub revokerole {
1.957 raeburn 11313: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11314: my $now=time;
1.965 raeburn 11315: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11316: }
11317:
11318: # ---------------------------------------------------------- Revoke Custom Role
11319:
11320: sub revokecustomrole {
1.957 raeburn 11321: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11322: my $now=time;
1.357 www 11323: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11324: $deleteflag,$selfenroll,$context);
1.17 www 11325: }
11326:
1.533 banghart 11327: # ------------------------------------------------------------ Disk usage
1.535 albertel 11328: sub diskusage {
1.955 raeburn 11329: my ($udom,$uname,$directorypath,$getpropath)=@_;
11330: $directorypath =~ s/\/$//;
11331: my $listing=&reply('du2:'.&escape($directorypath).':'
11332: .&escape($getpropath).':'.&escape($uname).':'
11333: .&escape($udom),homeserver($uname,$udom));
11334: if ($listing eq 'unknown_cmd') {
11335: if ($getpropath) {
11336: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11337: }
11338: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11339: }
1.514 albertel 11340: return $listing;
1.512 banghart 11341: }
11342:
1.566 banghart 11343: sub is_locked {
1.1096 raeburn 11344: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11345: my @check;
11346: my $is_locked;
1.1093 raeburn 11347: push (@check,$file_name);
1.613 albertel 11348: my %locked = &get('file_permissions',\@check,
1.620 albertel 11349: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11350: my ($tmp)=keys(%locked);
11351: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11352:
1.566 banghart 11353: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11354: $is_locked = 'false';
11355: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11356: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11357: $is_locked = 'true';
1.1096 raeburn 11358: if (ref($which) eq 'ARRAY') {
11359: push(@{$which},$entry);
11360: } else {
11361: last;
11362: }
1.745 raeburn 11363: }
11364: }
1.566 banghart 11365: } else {
11366: $is_locked = 'false';
11367: }
1.1093 raeburn 11368: return $is_locked;
1.566 banghart 11369: }
11370:
1.759 albertel 11371: sub declutter_portfile {
11372: my ($file) = @_;
1.833 albertel 11373: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11374: return $file;
11375: }
11376:
1.559 banghart 11377: # ------------------------------------------------------------- Mark as Read Only
11378:
11379: sub mark_as_readonly {
11380: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11381: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11382: my ($tmp)=keys(%current_permissions);
11383: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11384: foreach my $file (@{$files}) {
1.759 albertel 11385: $file = &declutter_portfile($file);
1.561 banghart 11386: push(@{$current_permissions{$file}},$what);
1.559 banghart 11387: }
1.613 albertel 11388: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11389: return;
11390: }
11391:
1.572 banghart 11392: # ------------------------------------------------------------Save Selected Files
11393:
11394: sub save_selected_files {
11395: my ($user, $path, @files) = @_;
11396: my $filename = $user."savedfiles";
1.573 banghart 11397: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 11398: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11399: foreach my $file (@files) {
1.620 albertel 11400: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11401: }
11402: foreach my $file (@other_files) {
1.574 banghart 11403: print (OUT $file."\n");
1.572 banghart 11404: }
1.574 banghart 11405: close (OUT);
1.572 banghart 11406: return 'ok';
11407: }
11408:
1.574 banghart 11409: sub clear_selected_files {
11410: my ($user) = @_;
11411: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 11412: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11413: print (OUT undef);
11414: close (OUT);
11415: return ("ok");
11416: }
11417:
1.572 banghart 11418: sub files_in_path {
11419: my ($user, $path) = @_;
11420: my $filename = $user."savedfiles";
11421: my %return_files;
1.1172.2.96 raeburn 11422: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11423: while (my $line_in = <IN>) {
1.574 banghart 11424: chomp ($line_in);
11425: my @paths_and_file = split (m!/!, $line_in);
11426: my $file_part = pop (@paths_and_file);
11427: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11428: $path_part.='/';
11429: my $path_and_file = $path_part.$file_part;
11430: if ($path_part eq $path) {
11431: $return_files{$file_part}= 'selected';
11432: }
11433: }
1.574 banghart 11434: close (IN);
11435: return (\%return_files);
1.572 banghart 11436: }
11437:
11438: # called in portfolio select mode, to show files selected NOT in current directory
11439: sub files_not_in_path {
11440: my ($user, $path) = @_;
11441: my $filename = $user."savedfiles";
11442: my @return_files;
11443: my $path_part;
1.1172.2.96 raeburn 11444: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11445: while (my $line = <IN>) {
1.572 banghart 11446: #ok, I know it's clunky, but I want it to work
1.800 albertel 11447: my @paths_and_file = split(m|/|, $line);
11448: my $file_part = pop(@paths_and_file);
11449: chomp($file_part);
11450: my $path_part = join('/', @paths_and_file);
1.572 banghart 11451: $path_part .= '/';
11452: my $path_and_file = $path_part.$file_part;
11453: if ($path_part ne $path) {
1.800 albertel 11454: push(@return_files, ($path_and_file));
1.572 banghart 11455: }
11456: }
1.800 albertel 11457: close(OUT);
1.574 banghart 11458: return (@return_files);
1.572 banghart 11459: }
11460:
1.745 raeburn 11461: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11462:
1.745 raeburn 11463: sub get_portfile_permissions {
11464: my ($domain,$user) = @_;
1.613 albertel 11465: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11466: my ($tmp)=keys(%current_permissions);
11467: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11468: return \%current_permissions;
11469: }
11470:
11471: #---------------------------------------------Get portfolio file access controls
11472:
1.749 raeburn 11473: sub get_access_controls {
1.745 raeburn 11474: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11475: my %access;
11476: my $real_file = $file;
11477: $file =~ s/\.meta$//;
1.745 raeburn 11478: if (defined($file)) {
1.749 raeburn 11479: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11480: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11481: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11482: }
11483: }
1.745 raeburn 11484: } else {
1.749 raeburn 11485: foreach my $key (keys(%{$current_permissions})) {
11486: if ($key =~ /\0accesscontrol$/) {
11487: if (defined($group)) {
11488: if ($key !~ m-^\Q$group\E/-) {
11489: next;
11490: }
11491: }
11492: my ($fullpath) = split(/\0/,$key);
11493: if (ref($$current_permissions{$key}) eq 'HASH') {
11494: foreach my $control (keys(%{$$current_permissions{$key}})) {
11495: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11496: }
11497: }
11498: }
11499: }
11500: }
11501: return %access;
11502: }
11503:
11504: sub modify_access_controls {
11505: my ($file_name,$changes,$domain,$user)=@_;
11506: my ($outcome,$deloutcome);
11507: my %store_permissions;
11508: my %new_values;
11509: my %new_control;
11510: my %translation;
11511: my @deletions = ();
11512: my $now = time;
11513: if (exists($$changes{'activate'})) {
11514: if (ref($$changes{'activate'}) eq 'HASH') {
11515: my @newitems = sort(keys(%{$$changes{'activate'}}));
11516: my $numnew = scalar(@newitems);
11517: for (my $i=0; $i<$numnew; $i++) {
11518: my $newkey = $newitems[$i];
11519: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11520: if ($newkey =~ /^\d+:/) {
11521: $newkey =~ s/^(\d+)/$newid/;
11522: $translation{$1} = $newid;
11523: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11524: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11525: $translation{$1} = $newid;
11526: }
1.749 raeburn 11527: $new_values{$file_name."\0".$newkey} =
11528: $$changes{'activate'}{$newitems[$i]};
11529: $new_control{$newkey} = $now;
11530: }
11531: }
11532: }
11533: my %todelete;
11534: my %changed_items;
11535: foreach my $action ('delete','update') {
11536: if (exists($$changes{$action})) {
11537: if (ref($$changes{$action}) eq 'HASH') {
11538: foreach my $key (keys(%{$$changes{$action}})) {
11539: my ($itemnum) = ($key =~ /^([^:]+):/);
11540: if ($action eq 'delete') {
11541: $todelete{$itemnum} = 1;
11542: } else {
11543: $changed_items{$itemnum} = $key;
11544: }
11545: }
1.745 raeburn 11546: }
11547: }
1.749 raeburn 11548: }
11549: # get lock on access controls for file.
11550: my $lockhash = {
11551: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11552: ':'.$env{'user.domain'},
11553: };
11554: my $tries = 0;
11555: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11556:
1.1172.2.79 raeburn 11557: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11558: $tries ++;
1.1172.2.79 raeburn 11559: sleep(0.1);
1.749 raeburn 11560: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11561: }
11562: if ($gotlock eq 'ok') {
11563: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11564: my ($tmp)=keys(%curr_permissions);
11565: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11566: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11567: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11568: if (ref($curr_controls) eq 'HASH') {
11569: foreach my $control_item (keys(%{$curr_controls})) {
11570: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11571: if (defined($todelete{$itemnum})) {
11572: push(@deletions,$file_name."\0".$control_item);
11573: } else {
11574: if (defined($changed_items{$itemnum})) {
11575: $new_control{$changed_items{$itemnum}} = $now;
11576: push(@deletions,$file_name."\0".$control_item);
11577: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11578: } else {
11579: $new_control{$control_item} = $$curr_controls{$control_item};
11580: }
11581: }
1.745 raeburn 11582: }
11583: }
11584: }
1.970 raeburn 11585: my ($group);
11586: if (&is_course($domain,$user)) {
11587: ($group,my $file) = split(/\//,$file_name,2);
11588: }
1.749 raeburn 11589: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11590: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11591: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11592: # remove lock
11593: my @del_lock = ($file_name."\0".'locked_access_records');
11594: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11595: my $sqlresult =
1.970 raeburn 11596: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11597: $group);
1.749 raeburn 11598: } else {
11599: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11600: }
1.749 raeburn 11601: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11602: }
11603:
1.827 raeburn 11604: sub make_public_indefinitely {
11605: my ($requrl) = @_;
11606: my $now = time;
11607: my $action = 'activate';
11608: my $aclnum = 0;
11609: if (&is_portfolio_url($requrl)) {
11610: my (undef,$udom,$unum,$file_name,$group) =
11611: &parse_portfolio_url($requrl);
11612: my $current_perms = &get_portfile_permissions($udom,$unum);
11613: my %access_controls = &get_access_controls($current_perms,
11614: $group,$file_name);
11615: foreach my $key (keys(%{$access_controls{$file_name}})) {
11616: my ($num,$scope,$end,$start) =
11617: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11618: if ($scope eq 'public') {
11619: if ($start <= $now && $end == 0) {
11620: $action = 'none';
11621: } else {
11622: $action = 'update';
11623: $aclnum = $num;
11624: }
11625: last;
11626: }
11627: }
11628: if ($action eq 'none') {
11629: return 'ok';
11630: } else {
11631: my %changes;
11632: my $newend = 0;
11633: my $newstart = $now;
11634: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11635: $changes{$action}{$newkey} = {
11636: type => 'public',
11637: time => {
11638: start => $newstart,
11639: end => $newend,
11640: },
11641: };
11642: my ($outcome,$deloutcome,$new_values,$translation) =
11643: &modify_access_controls($file_name,\%changes,$udom,$unum);
11644: return $outcome;
11645: }
11646: } else {
11647: return 'invalid';
11648: }
11649: }
11650:
1.745 raeburn 11651: #------------------------------------------------------Get Marked as Read Only
11652:
11653: sub get_marked_as_readonly {
11654: my ($domain,$user,$what,$group) = @_;
11655: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11656: my @readonly_files;
1.629 banghart 11657: my $cmp1=$what;
11658: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11659: while (my ($file_name,$value) = each(%{$current_permissions})) {
11660: if (defined($group)) {
11661: if ($file_name !~ m-^\Q$group\E/-) {
11662: next;
11663: }
11664: }
1.561 banghart 11665: if (ref($value) eq "ARRAY"){
11666: foreach my $stored_what (@{$value}) {
1.629 banghart 11667: my $cmp2=$stored_what;
1.759 albertel 11668: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11669: $cmp2=join('',@{$stored_what});
1.745 raeburn 11670: }
1.629 banghart 11671: if ($cmp1 eq $cmp2) {
1.561 banghart 11672: push(@readonly_files, $file_name);
1.745 raeburn 11673: last;
1.563 banghart 11674: } elsif (!defined($what)) {
11675: push(@readonly_files, $file_name);
1.745 raeburn 11676: last;
1.561 banghart 11677: }
11678: }
1.745 raeburn 11679: }
1.561 banghart 11680: }
11681: return @readonly_files;
11682: }
1.577 banghart 11683: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11684:
1.577 banghart 11685: sub get_marked_as_readonly_hash {
1.745 raeburn 11686: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11687: my %readonly_files;
1.745 raeburn 11688: while (my ($file_name,$value) = each(%{$current_permissions})) {
11689: if (defined($group)) {
11690: if ($file_name !~ m-^\Q$group\E/-) {
11691: next;
11692: }
11693: }
1.577 banghart 11694: if (ref($value) eq "ARRAY"){
11695: foreach my $stored_what (@{$value}) {
1.745 raeburn 11696: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11697: foreach my $lock_descriptor(@{$stored_what}) {
11698: if ($lock_descriptor eq 'graded') {
11699: $readonly_files{$file_name} = 'graded';
11700: } elsif ($lock_descriptor eq 'handback') {
11701: $readonly_files{$file_name} = 'handback';
11702: } else {
11703: if (!exists($readonly_files{$file_name})) {
11704: $readonly_files{$file_name} = 'locked';
11705: }
11706: }
1.745 raeburn 11707: }
1.750 banghart 11708: }
1.577 banghart 11709: }
11710: }
11711: }
11712: return %readonly_files;
11713: }
1.559 banghart 11714: # ------------------------------------------------------------ Unmark as Read Only
11715:
11716: sub unmark_as_readonly {
1.629 banghart 11717: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11718: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11719: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11720: $file_name = &declutter_portfile($file_name);
1.634 albertel 11721: my $symb_crs = $what;
11722: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11723: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11724: my ($tmp)=keys(%current_permissions);
11725: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11726: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11727: foreach my $file (@readonly_files) {
1.759 albertel 11728: my $clean_file = &declutter_portfile($file);
11729: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11730: my $current_locks = $current_permissions{$file};
1.563 banghart 11731: my @new_locks;
11732: my @del_keys;
11733: if (ref($current_locks) eq "ARRAY"){
11734: foreach my $locker (@{$current_locks}) {
1.632 albertel 11735: my $compare=$locker;
1.749 raeburn 11736: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11737: $compare=join('',@{$locker});
1.746 raeburn 11738: if ($compare ne $symb_crs) {
11739: push(@new_locks, $locker);
11740: }
1.563 banghart 11741: }
11742: }
1.650 albertel 11743: if (scalar(@new_locks) > 0) {
1.563 banghart 11744: $current_permissions{$file} = \@new_locks;
11745: } else {
11746: push(@del_keys, $file);
1.613 albertel 11747: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11748: delete($current_permissions{$file});
1.563 banghart 11749: }
11750: }
1.561 banghart 11751: }
1.613 albertel 11752: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11753: return;
11754: }
1.512 banghart 11755:
1.17 www 11756: # ------------------------------------------------------------ Directory lister
11757:
11758: sub dirlist {
1.955 raeburn 11759: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11760: $uri=~s/^\///;
11761: $uri=~s/\/$//;
1.253 stredwic 11762: my ($udom, $uname);
1.955 raeburn 11763: if ($getuserdir) {
1.253 stredwic 11764: $udom = $userdomain;
11765: $uname = $username;
1.955 raeburn 11766: } else {
11767: (undef,$udom,$uname)=split(/\//,$uri);
11768: if(defined($userdomain)) {
11769: $udom = $userdomain;
11770: }
11771: if(defined($username)) {
11772: $uname = $username;
11773: }
1.253 stredwic 11774: }
1.955 raeburn 11775: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11776:
1.955 raeburn 11777: $dirRoot = $perlvar{'lonDocRoot'};
11778: if (defined($getpropath)) {
11779: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11780: $dirRoot =~ s/\/$//;
1.955 raeburn 11781: } elsif (defined($getuserdir)) {
11782: my $subdir=$uname.'__';
11783: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11784: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11785: ."/$udom/$subdir/$uname";
11786: } elsif (defined($alternateRoot)) {
11787: $dirRoot = $alternateRoot;
1.751 banghart 11788: }
1.253 stredwic 11789:
11790: if($udom) {
11791: if($uname) {
1.1135 raeburn 11792: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11793: if ($uhome eq 'no_host') {
11794: return ([],'no_host');
11795: }
1.955 raeburn 11796: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11797: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11798: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11799: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11800: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11801: } else {
11802: @listing_results = map { &unescape($_); } split(/:/,$listing);
11803: }
1.605 matthew 11804: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11805: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11806: @listing_results = split(/:/,$listing);
11807: } else {
11808: @listing_results = map { &unescape($_); } split(/:/,$listing);
11809: }
1.1135 raeburn 11810: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11811: ($listing eq 'rejected') || ($listing eq 'refused') ||
11812: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11813: return ([],$listing);
11814: } else {
11815: return (\@listing_results);
1.1135 raeburn 11816: }
1.955 raeburn 11817: } elsif(!$alternateRoot) {
1.1136 raeburn 11818: my (%allusers,%listerror);
1.841 albertel 11819: my %servers = &get_servers($udom,'library');
1.955 raeburn 11820: foreach my $tryserver (keys(%servers)) {
11821: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11822: &escape($udom),$tryserver);
11823: if ($listing eq 'unknown_cmd') {
11824: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11825: $udom, $tryserver);
11826: } else {
11827: @listing_results = map { &unescape($_); } split(/:/,$listing);
11828: }
1.841 albertel 11829: if ($listing eq 'unknown_cmd') {
11830: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11831: $udom, $tryserver);
11832: @listing_results = split(/:/,$listing);
11833: } else {
11834: @listing_results =
11835: map { &unescape($_); } split(/:/,$listing);
11836: }
1.1136 raeburn 11837: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11838: ($listing eq 'rejected') || ($listing eq 'refused') ||
11839: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11840: $listerror{$tryserver} = $listing;
11841: } else {
1.841 albertel 11842: foreach my $line (@listing_results) {
11843: my ($entry) = split(/&/,$line,2);
11844: $allusers{$entry} = 1;
11845: }
11846: }
1.253 stredwic 11847: }
1.1136 raeburn 11848: my @alluserslist=();
1.800 albertel 11849: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11850: push(@alluserslist,$user.'&user');
1.253 stredwic 11851: }
1.1172.2.80 raeburn 11852: if (!%listerror) {
11853: # no errors
11854: return (\@alluserslist);
11855: } elsif (scalar(keys(%servers)) == 1) {
11856: # one library server, one error
11857: my ($key) = keys(%listerror);
11858: return (\@alluserslist, $listerror{$key});
11859: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11860: # con_lost indicates that we might miss data from at least one
11861: # library server
11862: return (\@alluserslist, 'con_lost');
11863: } else {
11864: # multiple library servers and no con_lost -> data should be
11865: # complete.
11866: return (\@alluserslist);
11867: }
11868:
1.253 stredwic 11869: } else {
1.1136 raeburn 11870: return ([],'missing username');
1.253 stredwic 11871: }
1.955 raeburn 11872: } elsif(!defined($getpropath)) {
1.1136 raeburn 11873: my $path = $perlvar{'lonDocRoot'}.'/res/';
11874: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11875: return (\@all_domains);
1.955 raeburn 11876: } else {
1.1136 raeburn 11877: return ([],'missing domain');
1.275 stredwic 11878: }
11879: }
11880:
11881: # --------------------------------------------- GetFileTimestamp
11882: # This function utilizes dirlist and returns the date stamp for
11883: # when it was last modified. It will also return an error of -1
11884: # if an error occurs
11885:
11886: sub GetFileTimestamp {
1.955 raeburn 11887: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11888: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11889: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11890: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11891: undef,$getuserdir);
11892: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11893: return -1;
11894: }
11895: if (ref($fileref) eq 'ARRAY') {
11896: my @stats = split('&',$fileref->[0]);
1.375 matthew 11897: # @stats contains first the filename, then the stat output
11898: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11899: } else {
11900: return -1;
1.253 stredwic 11901: }
1.26 www 11902: }
11903:
1.712 albertel 11904: sub stat_file {
11905: my ($uri) = @_;
1.787 albertel 11906: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11907:
1.955 raeburn 11908: my ($udom,$uname,$file);
1.712 albertel 11909: if ($uri =~ m-^/(uploaded|editupload)/-) {
11910: ($udom,$uname,$file) =
1.811 albertel 11911: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11912: $file = 'userfiles/'.$file;
11913: }
11914: if ($uri =~ m-^/res/-) {
11915: ($udom,$uname) =
1.807 albertel 11916: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11917: $file = $uri;
11918: }
11919:
11920: if (!$udom || !$uname || !$file) {
11921: # unable to handle the uri
11922: return ();
11923: }
1.956 raeburn 11924: my $getpropath;
11925: if ($file =~ /^userfiles\//) {
11926: $getpropath = 1;
11927: }
1.1136 raeburn 11928: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11929: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11930: return ();
11931: } else {
11932: if (ref($listref) eq 'ARRAY') {
11933: my @stats = split('&',$listref->[0]);
11934: shift(@stats); #filename is first
11935: return @stats;
11936: }
1.712 albertel 11937: }
11938: return ();
11939: }
11940:
1.26 www 11941: # -------------------------------------------------------- Value of a Condition
11942:
1.713 albertel 11943: # gets the value of a specific preevaluated condition
11944: # stored in the string $env{user.state.<cid>}
11945: # or looks up a condition reference in the bighash and if if hasn't
11946: # already been evaluated recurses into docondval to get the value of
11947: # the condition, then memoizing it to
11948: # $env{user.state.<cid>.<condition>}
1.40 www 11949: sub directcondval {
11950: my $number=shift;
1.620 albertel 11951: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11952: &Apache::lonuserstate::evalstate();
11953: }
1.713 albertel 11954: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11955: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11956: } elsif ($number =~ /^_/) {
11957: my $sub_condition;
11958: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11959: &GDBM_READER(),0640)) {
11960: $sub_condition=$bighash{'conditions'.$number};
11961: untie(%bighash);
11962: }
11963: my $value = &docondval($sub_condition);
1.949 raeburn 11964: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11965: return $value;
11966: }
1.620 albertel 11967: if ($env{'user.state.'.$env{'request.course.id'}}) {
11968: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11969: } else {
11970: return 2;
11971: }
11972: }
11973:
1.713 albertel 11974: # get the collection of conditions for this resource
1.26 www 11975: sub condval {
11976: my $condidx=shift;
1.54 www 11977: my $allpathcond='';
1.713 albertel 11978: foreach my $cond (split(/\|/,$condidx)) {
11979: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11980: $allpathcond.=
11981: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11982: }
1.191 harris41 11983: }
1.54 www 11984: $allpathcond=~s/\|$//;
1.713 albertel 11985: return &docondval($allpathcond);
11986: }
11987:
11988: #evaluates an expression of conditions
11989: sub docondval {
11990: my ($allpathcond) = @_;
11991: my $result=0;
11992: if ($env{'request.course.id'}
11993: && defined($allpathcond)) {
11994: my $operand='|';
11995: my @stack;
11996: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11997: if ($chunk eq '(') {
11998: push @stack,($operand,$result);
11999: } elsif ($chunk eq ')') {
12000: my $before=pop @stack;
12001: if (pop @stack eq '&') {
12002: $result=$result>$before?$before:$result;
12003: } else {
12004: $result=$result>$before?$result:$before;
12005: }
12006: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12007: $operand=$chunk;
12008: } else {
12009: my $new=directcondval($chunk);
12010: if ($operand eq '&') {
12011: $result=$result>$new?$new:$result;
12012: } else {
12013: $result=$result>$new?$result:$new;
12014: }
12015: }
12016: }
1.26 www 12017: }
12018: return $result;
1.421 albertel 12019: }
12020:
12021: # ---------------------------------------------------- Devalidate courseresdata
12022:
12023: sub devalidatecourseresdata {
12024: my ($coursenum,$coursedomain)=@_;
12025: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12026: &devalidate_cache_new('courseres',$hashid);
1.28 www 12027: }
12028:
1.763 www 12029:
1.200 www 12030: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12031: #
12032: # Parameters:
12033: # $coursenum - Number of the course.
12034: # $coursedomain - Domain at which the course was created.
12035: # Returns:
12036: # A hash of the course parameters along (I think) with timestamps
12037: # and version info.
1.877 foxr 12038:
1.624 albertel 12039: sub get_courseresdata {
12040: my ($coursenum,$coursedomain)=@_;
1.200 www 12041: my $coursehom=&homeserver($coursenum,$coursedomain);
12042: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12043: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12044: my %dumpreply;
1.417 albertel 12045: unless (defined($cached)) {
1.624 albertel 12046: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12047: $result=\%dumpreply;
1.251 albertel 12048: my ($tmp) = keys(%dumpreply);
12049: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12050: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12051: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12052: return $tmp;
1.416 albertel 12053: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12054: $result=undef;
1.599 albertel 12055: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12056: }
12057: }
1.624 albertel 12058: return $result;
12059: }
12060:
1.633 albertel 12061: sub devalidateuserresdata {
12062: my ($uname,$udom)=@_;
12063: my $hashid="$udom:$uname";
12064: &devalidate_cache_new('userres',$hashid);
12065: }
12066:
1.624 albertel 12067: sub get_userresdata {
12068: my ($uname,$udom)=@_;
12069: #most student don\'t have any data set, check if there is some data
12070: if (&EXT_cache_status($udom,$uname)) { return undef; }
12071:
12072: my $hashid="$udom:$uname";
12073: my ($result,$cached)=&is_cached_new('userres',$hashid);
12074: if (!defined($cached)) {
12075: my %resourcedata=&dump('resourcedata',$udom,$uname);
12076: $result=\%resourcedata;
12077: &do_cache_new('userres',$hashid,$result,600);
12078: }
12079: my ($tmp)=keys(%$result);
12080: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12081: return $result;
12082: }
12083: #error 2 occurs when the .db doesn't exist
12084: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 12085: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12086: &logthis("<font color=\"blue\">WARNING:".
12087: " Trying to get resource data for ".
12088: $uname." at ".$udom.": ".
12089: $tmp."</font>");
12090: }
1.624 albertel 12091: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12092: #&EXT_cache_set($udom,$uname);
12093: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12094: undef($tmp); # not really an error so don't send it back
1.624 albertel 12095: }
12096: return $tmp;
12097: }
1.879 foxr 12098: #----------------------------------------------- resdata - return resource data
12099: # Purpose:
12100: # Return resource data for either users or for a course.
12101: # Parameters:
12102: # $name - Course/user name.
12103: # $domain - Name of the domain the user/course is registered on.
12104: # $type - Type of thing $name is (must be 'course' or 'user'
12105: # @which - Array of names of resources desired.
12106: # Returns:
12107: # The value of the first reasource in @which that is found in the
12108: # resource hash.
12109: # Exceptional Conditions:
12110: # If the $type passed in is not valid (not the string 'course' or
12111: # 'user', an undefined reference is returned.
12112: # If none of the resources are found, an undef is returned
1.624 albertel 12113: sub resdata {
12114: my ($name,$domain,$type,@which)=@_;
12115: my $result;
12116: if ($type eq 'course') {
12117: $result=&get_courseresdata($name,$domain);
12118: } elsif ($type eq 'user') {
12119: $result=&get_userresdata($name,$domain);
12120: }
12121: if (!ref($result)) { return $result; }
1.251 albertel 12122: foreach my $item (@which) {
1.927 albertel 12123: if (defined($result->{$item->[0]})) {
12124: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12125: }
1.250 albertel 12126: }
1.291 albertel 12127: return undef;
1.200 www 12128: }
12129:
1.1172.2.146. .1(raebu 12130:22): sub get_domain_lti {
12131:22): my ($cdom,$context) = @_;
.4(raebu 12132:22): my ($name,$cachename,%lti);
.1(raebu 12133:22): if ($context eq 'consumer') {
12134:22): $name = 'ltitools';
12135:22): } elsif ($context eq 'provider') {
12136:22): $name = 'lti';
.4(raebu 12137:22): } elsif ($context eq 'linkprot') {
12138:22): $name = 'ltisec';
.1(raebu 12139:22): } else {
12140:22): return %lti;
12141:22): }
.4(raebu 12142:22): if ($context eq 'linkprot') {
12143:22): $cachename = $context;
12144:22): } else {
12145:22): $cachename = $name;
12146:22): }
12147:22): my ($result,$cached)=&is_cached_new($cachename,$cdom);
.1(raebu 12148:22): if (defined($cached)) {
12149:22): if (ref($result) eq 'HASH') {
12150:22): %lti = %{$result};
12151:22): }
12152:22): } else {
12153:22): my %domconfig = &get_dom('configuration',[$name],$cdom);
12154:22): if (ref($domconfig{$name}) eq 'HASH') {
.4(raebu 12155:22): if ($context eq 'linkprot') {
12156:22): if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12157:22): %lti = %{$domconfig{$name}{'linkprot'}};
12158:22): }
12159:22): } else {
12160:22): %lti = %{$domconfig{$name}};
12161:22): }
.1(raebu 12162:22): }
12163:22): my $cachetime = 24*60*60;
.4(raebu 12164:22): &do_cache_new($cachename,$cdom,\%lti,$cachetime);
.1(raebu 12165:22): }
12166:22): return %lti;
12167:22): }
12168:22):
12169:22): sub get_course_lti {
.13(raeb 12170:-23): my ($cnum,$cdom,$context) = @_;
12171:-23): my ($name,$cachename,%lti);
12172:-23): if ($context eq 'consumer') {
12173:-23): $name = 'ltitools';
12174:-23): $cachename = 'courseltitools';
12175:-23): } elsif ($context eq 'provider') {
12176:-23): $name = 'lti';
12177:-23): $cachename = 'courselti';
12178:-23): } else {
12179:-23): return %lti;
12180:-23): }
.1(raebu 12181:22): my $hashid=$cdom.'_'.$cnum;
.13(raeb 12182:-23): my ($result,$cached)=&is_cached_new($cachename,$hashid);
.1(raebu 12183:22): if (defined($cached)) {
12184:22): if (ref($result) eq 'HASH') {
.13(raeb 12185:-23): %lti = %{$result};
.1(raebu 12186:22): }
12187:22): } else {
.13(raeb 12188:-23): %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
.1(raebu 12189:22): my $cachetime = 24*60*60;
.13(raeb 12190:-23): &do_cache_new($cachename,$hashid,\%lti,$cachetime);
.1(raebu 12191:22): }
.13(raeb 12192:-23): return %lti;
.1(raebu 12193:22): }
12194:22):
.3(raebu 12195:22): sub courselti_itemid {
12196:22): my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12197:22): my ($chome,$itemid);
12198:22): $chome = &homeserver($cnum,$cdom);
12199:22): return if ($chome eq 'no_host');
12200:22): if (ref($params) eq 'HASH') {
12201:22): my $rep;
12202:22): if (grep { $_ eq $chome } current_machine_ids()) {
12203:22): $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12204:22): } else {
12205:22): my $escurl = &escape($url);
12206:22): my $escmethod = &escape($method);
12207:22): my $items = &freeze_escape($params);
12208:22): $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12209:22): }
12210:22): unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12211:22): ($rep eq 'unknown_cmd')) {
12212:22): $itemid = $rep;
12213:22): }
12214:22): }
12215:22): return $itemid;
12216:22): }
12217:22):
12218:22): sub domainlti_itemid {
12219:22): my ($cdom,$url,$method,$params,$context) = @_;
12220:22): my ($primary_id,$itemid);
12221:22): $primary_id = &domain($cdom,'primary');
12222:22): return if ($primary_id eq '');
12223:22): if (ref($params) eq 'HASH') {
12224:22): my $rep;
12225:22): if (grep { $_ eq $primary_id } current_machine_ids()) {
12226:22): $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12227:22): } else {
12228:22): my $cnum = '';
12229:22): my $escurl = &escape($url);
12230:22): my $escmethod = &escape($method);
12231:22): my $items = &freeze_escape($params);
12232:22): $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12233:22): }
12234:22): unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12235:22): ($rep eq 'unknown_cmd')) {
12236:22): $itemid = $rep;
12237:22): }
12238:22): }
12239:22): return $itemid;
12240:22): }
12241:22):
.15(raeb 12242:-23): sub get_ltitools_id {
12243:-23): my ($context,$cdom,$cnum,$title) = @_;
12244:-23): my ($lockhash,$tries,$gotlock,$id,$error);
12245:-23):
12246:-23): # get lock on ltitools db
12247:-23): $lockhash = {
12248:-23): lock => $env{'user.name'}.
12249:-23): ':'.$env{'user.domain'},
12250:-23): };
12251:-23): $tries = 0;
12252:-23): if ($context eq 'domain') {
12253:-23): $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12254:-23): } else {
12255:-23): $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12256:-23): }
12257:-23): while (($gotlock ne 'ok') && ($tries<10)) {
12258:-23): $tries ++;
12259:-23): sleep (0.1);
12260:-23): if ($context eq 'domain') {
12261:-23): $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12262:-23): } else {
12263:-23): $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12264:-23): }
12265:-23): }
12266:-23): if ($gotlock eq 'ok') {
12267:-23): my %currids;
12268:-23): if ($context eq 'domain') {
12269:-23): %currids = &dump_dom('ltitools',$cdom);
12270:-23): } else {
12271:-23): %currids = &dump('ltitools',$cdom,$cnum);
12272:-23): }
12273:-23): if ($currids{'lock'}) {
12274:-23): delete($currids{'lock'});
12275:-23): if (keys(%currids)) {
12276:-23): my @curr = sort { $a <=> $b } keys(%currids);
12277:-23): if ($curr[-1] =~ /^\d+$/) {
12278:-23): $id = 1 + $curr[-1];
12279:-23): }
12280:-23): } else {
12281:-23): $id = 1;
12282:-23): }
12283:-23): if ($id) {
12284:-23): if ($context eq 'domain') {
12285:-23): unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12286:-23): $error = 'nostore';
12287:-23): }
12288:-23): } else {
12289:-23): unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12290:-23): $error = 'nostore';
12291:-23): }
12292:-23): }
12293:-23): } else {
12294:-23): $error = 'nonumber';
12295:-23): }
12296:-23): }
12297:-23): my $dellockoutcome;
12298:-23): if ($context eq 'domain') {
12299:-23): $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12300:-23): } else {
12301:-23): $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12302:-23): }
12303:-23): } else {
12304:-23): $error = 'nolock';
12305:-23): }
12306:-23): return ($id,$error);
12307:-23): }
12308:-23):
.9(raebu 12309:23): sub count_supptools {
12310:23): my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31 raeburn 12311: my $hashid=$cnum.':'.$cdom;
1.1172.2.146. .9(raebu 12312:23): my ($numexttools,$cached);
1.1172.2.31 raeburn 12313: unless ($ignorecache) {
1.1172.2.146. .9(raebu 12314:23): ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31 raeburn 12315: }
12316: unless (defined($cached)) {
12317: my $chome=&homeserver($cnum,$cdom);
1.1172.2.146. .9(raebu 12318:23): $numexttools = 0;
1.1172.2.31 raeburn 12319: unless ($chome eq 'no_host') {
1.1172.2.146. .9(raebu 12320:23): my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12321:23): if (ref($supplemental) eq 'HASH') {
12322:23): if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12323:23): foreach my $key (keys(%{$supplemental->{'ids'}})) {
12324:23): if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12325:23): $numexttools ++;
12326:23): }
12327:23): }
12328:23): }
12329:23): }
1.1172.2.31 raeburn 12330: }
1.1172.2.146. .9(raebu 12331:23): &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31 raeburn 12332: }
1.1172.2.146. .9(raebu 12333:23): return $numexttools;
12334:23): }
12335:23):
12336:23): sub has_unhidden_suppfiles {
12337:23): my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12338:23): my $hashid=$cnum.':'.$cdom;
12339:23): my ($showsupp,$cached);
12340:23): unless ($ignorecache) {
12341:23): ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12342:23): }
12343:23): unless (defined($cached)) {
12344:23): my $chome=&homeserver($cnum,$cdom);
12345:23): unless ($chome eq 'no_host') {
12346:23): my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12347:23): if (ref($supplemental) eq 'HASH') {
12348:23): if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12349:23): foreach my $key (keys(%{$supplemental->{'ids'}})) {
12350:23): next if ($key =~ /\.sequence$/);
12351:23): if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12352:23): foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12353:23): unless ($supplemental->{'hidden'}->{$id}) {
12354:23): $showsupp = 1;
12355:23): last;
12356:23): }
12357:23): }
12358:23): }
12359:23): last if ($showsupp);
12360:23): }
12361:23): }
12362:23): }
12363:23): }
12364:23): &do_cache_new('showsupp',$hashid,$showsupp,600);
12365:23): }
12366:23): return $showsupp;
1.1172.2.31 raeburn 12367: }
12368:
1.379 matthew 12369: #
12370: # EXT resource caching routines
12371: #
12372:
1.1172.2.146. .1(raebu 12373:22): {
12374:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12375:22): #
12376:22): # The course for which we cache
12377:22): my $cachedmapkey='';
12378:22): # The cached recursive maps for this course
12379:22): my %cachedmaps=();
12380:22): # When this was last done
12381:22): my $cachedmaptime='';
12382:22):
1.379 matthew 12383: sub clear_EXT_cache_status {
1.383 albertel 12384: &delenv('cache.EXT.');
1.379 matthew 12385: }
12386:
12387: sub EXT_cache_status {
12388: my ($target_domain,$target_user) = @_;
1.383 albertel 12389: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12390: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12391: # We know already the user has no data
12392: return 1;
12393: } else {
12394: return 0;
12395: }
12396: }
12397:
12398: sub EXT_cache_set {
12399: my ($target_domain,$target_user) = @_;
1.383 albertel 12400: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12401: #&appenv({$cachename => time});
1.379 matthew 12402: }
12403:
1.28 www 12404: # --------------------------------------------------------- Value of a Variable
1.58 www 12405: sub EXT {
1.715 albertel 12406:
1.1172.2.28 raeburn 12407: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12408: unless ($varname) { return ''; }
1.218 albertel 12409: #get real user name/domain, courseid and symb
12410: my $courseid;
1.359 albertel 12411: my $publicuser;
1.427 www 12412: if ($symbparm) {
12413: $symbparm=&get_symb_from_alias($symbparm);
12414: }
1.218 albertel 12415: if (!($uname && $udom)) {
1.790 albertel 12416: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12417: if (!$symbparm) { $symbparm=$cursymb; }
12418: } else {
1.620 albertel 12419: $courseid=$env{'request.course.id'};
1.218 albertel 12420: }
1.48 www 12421: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12422: my $rest;
1.320 albertel 12423: if (defined($therest[0])) {
1.48 www 12424: $rest=join('.',@therest);
12425: } else {
12426: $rest='';
12427: }
1.320 albertel 12428:
1.57 www 12429: my $qualifierrest=$qualifier;
12430: if ($rest) { $qualifierrest.='.'.$rest; }
12431: my $spacequalifierrest=$space;
12432: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12433: if ($realm eq 'user') {
1.48 www 12434: # --------------------------------------------------------------- user.resource
12435: if ($space eq 'resource') {
1.651 albertel 12436: if ( (defined($Apache::lonhomework::parsing_a_problem)
12437: || defined($Apache::lonhomework::parsing_a_task))
12438: &&
1.1172.2.142 raeburn 12439: ($symbparm eq &symbread()) ) {
1.744 albertel 12440: # if we are in the middle of processing the resource the
12441: # get the value we are planning on committing
12442: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12443: return $Apache::lonhomework::results{$qualifierrest};
12444: } else {
12445: return $Apache::lonhomework::history{$qualifierrest};
12446: }
1.335 albertel 12447: } else {
1.359 albertel 12448: my %restored;
1.620 albertel 12449: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12450: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12451: } else {
12452: %restored=&restore($symbparm,$courseid,$udom,$uname);
12453: }
1.335 albertel 12454: return $restored{$qualifierrest};
12455: }
1.48 www 12456: # ----------------------------------------------------------------- user.access
12457: } elsif ($space eq 'access') {
1.218 albertel 12458: # FIXME - not supporting calls for a specific user
1.48 www 12459: return &allowed($qualifier,$rest);
12460: # ------------------------------------------ user.preferences, user.environment
12461: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12462: if (($uname eq $env{'user.name'}) &&
12463: ($udom eq $env{'user.domain'})) {
12464: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12465: } else {
1.359 albertel 12466: my %returnhash;
12467: if (!$publicuser) {
12468: %returnhash=&userenvironment($udom,$uname,
12469: $qualifierrest);
12470: }
1.218 albertel 12471: return $returnhash{$qualifierrest};
12472: }
1.48 www 12473: # ----------------------------------------------------------------- user.course
12474: } elsif ($space eq 'course') {
1.218 albertel 12475: # FIXME - not supporting calls for a specific user
1.620 albertel 12476: return $env{join('.',('request.course',$qualifier))};
1.48 www 12477: # ------------------------------------------------------------------- user.role
12478: } elsif ($space eq 'role') {
1.218 albertel 12479: # FIXME - not supporting calls for a specific user
1.620 albertel 12480: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12481: if ($qualifier eq 'value') {
12482: return $role;
12483: } elsif ($qualifier eq 'extent') {
12484: return $where;
12485: }
12486: # ----------------------------------------------------------------- user.domain
12487: } elsif ($space eq 'domain') {
1.218 albertel 12488: return $udom;
1.48 www 12489: # ------------------------------------------------------------------- user.name
12490: } elsif ($space eq 'name') {
1.218 albertel 12491: return $uname;
1.48 www 12492: # ---------------------------------------------------- Any other user namespace
1.29 www 12493: } else {
1.359 albertel 12494: my %reply;
12495: if (!$publicuser) {
12496: %reply=&get($space,[$qualifierrest],$udom,$uname);
12497: }
12498: return $reply{$qualifierrest};
1.48 www 12499: }
1.236 www 12500: } elsif ($realm eq 'query') {
12501: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12502: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12503: [$spacequalifierrest]);
1.620 albertel 12504: return $env{'form.'.$spacequalifierrest};
1.236 www 12505: } elsif ($realm eq 'request') {
1.48 www 12506: # ------------------------------------------------------------- request.browser
12507: if ($space eq 'browser') {
1.1145 bisitz 12508: return $env{'browser.'.$qualifier};
1.57 www 12509: # ------------------------------------------------------------ request.filename
12510: } else {
1.620 albertel 12511: return $env{'request.'.$spacequalifierrest};
1.29 www 12512: }
1.28 www 12513: } elsif ($realm eq 'course') {
1.48 www 12514: # ---------------------------------------------------------- course.description
1.620 albertel 12515: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12516: } elsif ($realm eq 'resource') {
1.165 www 12517:
1.620 albertel 12518: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12519: if (!$symbparm) { $symbparm=&symbread(); }
12520: }
1.693 albertel 12521:
1.1172.2.30 raeburn 12522: if ($qualifier eq '') {
12523: if ($space eq 'title') {
12524: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12525: return &gettitle($symbparm);
12526: }
1.693 albertel 12527:
1.1172.2.30 raeburn 12528: if ($space eq 'map') {
12529: my ($map) = &decode_symb($symbparm);
12530: return &symbread($map);
12531: }
12532: if ($space eq 'maptitle') {
12533: my ($map) = &decode_symb($symbparm);
12534: return &gettitle($map);
12535: }
12536: if ($space eq 'filename') {
12537: if ($symbparm) {
12538: return &clutter((&decode_symb($symbparm))[2]);
12539: }
12540: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12541: }
1.1172.2.30 raeburn 12542:
12543: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12544: if ($space eq 'visibleparts') {
12545: my $navmap = Apache::lonnavmaps::navmap->new();
12546: my $item;
12547: if (ref($navmap)) {
12548: my $res = $navmap->getBySymb($symbparm);
12549: my $parts = $res->parts();
12550: if (ref($parts) eq 'ARRAY') {
12551: $item = join(',',@{$parts});
12552: }
12553: undef($navmap);
12554: }
12555: return $item;
12556: }
12557: }
12558: }
1.693 albertel 12559:
12560: my ($section, $group, @groups);
1.593 albertel 12561: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 12562: if (($courseid eq '') && ($cid)) {
12563: $courseid = $cid;
12564: }
12565: if (($symbparm && $courseid) &&
12566: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12567:
1.218 albertel 12568: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12569:
1.60 www 12570: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12571: my $symbp=$symbparm;
1.735 albertel 12572: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12573:
12574: my $symbparm=$symbp.'.'.$spacequalifierrest;
12575: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12576:
1.620 albertel 12577: if (($env{'user.name'} eq $uname) &&
12578: ($env{'user.domain'} eq $udom)) {
12579: $section=$env{'request.course.sec'};
1.733 raeburn 12580: @groups = split(/:/,$env{'request.course.groups'});
12581: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12582: } else {
1.539 albertel 12583: if (! defined($usection)) {
1.551 albertel 12584: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12585: } else {
12586: $section = $usection;
12587: }
1.733 raeburn 12588: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12589: }
12590:
12591: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12592: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12593: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12594:
1.593 albertel 12595: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12596: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 12597: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12598:
1.60 www 12599: # ----------------------------------------------------------- first, check user
1.624 albertel 12600:
12601: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 12602: ([$courselevelr,'resource'],
12603: [$courselevelm,'map' ],
12604: [$courselevel, 'course' ]));
1.931 albertel 12605: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12606:
1.594 albertel 12607: # ------------------------------------------------ second, check some of course
1.684 raeburn 12608: my $coursereply;
1.691 raeburn 12609: if (@groups > 0) {
12610: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12611: $mapparm,$spacequalifierrest);
1.927 albertel 12612: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12613: }
1.96 www 12614:
1.684 raeburn 12615: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12616: $env{'course.'.$courseid.'.domain'},
12617: 'course',
12618: ([$seclevelr, 'resource'],
12619: [$seclevelm, 'map' ],
12620: [$seclevel, 'course' ],
12621: [$courselevelr,'resource']));
12622: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12623:
1.60 www 12624: # ------------------------------------------------------ third, check map parms
1.218 albertel 12625: my %parmhash=();
12626: my $thisparm='';
12627: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12628: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12629: &GDBM_READER(),0640)) {
1.218 albertel 12630: $thisparm=$parmhash{$symbparm};
12631: untie(%parmhash);
12632: }
1.927 albertel 12633: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12634: }
1.594 albertel 12635: # ------------------------------------------ fourth, look in resource metadata
1.71 www 12636:
1.1172.2.146. .13(raeb 12637:-23): my $what = $spacequalifierrest;
12638:-23): $what=~s/\./\_/;
12639:-23): my $filename;
1.282 albertel 12640: if (!$symbparm) { $symbparm=&symbread(); }
12641: if ($symbparm) {
1.409 www 12642: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12643: } else {
1.620 albertel 12644: $filename=$env{'request.filename'};
1.282 albertel 12645: }
1.1172.2.146. .13(raeb 12646:-23): my $toolsymb;
12647:-23): if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12648:-23): $toolsymb = $symbparm;
12649:-23): }
12650:-23): my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12651: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146. .13(raeb 12652:-23): $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12653: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12654:
1.1172.2.146. .13(raeb 12655:-23): # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12656: if ($symbparm && defined($courseid) &&
1.620 albertel 12657: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12658: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12659: $env{'course.'.$courseid.'.domain'},
12660: 'course',
1.927 albertel 12661: ([$courselevelm,'map' ],
12662: [$courselevel, 'course']));
12663: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12664: }
1.145 www 12665: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12666: unless ($space eq '0') {
1.336 albertel 12667: my @parts=split(/_/,$space);
12668: my $id=pop(@parts);
12669: my $part=join('_',@parts);
12670: if ($part eq '') { $part='0'; }
1.927 albertel 12671: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12672: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12673: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12674: }
1.395 albertel 12675: if ($recurse) { return undef; }
1.1172.2.146. .13(raeb 12676:-23): my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12677: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12678: # ---------------------------------------------------- Any other user namespace
12679: } elsif ($realm eq 'environment') {
12680: # ----------------------------------------------------------------- environment
1.620 albertel 12681: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12682: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12683: } else {
1.770 albertel 12684: if ($uname eq 'anonymous' && $udom eq '') {
12685: return '';
12686: }
1.219 albertel 12687: my %returnhash=&userenvironment($udom,$uname,
12688: $spacequalifierrest);
12689: return $returnhash{$spacequalifierrest};
12690: }
1.28 www 12691: } elsif ($realm eq 'system') {
1.48 www 12692: # ----------------------------------------------------------------- system.time
12693: if ($space eq 'time') {
12694: return time;
12695: }
1.696 albertel 12696: } elsif ($realm eq 'server') {
12697: # ----------------------------------------------------------------- system.time
12698: if ($space eq 'name') {
12699: return $ENV{'SERVER_NAME'};
12700: }
1.1172.2.146. .1(raebu 12701:22): } elsif ($realm eq 'client') {
12702:22): if ($space eq 'remote_addr') {
12703:22): return &get_requestor_ip();
12704:22): }
1.28 www 12705: }
1.48 www 12706: return '';
1.61 www 12707: }
12708:
1.927 albertel 12709: sub get_reply {
12710: my ($reply_value) = @_;
1.940 raeburn 12711: if (ref($reply_value) eq 'ARRAY') {
12712: if (wantarray) {
12713: return @$reply_value;
12714: }
12715: return $reply_value->[0];
12716: } else {
12717: return $reply_value;
1.927 albertel 12718: }
12719: }
12720:
1.691 raeburn 12721: sub check_group_parms {
12722: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
12723: my @groupitems = ();
12724: my $resultitem;
1.927 albertel 12725: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 12726: foreach my $group (@{$groups}) {
12727: foreach my $level (@levels) {
1.927 albertel 12728: my $item = $courseid.'.['.$group.'].'.$level->[0];
12729: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12730: }
12731: }
12732: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12733: $env{'course.'.$courseid.'.domain'},
12734: 'course',@groupitems);
12735: return $coursereply;
12736: }
12737:
1.1172.2.146. .1(raebu 12738:22): sub get_map_hierarchy {
12739:22): my ($mapname,$courseid) = @_;
12740:22): my @recurseup = ();
12741:22): if ($mapname) {
12742:22): if (($cachedmapkey eq $courseid) &&
12743:22): (abs($cachedmaptime-time)<5)) {
12744:22): if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12745:22): return @{$cachedmaps{$mapname}};
12746:22): }
12747:22): }
12748:22): my $navmap = Apache::lonnavmaps::navmap->new();
12749:22): if (ref($navmap)) {
12750:22): @recurseup = $navmap->recurseup_maps($mapname);
12751:22): undef($navmap);
12752:22): $cachedmaps{$mapname} = \@recurseup;
12753:22): $cachedmaptime=time;
12754:22): $cachedmapkey=$courseid;
12755:22): }
12756:22): }
12757:22): return @recurseup;
12758:22): }
12759:22):
.2(raebu 12760:22): }
.1(raebu 12761:22):
1.691 raeburn 12762: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12763: my ($courseid,@groups) = @_;
12764: @groups = sort(@groups);
1.691 raeburn 12765: return @groups;
12766: }
12767:
1.395 albertel 12768: sub packages_tab_default {
1.1172.2.146. .13(raeb 12769:-23): my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12770: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12771:
12772: my (@extension,@specifics,$do_default);
1.1172.2.146. .13(raeb 12773:-23): foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12774: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12775: if ($pack_type eq 'default') {
12776: $do_default=1;
12777: } elsif ($pack_type eq 'extension') {
12778: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12779: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12780: # only look at packages defaults for packages that this id is
1.738 albertel 12781: push(@specifics,[$package,$pack_type,$pack_part]);
12782: }
12783: }
12784: # first look for a package that matches the requested part id
12785: foreach my $package (@specifics) {
12786: my (undef,$pack_type,$pack_part)=@{$package};
12787: next if ($pack_part ne $part);
12788: if (defined($packagetab{"$pack_type&$name&default"})) {
12789: return $packagetab{"$pack_type&$name&default"};
12790: }
12791: }
12792: # look for any possible matching non extension_ package
12793: foreach my $package (@specifics) {
12794: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12795: if (defined($packagetab{"$pack_type&$name&default"})) {
12796: return $packagetab{"$pack_type&$name&default"};
12797: }
1.585 albertel 12798: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12799: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12800: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12801: }
12802: }
1.738 albertel 12803: # look for any posible extension_ match
12804: foreach my $package (@extension) {
12805: my ($package,$pack_type)=@{$package};
12806: if (defined($packagetab{"$pack_type&$name&default"})) {
12807: return $packagetab{"$pack_type&$name&default"};
12808: }
12809: if (defined($packagetab{$package."&$name&default"})) {
12810: return $packagetab{$package."&$name&default"};
12811: }
12812: }
12813: # look for a global default setting
12814: if ($do_default && defined($packagetab{"default&$name&default"})) {
12815: return $packagetab{"default&$name&default"};
12816: }
1.395 albertel 12817: return undef;
12818: }
12819:
1.334 albertel 12820: sub add_prefix_and_part {
12821: my ($prefix,$part)=@_;
12822: my $keyroot;
12823: if (defined($prefix) && $prefix !~ /^__/) {
12824: # prefix that has a part already
12825: $keyroot=$prefix;
12826: } elsif (defined($prefix)) {
12827: # prefix that is missing a part
12828: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12829: } else {
12830: # no prefix at all
12831: if (defined($part)) { $keyroot='_'.$part; }
12832: }
12833: return $keyroot;
12834: }
12835:
1.71 www 12836: # ---------------------------------------------------------------- Get metadata
12837:
1.599 albertel 12838: my %metaentry;
1.1070 www 12839: my %importedpartids;
1.1172.2.99 raeburn 12840: my %importedrespids;
1.71 www 12841: sub metadata {
1.1172.2.146. .13(raeb 12842:-23): my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12843: $uri=&declutter($uri);
1.288 albertel 12844: # if it is a non metadata possible uri return quickly
1.529 albertel 12845: if (($uri eq '') ||
12846: (($uri =~ m|^/*adm/|) &&
1.1172.2.146. .1(raebu 12847:22): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12848: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12849: return undef;
12850: }
1.1172.2.49 raeburn 12851: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12852: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12853: return undef;
1.288 albertel 12854: }
1.73 www 12855: my $filename=$uri;
12856: $uri=~s/\.meta$//;
1.172 www 12857: #
12858: # Is the metadata already cached?
1.177 www 12859: # Look at timestamp of caching
1.172 www 12860: # Everything is cached by the main uri, libraries are never directly cached
12861: #
1.428 albertel 12862: if (!defined($liburi)) {
1.599 albertel 12863: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12864: if (defined($cached)) { return $result->{':'.$what}; }
12865: }
1.1172.2.146. .13(raeb 12866:-23):
12867:-23): #
12868:-23): # If the uri is for an external tool the file from
12869:-23): # which metadata should be retrieved depends on whether
12870:-23): # the tool had been configured to be gradable (set in the Course
12871:-23): # Editor or Resource Editor).
12872:-23): #
12873:-23): # If a valid symb has been included as the third arg in the call
12874:-23): # to &metadata() that can be used to retrieve the value of
12875:-23): # parameter_0_gradable set for the resource, and included in the
12876:-23): # uploaded map containing the tool. The value is retrieved via
12877:-23): # &EXT(), if a valid symb is available. Otherwise the value of
12878:-23): # gradable in the exttool_$marker.db file for the tool instance
12879:-23): # is retrieved via &get().
12880:-23): #
12881:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
12882:-23): # hiddenresource and encrypturl (during course initialization)
12883:-23): # the map-level parameter for resource.0.gradable included in the
12884:-23): # uploaded map containing the tool will not yet have been stored
12885:-23): # in the user_course_parms.db file for the user's session, so in
12886:-23): # this case fall back to retrieving gradable status from the
12887:-23): # exttool_$marker.db file.
12888:-23): #
12889:-23): # In order to avoid an infinite loop, &metadata() will return
12890:-23): # before a call to &EXT(), if the uri is for an external tool
12891:-23): # and the $what for which metadata is being requested is
12892:-23): # parameter_0_gradable or 0_gradable.
12893:-23): #
12894:-23):
12895:-23): if ($uri =~ /ext\.tool$/) {
12896:-23): if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12897:-23): return;
12898:-23): } else {
12899:-23): my ($checked,$use_passback);
12900:-23): if ($toolsymb ne '') {
12901:-23): (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12902:-23): if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12903:-23): $checked = 1;
12904:-23): if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12905:-23): $use_passback = 1;
12906:-23): }
12907:-23): }
12908:-23): }
12909:-23): unless ($checked) {
12910:-23): my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12911:-23): $marker=~s/\D//g;
12912:-23): if ($marker) {
12913:-23): my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12914:-23): $use_passback = $toolsettings{'gradable'};
12915:-23): }
12916:-23): }
12917:-23): if ($use_passback) {
12918:-23): $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12919:-23): } else {
12920:-23): $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12921:-23): }
12922:-23): }
12923:-23): }
12924:-23):
1.428 albertel 12925: {
1.1069 www 12926: # Imported parts would go here
1.1172.2.99 raeburn 12927: my @origfiletagids=();
1.1069 www 12928: my $importedparts=0;
1.1172.2.99 raeburn 12929:
12930: # Imported responseids would go here
12931: my $importedresponses=0;
1.172 www 12932: #
12933: # Is this a recursive call for a library?
12934: #
1.599 albertel 12935: # if (! exists($metacache{$uri})) {
12936: # $metacache{$uri}={};
12937: # }
1.924 albertel 12938: my $cachetime = 60*60;
1.171 www 12939: if ($liburi) {
12940: $liburi=&declutter($liburi);
12941: $filename=$liburi;
1.401 bowersj2 12942: } else {
1.599 albertel 12943: &devalidate_cache_new('meta',$uri);
12944: undef(%metaentry);
1.401 bowersj2 12945: }
1.140 www 12946: my %metathesekeys=();
1.73 www 12947: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12948: my $metastring;
1.1140 www 12949: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12950: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12951: $metastring =
1.929 albertel 12952: &Apache::lonnet::ssi_body($which,
1.924 albertel 12953: ('grade_target' => 'meta'));
12954: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12955: } elsif (($uri !~ m -^(editupload)/-) &&
12956: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12957: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12958: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12959: $metastring=&getfile($file);
1.489 albertel 12960: }
1.208 albertel 12961: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12962: my $token;
1.140 www 12963: undef %metathesekeys;
1.71 www 12964: while ($token=$parser->get_token) {
1.339 albertel 12965: if ($token->[0] eq 'S') {
12966: if (defined($token->[2]->{'package'})) {
1.172 www 12967: #
12968: # This is a package - get package info
12969: #
1.339 albertel 12970: my $package=$token->[2]->{'package'};
12971: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12972: if (defined($token->[2]->{'id'})) {
12973: $keyroot.='_'.$token->[2]->{'id'};
12974: }
1.599 albertel 12975: if ($metaentry{':packages'}) {
12976: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12977: } else {
1.599 albertel 12978: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12979: }
1.736 albertel 12980: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12981: my $part=$keyroot;
12982: $part=~s/^\_//;
1.736 albertel 12983: if ($pack_entry=~/^\Q$package\E\&/ ||
12984: $pack_entry=~/^\Q$package\E_0\&/) {
12985: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12986: # ignore package.tab specified default values
12987: # here &package_tab_default() will fetch those
12988: if ($subp eq 'default') { next; }
1.736 albertel 12989: my $value=$packagetab{$pack_entry};
1.432 albertel 12990: my $unikey;
12991: if ($pack =~ /_0$/) {
12992: $unikey='parameter_0_'.$name;
12993: $part=0;
12994: } else {
12995: $unikey='parameter'.$keyroot.'_'.$name;
12996: }
1.339 albertel 12997: if ($subp eq 'display') {
12998: $value.=' [Part: '.$part.']';
12999: }
1.599 albertel 13000: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13001: $metathesekeys{$unikey}=1;
1.599 albertel 13002: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13003: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13004: }
1.599 albertel 13005: if (defined($metaentry{':'.$unikey.'.default'})) {
13006: $metaentry{':'.$unikey}=
13007: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13008: }
1.339 albertel 13009: }
13010: }
13011: } else {
1.172 www 13012: #
13013: # This is not a package - some other kind of start tag
1.339 albertel 13014: #
13015: my $entry=$token->[1];
1.1068 www 13016: my $unikey='';
1.175 www 13017:
1.339 albertel 13018: if ($entry eq 'import') {
1.175 www 13019: #
13020: # Importing a library here
1.339 albertel 13021: #
1.1067 www 13022: my $location=$parser->get_text('/import');
13023: my $dir=$filename;
13024: $dir=~s|[^/]*$||;
13025: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 13026:
13027: my $importid=$token->[2]->{'id'};
1.1068 www 13028: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 13029: #
13030: # Check metadata for imported file to
13031: # see if it contained response items
13032: #
13033: my %currmetaentry = %metaentry;
13034: my $libresponseorder = &metadata($location,'responseorder');
13035: my $origfile;
13036: if ($libresponseorder ne '') {
13037: if ($#origfiletagids<0) {
13038: undef(%importedrespids);
13039: undef(%importedpartids);
13040: }
13041: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
13042: if (@{$importedrespids{$importid}} > 0) {
13043: $importedresponses = 1;
13044: # We need to get the original file and the imported file to get the response order correct
13045: # Load and inspect original file
13046: if ($#origfiletagids<0) {
13047: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13048: $origfile=&getfile($origfilelocation);
13049: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13050: }
13051: }
13052: }
13053: # Do not overwrite contents of %metaentry hash for resource itself with
13054: # hash populated for imported library file
13055: %metaentry = %currmetaentry;
13056: undef(%currmetaentry);
1.1068 www 13057: if ($importmode eq 'problem') {
1.1069 www 13058: # Import as problem/response
1.1068 www 13059: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13060: } elsif ($importmode eq 'part') {
13061: # Import as part(s)
1.1069 www 13062: $importedparts=1;
13063: # We need to get the original file and the imported file to get the part order correct
13064: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 13065: # Load and inspect original file if we didn't do that already
13066: if ($#origfiletagids<0) {
13067: undef(%importedrespids);
13068: undef(%importedpartids);
13069: if ($origfile eq '') {
13070: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13071: $origfile=&getfile($origfilelocation);
13072: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13073: }
1.1070 www 13074: }
13075:
1.1069 www 13076: # Load and inspect imported file
13077: my $impfile=&getfile($location);
13078: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13079: if ($#impfilepartids>=0) {
13080: # This problem had parts
1.1070 www 13081: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13082: } else {
13083: # Importing by turning a single problem into a problem part
13084: # It gets the import-tags ID as part-ID
13085: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13086: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13087: }
1.1068 www 13088: } else {
13089: # Normal import
13090: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13091: if (defined($token->[2]->{'id'})) {
13092: $unikey.='_'.$token->[2]->{'id'};
13093: }
1.1067 www 13094: }
13095:
1.339 albertel 13096: if ($depthcount<20) {
1.736 albertel 13097: my $metadata =
1.1172.2.146. .13(raeb 13098:-23): &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13099: $depthcount+1);
13100: foreach my $meta (split(',',$metadata)) {
13101: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13102: $metathesekeys{$meta}=1;
1.339 albertel 13103: }
1.1068 www 13104:
13105: }
1.1067 www 13106: } else {
13107: #
13108: # Not importing, some other kind of non-package, non-library start tag
13109: #
13110: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13111: if (defined($token->[2]->{'id'})) {
13112: $unikey.='_'.$token->[2]->{'id'};
13113: }
1.339 albertel 13114: if (defined($token->[2]->{'name'})) {
13115: $unikey.='_'.$token->[2]->{'name'};
13116: }
13117: $metathesekeys{$unikey}=1;
1.736 albertel 13118: foreach my $param (@{$token->[3]}) {
13119: $metaentry{':'.$unikey.'.'.$param} =
13120: $token->[2]->{$param};
1.339 albertel 13121: }
13122: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13123: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13124: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13125: # only ws inside the tag, and not in default, so use default
13126: # as value
1.599 albertel 13127: $metaentry{':'.$unikey}=$default;
1.908 albertel 13128: } elsif ( $internaltext =~ /\S/ ) {
13129: # something interesting inside the tag
13130: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13131: } else {
1.908 albertel 13132: # no interesting values, don't set a default
1.339 albertel 13133: }
1.172 www 13134: # end of not-a-package not-a-library import
1.339 albertel 13135: }
1.172 www 13136: # end of not-a-package start tag
1.339 albertel 13137: }
1.172 www 13138: # the next is the end of "start tag"
1.339 albertel 13139: }
13140: }
1.483 albertel 13141: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13142: $extension = lc($extension);
13143: if ($extension eq 'htm') { $extension='html'; }
13144:
1.737 albertel 13145: foreach my $key (keys(%packagetab)) {
1.483 albertel 13146: #no specific packages #how's our extension
13147: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13148: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13149: \%metathesekeys);
13150: }
1.883 albertel 13151:
13152: if (!exists($metaentry{':packages'})
13153: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13154: foreach my $key (keys(%packagetab)) {
1.483 albertel 13155: #no specific packages well let's get default then
13156: if ($key!~/^default&/) { next; }
1.488 albertel 13157: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13158: \%metathesekeys);
13159: }
13160: }
1.338 www 13161: # are there custom rights to evaluate
1.599 albertel 13162: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13163:
1.338 www 13164: #
13165: # Importing a rights file here
1.339 albertel 13166: #
13167: unless ($depthcount) {
1.599 albertel 13168: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13169: my $dir=$filename;
13170: $dir=~s|[^/]*$||;
13171: $location=&filelocation($dir,$location);
1.736 albertel 13172: my $rights_metadata =
1.1172.2.146. .13(raeb 13173:-23): &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13174: $depthcount+1);
13175: foreach my $rights (split(',',$rights_metadata)) {
13176: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13177: $metathesekeys{$rights}=1;
1.339 albertel 13178: }
13179: }
13180: }
1.737 albertel 13181: # uniqifiy package listing
13182: my %seen;
13183: my @uniq_packages =
13184: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13185: $metaentry{':packages'} = join(',',@uniq_packages);
13186:
1.1172.2.99 raeburn 13187: if (($importedresponses) || ($importedparts)) {
13188: if ($importedparts) {
1.1070 www 13189: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 13190: $metaentry{':partorder'}='';
13191: $metathesekeys{'partorder'}=1;
13192: }
13193: if ($importedresponses) {
13194: # We had imported responses and need to rebuild responseorder
13195: $metaentry{':responseorder'}='';
13196: $metathesekeys{'responseorder'}=1;
13197: }
13198: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13199: my $origid = $origfiletagids[$index+1];
13200: if ($origfiletagids[$index] eq 'part') {
13201: # Original part, part of the problem
13202: if ($importedparts) {
13203: $metaentry{':partorder'}.=','.$origid;
13204: }
13205: } elsif ($origfiletagids[$index] eq 'import') {
13206: if ($importedparts) {
13207: # We have imported parts at this position
13208: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13209: }
13210: if ($importedresponses) {
13211: # We have imported responses at this position
13212: if (ref($importedrespids{$origid}) eq 'ARRAY') {
13213: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
13214: }
13215: }
13216: } else {
13217: # Original response item, part of the problem
13218: if ($importedresponses) {
13219: $metaentry{':responseorder'}.=','.$origid;
13220: }
13221: }
13222: }
13223: if ($importedparts) {
13224: $metaentry{':partorder'}=~s/^\,//;
13225: }
13226: if ($importedresponses) {
13227: $metaentry{':responseorder'}=~s/^\,//;
13228: }
1.1070 www 13229: }
13230:
1.737 albertel 13231: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13232: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 13233: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 13234: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 13235: # this is the end of "was not already recently cached
1.71 www 13236: }
1.599 albertel 13237: return $metaentry{':'.$what};
1.261 albertel 13238: }
13239:
1.488 albertel 13240: sub metadata_create_package_def {
1.483 albertel 13241: my ($uri,$key,$package,$metathesekeys)=@_;
13242: my ($pack,$name,$subp)=split(/\&/,$key);
13243: if ($subp eq 'default') { next; }
13244:
1.599 albertel 13245: if (defined($metaentry{':packages'})) {
13246: $metaentry{':packages'}.=','.$package;
1.483 albertel 13247: } else {
1.599 albertel 13248: $metaentry{':packages'}=$package;
1.483 albertel 13249: }
13250: my $value=$packagetab{$key};
13251: my $unikey;
13252: $unikey='parameter_0_'.$name;
1.599 albertel 13253: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13254: $$metathesekeys{$unikey}=1;
1.599 albertel 13255: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13256: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13257: }
1.599 albertel 13258: if (defined($metaentry{':'.$unikey.'.default'})) {
13259: $metaentry{':'.$unikey}=
13260: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13261: }
13262: }
13263:
1.261 albertel 13264: sub metadata_generate_part0 {
13265: my ($metadata,$metacache,$uri) = @_;
13266: my %allnames;
1.737 albertel 13267: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13268: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13269: my $part=$$metacache{':'.$metakey.'.part'};
13270: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13271: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13272: $allnames{$name}=$part;
13273: }
13274: }
13275: }
13276: foreach my $name (keys(%allnames)) {
13277: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13278: my $key=":parameter_0_$name";
1.261 albertel 13279: $$metacache{"$key.part"}='0';
13280: $$metacache{"$key.name"}=$name;
1.428 albertel 13281: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13282: $allnames{$name}.'_'.$name.
13283: '.type'};
1.428 albertel 13284: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13285: '.display'};
1.644 www 13286: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13287: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13288: $$metacache{"$key.display"}=$olddis;
13289: }
1.71 www 13290: }
13291:
1.764 albertel 13292: # ------------------------------------------------------ Devalidate title cache
13293:
13294: sub devalidate_title_cache {
13295: my ($url)=@_;
13296: if (!$env{'request.course.id'}) { return; }
13297: my $symb=&symbread($url);
13298: if (!$symb) { return; }
13299: my $key=$env{'request.course.id'}."\0".$symb;
13300: &devalidate_cache_new('title',$key);
13301: }
13302:
1.1014 droeschl 13303: # ------------------------------------------------- Get the title of a course
13304:
13305: sub current_course_title {
13306: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13307: }
1.301 www 13308: # ------------------------------------------------- Get the title of a resource
13309:
13310: sub gettitle {
13311: my $urlsymb=shift;
13312: my $symb=&symbread($urlsymb);
1.534 albertel 13313: if ($symb) {
1.620 albertel 13314: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13315: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13316: if (defined($cached)) {
13317: return $result;
13318: }
1.534 albertel 13319: my ($map,$resid,$url)=&decode_symb($symb);
13320: my $title='';
1.907 albertel 13321: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13322: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13323: } else {
13324: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13325: &GDBM_READER(),0640)) {
13326: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13327: $title=$bighash{'title_'.$mapid.'.'.$resid};
13328: untie(%bighash);
13329: }
1.534 albertel 13330: }
13331: $title=~s/\&colon\;/\:/gs;
13332: if ($title) {
1.1159 www 13333: # Remember both $symb and $title for dynamic metadata
13334: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13335: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13336: # Cache this title and then return it
1.599 albertel 13337: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13338: }
13339: $urlsymb=$url;
13340: }
13341: my $title=&metadata($urlsymb,'title');
13342: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13343: return $title;
1.301 www 13344: }
1.613 albertel 13345:
1.614 albertel 13346: sub get_slot {
13347: my ($which,$cnum,$cdom)=@_;
13348: if (!$cnum || !$cdom) {
1.790 albertel 13349: (undef,my $courseid)=&whichuser();
1.620 albertel 13350: $cdom=$env{'course.'.$courseid.'.domain'};
13351: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13352: }
1.703 albertel 13353: my $key=join("\0",'slots',$cdom,$cnum,$which);
13354: my %slotinfo;
13355: if (exists($remembered{$key})) {
13356: $slotinfo{$which} = $remembered{$key};
13357: } else {
13358: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13359: &Apache::lonhomework::showhash(%slotinfo);
13360: my ($tmp)=keys(%slotinfo);
13361: if ($tmp=~/^error:/) { return (); }
13362: $remembered{$key} = $slotinfo{$which};
13363: }
1.616 albertel 13364: if (ref($slotinfo{$which}) eq 'HASH') {
13365: return %{$slotinfo{$which}};
13366: }
13367: return $slotinfo{$which};
1.614 albertel 13368: }
1.1150 raeburn 13369:
13370: sub get_reservable_slots {
13371: my ($cnum,$cdom,$uname,$udom) = @_;
13372: my $now = time;
13373: my $reservable_info;
13374: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13375: if (exists($remembered{$key})) {
13376: $reservable_info = $remembered{$key};
13377: } else {
13378: my %resv;
13379: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13380: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13381: $reservable_info = \%resv;
13382: $remembered{$key} = $reservable_info;
13383: }
13384: return $reservable_info;
13385: }
13386:
13387: sub get_course_slots {
13388: my ($cnum,$cdom) = @_;
13389: my $hashid=$cnum.':'.$cdom;
13390: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13391: if (defined($cached)) {
13392: if (ref($result) eq 'HASH') {
13393: return %{$result};
13394: }
13395: } else {
13396: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13397: my ($tmp) = keys(%slots);
13398: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 13399: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13400: return %slots;
13401: }
13402: }
13403: return;
13404: }
13405:
13406: sub devalidate_slots_cache {
13407: my ($cnum,$cdom)=@_;
13408: my $hashid=$cnum.':'.$cdom;
13409: &devalidate_cache_new('allslots',$hashid);
13410: }
13411:
1.1172.2.8 raeburn 13412: sub get_coursechange {
13413: my ($cdom,$cnum) = @_;
13414: if ($cdom eq '' || $cnum eq '') {
13415: return unless ($env{'request.course.id'});
13416: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13417: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13418: }
13419: my $hashid=$cdom.'_'.$cnum;
13420: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13421: if ((defined($cached)) && ($change ne '')) {
13422: return $change;
13423: } else {
13424: my %crshash;
13425: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13426: if ($crshash{'internal.contentchange'} eq '') {
13427: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13428: if ($change eq '') {
13429: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13430: $change = $crshash{'internal.created'};
13431: }
13432: } else {
13433: $change = $crshash{'internal.contentchange'};
13434: }
13435: my $cachetime = 600;
13436: &do_cache_new('crschange',$hashid,$change,$cachetime);
13437: }
13438: return $change;
13439: }
13440:
13441: sub devalidate_coursechange_cache {
1.1172.2.146. .9(raebu 13442:23): my ($cdom,$cnum)=@_;
13443:23): my $hashid=$cdom.'_'.$cnum;
1.1172.2.8 raeburn 13444: &devalidate_cache_new('crschange',$hashid);
13445: }
13446:
1.1172.2.146. .9(raebu 13447:23): sub get_suppchange {
13448:23): my ($cdom,$cnum) = @_;
13449:23): if ($cdom eq '' || $cnum eq '') {
13450:23): return unless ($env{'request.course.id'});
13451:23): $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13452:23): $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13453:23): }
13454:23): my $hashid=$cdom.'_'.$cnum;
13455:23): my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13456:23): if ((defined($cached)) && ($change ne '')) {
13457:23): return $change;
13458:23): } else {
13459:23): my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13460:23): if ($crshash{'internal.supplementalchange'} eq '') {
13461:23): $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13462:23): if ($change eq '') {
13463:23): %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13464:23): $change = $crshash{'internal.created'};
13465:23): }
13466:23): } else {
13467:23): $change = $crshash{'internal.supplementalchange'};
13468:23): }
13469:23): my $cachetime = 600;
13470:23): &do_cache_new('suppchange',$hashid,$change,$cachetime);
13471:23): }
13472:23): return $change;
13473:23): }
13474:23):
13475:23): sub devalidate_suppchange_cache {
13476:23): my ($cdom,$cnum)=@_;
13477:23): my $hashid=$cdom.'_'.$cnum;
13478:23): &devalidate_cache_new('suppchange',$hashid);
13479:23): }
13480:23):
13481:23): sub update_supp_caches {
13482:23): my ($cdom,$cnum) = @_;
13483:23): my %servers = &internet_dom_servers($cdom);
13484:23): my @ids=¤t_machine_ids();
13485:23): foreach my $server (keys(%servers)) {
13486:23): next if (grep(/^\Q$server\E$/,@ids));
13487:23): my $hashid=$cnum.':'.$cdom;
13488:23): my $cachekey = &escape('showsupp').':'.&escape($hashid);
13489:23): &remote_devalidate_cache($server,[$cachekey]);
13490:23): }
13491:23): &has_unhidden_suppfiles($cnum,$cdom,1,1);
13492:23): &count_supptools($cnum,$cdom,1);
13493:23): my $now = time;
13494:23): if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13495:23): &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13496:23): }
13497:23): &put('environment',{'internal.supplementalchange' => $now},
13498:23): $cdom,$cnum);
13499:23): &Apache::lonnet::appenv(
13500:23): {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13501:23): &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13502:23): }
13503:23):
1.31 www 13504: # ------------------------------------------------- Update symbolic store links
13505:
13506: sub symblist {
13507: my ($mapname,%newhash)=@_;
1.438 www 13508: $mapname=&deversion(&declutter($mapname));
1.31 www 13509: my %hash;
1.620 albertel 13510: if (($env{'request.course.fn'}) && (%newhash)) {
13511: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13512: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13513: foreach my $url (keys(%newhash)) {
1.711 albertel 13514: next if ($url eq 'last_known'
13515: && $env{'form.no_update_last_known'});
13516: $hash{declutter($url)}=&encode_symb($mapname,
13517: $newhash{$url}->[1],
13518: $newhash{$url}->[0]);
1.191 harris41 13519: }
1.31 www 13520: if (untie(%hash)) {
13521: return 'ok';
13522: }
13523: }
13524: }
13525: return 'error';
1.212 www 13526: }
13527:
13528: # --------------------------------------------------------------- Verify a symb
13529:
13530: sub symbverify {
1.1172.2.11 raeburn 13531: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13532: my $thisfn=$thisurl;
1.439 www 13533: $thisfn=&declutter($thisfn);
1.215 www 13534: # direct jump to resource in page or to a sequence - will construct own symbs
13535: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13536: # check URL part
1.409 www 13537: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13538:
1.431 www 13539: unless ($url eq $thisfn) { return 0; }
1.213 www 13540:
1.216 www 13541: $symb=&symbclean($symb);
1.510 www 13542: $thisurl=&deversion($thisurl);
1.439 www 13543: $thisfn=&deversion($thisfn);
1.213 www 13544:
13545: my %bighash;
13546: my $okay=0;
1.431 www 13547:
1.620 albertel 13548: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13549: &GDBM_READER(),0640)) {
1.1032 raeburn 13550: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13551: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 13552: if ($map =~ m{^uploaded/.+\.page$}) {
13553: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13554: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13555: }
13556: }
13557: my $ids;
1.1172.2.122 raeburn 13558: if ($map =~ m{^uploaded/.+\.page$}) {
13559: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 13560: } else {
13561: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13562: }
1.1102 raeburn 13563: unless ($ids) {
1.1172.2.13 raeburn 13564: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 13565: $ids=$bighash{$idkey};
1.216 www 13566: }
13567: if ($ids) {
13568: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 13569: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13570: $symb =~ s/\?.+$//;
13571: }
1.800 albertel 13572: foreach my $id (split(/\,/,$ids)) {
13573: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13574: if (
13575: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 13576: eq $symb) {
1.1172.2.11 raeburn 13577: if (ref($encstate)) {
13578: $$encstate = $bighash{'encrypted_'.$id};
13579: }
1.1172.2.13 raeburn 13580: if (($env{'request.role.adv'}) ||
13581: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 13582: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 13583: $okay=1;
13584: last;
13585: }
13586: }
13587: }
1.216 www 13588: }
1.213 www 13589: untie(%bighash);
13590: }
13591: return $okay;
1.31 www 13592: }
13593:
1.210 www 13594: # --------------------------------------------------------------- Clean-up symb
13595:
13596: sub symbclean {
13597: my $symb=shift;
1.568 albertel 13598: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13599: # remove version from map
13600: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13601:
1.210 www 13602: # remove version from URL
13603: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13604:
1.507 www 13605: # remove wrapper
13606:
1.510 www 13607: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13608: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13609: return $symb;
1.409 www 13610: }
13611:
13612: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13613:
13614: sub encode_symb {
13615: my ($map,$resid,$url)=@_;
13616: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13617: }
1.409 www 13618:
13619: sub decode_symb {
1.568 albertel 13620: my $symb=shift;
13621: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13622: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13623: return (&fixversion($map),$resid,&fixversion($url));
13624: }
13625:
13626: sub fixversion {
13627: my $fn=shift;
1.609 banghart 13628: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13629: my %bighash;
13630: my $uri=&clutter($fn);
1.620 albertel 13631: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13632: # is this cached?
1.599 albertel 13633: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13634: if (defined($cached)) { return $result; }
13635: # unfortunately not cached, or expired
1.620 albertel 13636: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13637: &GDBM_READER(),0640)) {
13638: if ($bighash{'version_'.$uri}) {
13639: my $version=$bighash{'version_'.$uri};
1.444 www 13640: unless (($version eq 'mostrecent') ||
13641: ($version==&getversion($uri))) {
1.440 www 13642: $uri=~s/\.(\w+)$/\.$version\.$1/;
13643: }
13644: }
13645: untie %bighash;
1.413 www 13646: }
1.599 albertel 13647: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13648: }
13649:
13650: sub deversion {
13651: my $url=shift;
13652: $url=~s/\.\d+\.(\w+)$/\.$1/;
13653: return $url;
1.210 www 13654: }
13655:
1.31 www 13656: # ------------------------------------------------------ Return symb list entry
13657:
13658: sub symbread {
1.1172.2.126 raeburn 13659: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 13660: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 13661: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 13662: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 13663: unless (ref($possibles) eq 'HASH') {
13664: if ($ignorecachednull) {
13665: return $env{$cache_str} unless ($env{$cache_str} eq '');
13666: } else {
13667: return $env{$cache_str};
13668: }
1.1172.2.66 raeburn 13669: }
13670: }
1.242 www 13671: # no filename provided? try from environment
1.1172.2.54 raeburn 13672: unless ($thisfn) {
1.620 albertel 13673: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 13674: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 13675: }
13676: $thisfn=$env{'request.filename'};
1.44 www 13677: }
1.569 albertel 13678: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13679: # is that filename actually a symb? Verify, clean, and return
13680: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13681: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 13682: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13683: }
1.242 www 13684: }
1.44 www 13685: $thisfn=declutter($thisfn);
1.31 www 13686: my %hash;
1.37 www 13687: my %bighash;
13688: my $syval='';
1.620 albertel 13689: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128 raeburn 13690: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 13691: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13692: &GDBM_READER(),0640)) {
1.1172.2.146. .7(raebu 13693:22): $syval=$hash{$thisfn};
1.1172.2.126 raeburn 13694: untie(%hash);
13695: }
1.1172.2.128 raeburn 13696: if ($syval && $checkforblock) {
13697: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 13698: if (@blockers) {
13699: $syval='';
13700: }
13701: }
1.37 www 13702: }
13703: # ---------------------------------------------------------- There was an entry
13704: if ($syval) {
1.601 albertel 13705: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13706: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13707: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13708: #return $env{$cache_str}='';
1.601 albertel 13709: #}
13710: #$syval.=$1;
13711: #}
1.37 www 13712: } else {
13713: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13714: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13715: &GDBM_READER(),0640)) {
1.37 www 13716: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13717: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13718: unless ($ids) {
13719: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13720: }
13721: unless ($ids) {
13722: # alias?
13723: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13724: }
1.37 www 13725: if ($ids) {
13726: # ------------------------------------------------------------------- Has ID(s)
13727: my @possibilities=split(/\,/,$ids);
1.39 www 13728: if ($#possibilities==0) {
13729: # ----------------------------------------------- There is only one possibility
1.37 www 13730: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13731: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13732: $resid,$thisfn);
1.1172.2.66 raeburn 13733: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 13734: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13735: $possibles->{$syval} = 1;
13736: }
1.1172.2.66 raeburn 13737: }
13738: if ($checkforblock) {
1.1172.2.126 raeburn 13739: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 13740: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 13741: if (@blockers) {
13742: $syval = '';
13743: untie(%bighash);
13744: return $env{$cache_str}='';
13745: }
1.1172.2.66 raeburn 13746: }
13747: }
13748: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13749: # ------------------------------------------ There is more than one possibility
13750: my $realpossible=0;
1.800 albertel 13751: foreach my $id (@possibilities) {
13752: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 13753: my $canaccess;
13754: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13755: $canaccess = 1;
13756: } else {
13757: $canaccess = &allowed('bre',$file);
13758: }
13759: if ($canaccess) {
13760: my ($mapid,$resid)=split(/\./,$id);
13761: if ($bighash{'map_type_'.$mapid} ne 'page') {
13762: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13763: $resid,$thisfn);
1.1172.2.126 raeburn 13764: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 13765: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 13766: if ($checkforblock) {
1.1172.2.127 raeburn 13767: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 13768: if (@blockers > 0) {
13769: $syval = '';
13770: } else {
1.1172.2.66 raeburn 13771: $syval = $poss_syval;
13772: $realpossible++;
13773: }
13774: } else {
13775: $syval = $poss_syval;
13776: $realpossible++;
13777: }
1.1172.2.126 raeburn 13778: if ($syval) {
13779: if (ref($possibles) eq 'HASH') {
13780: $possibles->{$syval} = 1;
13781: }
13782: }
1.1172.2.66 raeburn 13783: }
1.39 www 13784: }
1.191 harris41 13785: }
1.39 www 13786: if ($realpossible!=1) { $syval=''; }
1.249 www 13787: } else {
13788: $syval='';
1.37 www 13789: }
13790: }
1.1172.2.66 raeburn 13791: untie(%bighash);
1.481 raeburn 13792: }
1.31 www 13793: }
1.62 www 13794: if ($syval) {
1.1172.2.128 raeburn 13795: return $env{$cache_str}=$syval;
1.62 www 13796: }
1.31 www 13797: }
1.949 raeburn 13798: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13799: return $env{$cache_str}='';
1.31 www 13800: }
13801:
13802: # ---------------------------------------------------------- Return random seed
13803:
1.32 www 13804: sub numval {
13805: my $txt=shift;
13806: $txt=~tr/A-J/0-9/;
13807: $txt=~tr/a-j/0-9/;
13808: $txt=~tr/K-T/0-9/;
13809: $txt=~tr/k-t/0-9/;
13810: $txt=~tr/U-Z/0-5/;
13811: $txt=~tr/u-z/0-5/;
13812: $txt=~s/\D//g;
1.564 albertel 13813: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13814: return int($txt);
1.368 albertel 13815: }
13816:
1.484 albertel 13817: sub numval2 {
13818: my $txt=shift;
13819: $txt=~tr/A-J/0-9/;
13820: $txt=~tr/a-j/0-9/;
13821: $txt=~tr/K-T/0-9/;
13822: $txt=~tr/k-t/0-9/;
13823: $txt=~tr/U-Z/0-5/;
13824: $txt=~tr/u-z/0-5/;
13825: $txt=~s/\D//g;
13826: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13827: my $total;
13828: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13829: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13830: return int($total);
13831: }
13832:
1.575 albertel 13833: sub numval3 {
13834: use integer;
13835: my $txt=shift;
13836: $txt=~tr/A-J/0-9/;
13837: $txt=~tr/a-j/0-9/;
13838: $txt=~tr/K-T/0-9/;
13839: $txt=~tr/k-t/0-9/;
13840: $txt=~tr/U-Z/0-5/;
13841: $txt=~tr/u-z/0-5/;
13842: $txt=~s/\D//g;
13843: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13844: my $total;
13845: foreach my $val (@txts) { $total+=$val; }
13846: if ($_64bit) { $total=(($total<<32)>>32); }
13847: return $total;
13848: }
13849:
1.675 albertel 13850: sub digest {
13851: my ($data)=@_;
13852: my $digest=&Digest::MD5::md5($data);
13853: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13854: my ($e,$f);
13855: {
13856: use integer;
13857: $e=($a+$b);
13858: $f=($c+$d);
13859: if ($_64bit) {
13860: $e=(($e<<32)>>32);
13861: $f=(($f<<32)>>32);
13862: }
13863: }
13864: if (wantarray) {
13865: return ($e,$f);
13866: } else {
13867: my $g;
13868: {
13869: use integer;
13870: $g=($e+$f);
13871: if ($_64bit) {
13872: $g=(($g<<32)>>32);
13873: }
13874: }
13875: return $g;
13876: }
13877: }
13878:
1.368 albertel 13879: sub latest_rnd_algorithm_id {
1.675 albertel 13880: return '64bit5';
1.366 albertel 13881: }
1.32 www 13882:
1.503 albertel 13883: sub get_rand_alg {
13884: my ($courseid)=@_;
1.790 albertel 13885: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13886: if ($courseid) {
1.620 albertel 13887: return $env{"course.$courseid.rndseed"};
1.503 albertel 13888: }
13889: return &latest_rnd_algorithm_id();
13890: }
13891:
1.562 albertel 13892: sub validCODE {
13893: my ($CODE)=@_;
13894: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13895: return 0;
13896: }
13897:
1.491 albertel 13898: sub getCODE {
1.620 albertel 13899: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13900: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13901: defined($Apache::lonhomework::parsing_a_task) ) &&
13902: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13903: return $Apache::lonhomework::history{'resource.CODE'};
13904: }
13905: return undef;
13906: }
1.1133 foxr 13907: #
13908: # Determines the random seed for a specific context:
13909: #
13910: # parameters:
13911: # symb - in course context the symb for the seed.
13912: # course_id - The course id of the form domain_coursenum.
13913: # domain - Domain for the user.
13914: # course - Course for the user.
13915: # cenv - environment of the course.
13916: #
13917: # NOTE:
13918: # All parameters are picked out of the environment if missing
13919: # or not defined.
13920: # If a symb cannot be determined the current time is used instead.
13921: #
13922: # For a given well defined symb, courside, domain, username,
13923: # and course environment, the seed is reproducible.
13924: #
1.31 www 13925: sub rndseed {
1.1133 foxr 13926: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13927: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13928: if (!defined($symb)) {
1.366 albertel 13929: unless ($symb=$wsymb) { return time; }
13930: }
1.1146 foxr 13931: if (!defined $courseid) {
13932: $courseid=$wcourseid;
13933: }
13934: if (!defined $domain) { $domain=$wdomain; }
13935: if (!defined $username) { $username=$wusername }
1.1133 foxr 13936:
13937: my $which;
13938: if (defined($cenv->{'rndseed'})) {
13939: $which = $cenv->{'rndseed'};
13940: } else {
13941: $which =&get_rand_alg($courseid);
13942: }
1.491 albertel 13943: if (defined(&getCODE())) {
1.675 albertel 13944: if ($which eq '64bit5') {
13945: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13946: } elsif ($which eq '64bit4') {
1.575 albertel 13947: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13948: } else {
13949: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13950: }
1.675 albertel 13951: } elsif ($which eq '64bit5') {
13952: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13953: } elsif ($which eq '64bit4') {
13954: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13955: } elsif ($which eq '64bit3') {
13956: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13957: } elsif ($which eq '64bit2') {
13958: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13959: } elsif ($which eq '64bit') {
13960: return &rndseed_64bit($symb,$courseid,$domain,$username);
13961: }
13962: return &rndseed_32bit($symb,$courseid,$domain,$username);
13963: }
13964:
13965: sub rndseed_32bit {
13966: my ($symb,$courseid,$domain,$username)=@_;
13967: {
13968: use integer;
13969: my $symbchck=unpack("%32C*",$symb) << 27;
13970: my $symbseed=numval($symb) << 22;
13971: my $namechck=unpack("%32C*",$username) << 17;
13972: my $nameseed=numval($username) << 12;
13973: my $domainseed=unpack("%32C*",$domain) << 7;
13974: my $courseseed=unpack("%32C*",$courseid);
13975: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13976: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13977: #&logthis("rndseed :$num:$symb");
1.564 albertel 13978: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13979: return $num;
13980: }
13981: }
13982:
13983: sub rndseed_64bit {
13984: my ($symb,$courseid,$domain,$username)=@_;
13985: {
13986: use integer;
13987: my $symbchck=unpack("%32S*",$symb) << 21;
13988: my $symbseed=numval($symb) << 10;
13989: my $namechck=unpack("%32S*",$username);
13990:
13991: my $nameseed=numval($username) << 21;
13992: my $domainseed=unpack("%32S*",$domain) << 10;
13993: my $courseseed=unpack("%32S*",$courseid);
13994:
13995: my $num1=$symbchck+$symbseed+$namechck;
13996: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13997: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13998: #&logthis("rndseed :$num:$symb");
1.564 albertel 13999: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14000: return "$num1,$num2";
1.155 albertel 14001: }
1.366 albertel 14002: }
14003:
1.443 albertel 14004: sub rndseed_64bit2 {
14005: my ($symb,$courseid,$domain,$username)=@_;
14006: {
14007: use integer;
14008: # strings need to be an even # of cahracters long, it it is odd the
14009: # last characters gets thrown away
14010: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14011: my $symbseed=numval($symb) << 10;
14012: my $namechck=unpack("%32S*",$username.' ');
14013:
14014: my $nameseed=numval($username) << 21;
1.501 albertel 14015: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14016: my $courseseed=unpack("%32S*",$courseid.' ');
14017:
14018: my $num1=$symbchck+$symbseed+$namechck;
14019: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14020: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14021: #&logthis("rndseed :$num:$symb");
1.803 albertel 14022: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14023: return "$num1,$num2";
14024: }
14025: }
14026:
14027: sub rndseed_64bit3 {
14028: my ($symb,$courseid,$domain,$username)=@_;
14029: {
14030: use integer;
14031: # strings need to be an even # of cahracters long, it it is odd the
14032: # last characters gets thrown away
14033: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14034: my $symbseed=numval2($symb) << 10;
14035: my $namechck=unpack("%32S*",$username.' ');
14036:
14037: my $nameseed=numval2($username) << 21;
1.443 albertel 14038: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14039: my $courseseed=unpack("%32S*",$courseid.' ');
14040:
14041: my $num1=$symbchck+$symbseed+$namechck;
14042: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14043: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14044: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14045: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14046:
1.503 albertel 14047: return "$num1:$num2";
1.443 albertel 14048: }
14049: }
14050:
1.575 albertel 14051: sub rndseed_64bit4 {
14052: my ($symb,$courseid,$domain,$username)=@_;
14053: {
14054: use integer;
14055: # strings need to be an even # of cahracters long, it it is odd the
14056: # last characters gets thrown away
14057: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14058: my $symbseed=numval3($symb) << 10;
14059: my $namechck=unpack("%32S*",$username.' ');
14060:
14061: my $nameseed=numval3($username) << 21;
14062: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14063: my $courseseed=unpack("%32S*",$courseid.' ');
14064:
14065: my $num1=$symbchck+$symbseed+$namechck;
14066: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14067: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14068: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14069: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14070:
1.575 albertel 14071: return "$num1:$num2";
14072: }
14073: }
14074:
1.675 albertel 14075: sub rndseed_64bit5 {
14076: my ($symb,$courseid,$domain,$username)=@_;
14077: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14078: return "$num1:$num2";
14079: }
14080:
1.366 albertel 14081: sub rndseed_CODE_64bit {
14082: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14083: {
1.366 albertel 14084: use integer;
1.443 albertel 14085: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14086: my $symbseed=numval2($symb);
1.491 albertel 14087: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14088: my $CODEseed=numval(&getCODE());
1.443 albertel 14089: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14090: my $num1=$symbseed+$CODEchck;
14091: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14092: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14093: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14094: if ($_64bit) { $num1=(($num1<<32)>>32); }
14095: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14096: return "$num1:$num2";
1.366 albertel 14097: }
14098: }
14099:
1.575 albertel 14100: sub rndseed_CODE_64bit4 {
14101: my ($symb,$courseid,$domain,$username)=@_;
14102: {
14103: use integer;
14104: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14105: my $symbseed=numval3($symb);
14106: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14107: my $CODEseed=numval3(&getCODE());
14108: my $courseseed=unpack("%32S*",$courseid.' ');
14109: my $num1=$symbseed+$CODEchck;
14110: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14111: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14112: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14113: if ($_64bit) { $num1=(($num1<<32)>>32); }
14114: if ($_64bit) { $num2=(($num2<<32)>>32); }
14115: return "$num1:$num2";
14116: }
14117: }
14118:
1.675 albertel 14119: sub rndseed_CODE_64bit5 {
14120: my ($symb,$courseid,$domain,$username)=@_;
14121: my $code = &getCODE();
14122: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14123: return "$num1:$num2";
14124: }
14125:
1.366 albertel 14126: sub setup_random_from_rndseed {
14127: my ($rndseed)=@_;
1.503 albertel 14128: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 14129: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14130: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14131: &Math::Random::random_set_seed_from_phrase($rndseed);
14132: } else {
14133: &Math::Random::random_set_seed($num1,$num2);
14134: }
1.366 albertel 14135: } else {
14136: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14137: }
1.36 albertel 14138: }
14139:
1.474 albertel 14140: sub latest_receipt_algorithm_id {
1.835 albertel 14141: return 'receipt3';
1.474 albertel 14142: }
14143:
1.480 www 14144: sub recunique {
14145: my $fucourseid=shift;
14146: my $unique;
1.835 albertel 14147: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14148: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14149: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14150: } else {
14151: $unique=$perlvar{'lonReceipt'};
14152: }
14153: return unpack("%32C*",$unique);
14154: }
14155:
14156: sub recprefix {
14157: my $fucourseid=shift;
14158: my $prefix;
1.835 albertel 14159: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14160: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14161: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14162: } else {
14163: $prefix=$perlvar{'lonHostID'};
14164: }
14165: return unpack("%32C*",$prefix);
14166: }
14167:
1.76 www 14168: sub ireceipt {
1.474 albertel 14169: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14170:
14171: my $return =&recprefix($fucourseid).'-';
14172:
14173: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14174: $env{'request.state'} eq 'construct') {
14175: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14176: return $return;
14177: }
14178:
1.76 www 14179: my $cuname=unpack("%32C*",$funame);
14180: my $cudom=unpack("%32C*",$fudom);
14181: my $cucourseid=unpack("%32C*",$fucourseid);
14182: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14183: my $cunique=&recunique($fucourseid);
1.474 albertel 14184: my $cpart=unpack("%32S*",$part);
1.835 albertel 14185: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14186:
1.790 albertel 14187: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14188:
14189: $return.= ($cunique%$cuname+
14190: $cunique%$cudom+
14191: $cusymb%$cuname+
14192: $cusymb%$cudom+
14193: $cucourseid%$cuname+
14194: $cucourseid%$cudom+
14195: $cpart%$cuname+
14196: $cpart%$cudom);
14197: } else {
14198: $return.= ($cunique%$cuname+
14199: $cunique%$cudom+
14200: $cusymb%$cuname+
14201: $cusymb%$cudom+
14202: $cucourseid%$cuname+
14203: $cucourseid%$cudom);
14204: }
14205: return $return;
1.76 www 14206: }
14207:
14208: sub receipt {
1.474 albertel 14209: my ($part)=@_;
1.790 albertel 14210: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14211: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14212: }
1.260 ng 14213:
1.790 albertel 14214: sub whichuser {
14215: my ($passedsymb)=@_;
14216: my ($symb,$courseid,$domain,$name,$publicuser);
14217: if (defined($env{'form.grade_symb'})) {
14218: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14219: my $allowed=&allowed('vgr',$tmp_courseid);
14220: if (!$allowed &&
14221: exists($env{'request.course.sec'}) &&
14222: $env{'request.course.sec'} !~ /^\s*$/) {
14223: $allowed=&allowed('vgr',$tmp_courseid.
14224: '/'.$env{'request.course.sec'});
14225: }
14226: if ($allowed) {
14227: ($symb)=&get_env_multiple('form.grade_symb');
14228: $courseid=$tmp_courseid;
14229: ($domain)=&get_env_multiple('form.grade_domain');
14230: ($name)=&get_env_multiple('form.grade_username');
14231: return ($symb,$courseid,$domain,$name,$publicuser);
14232: }
14233: }
14234: if (!$passedsymb) {
14235: $symb=&symbread();
14236: } else {
14237: $symb=$passedsymb;
14238: }
14239: $courseid=$env{'request.course.id'};
14240: $domain=$env{'user.domain'};
14241: $name=$env{'user.name'};
14242: if ($name eq 'public' && $domain eq 'public') {
14243: if (!defined($env{'form.username'})) {
14244: $env{'form.username'}.=time.rand(10000000);
14245: }
14246: $name.=$env{'form.username'};
14247: }
14248: return ($symb,$courseid,$domain,$name,$publicuser);
14249:
14250: }
14251:
1.36 albertel 14252: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14253: # returns either the contents of the file or
14254: # -1 if the file doesn't exist
1.481 raeburn 14255: #
14256: # if the target is a file that was uploaded via DOCS,
14257: # a check will be made to see if a current copy exists on the local server,
14258: # if it does this will be served, otherwise a copy will be retrieved from
14259: # the home server for the course and stored in /home/httpd/html/userfiles on
14260: # the local server.
1.472 albertel 14261:
1.36 albertel 14262: sub getfile {
1.538 albertel 14263: my ($file) = @_;
1.609 banghart 14264: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14265: &repcopy($file);
14266: return &readfile($file);
14267: }
14268:
14269: sub repcopy_userfile {
14270: my ($file)=@_;
1.1142 raeburn 14271: my $londocroot = $perlvar{'lonDocRoot'};
14272: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14273: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14274: my ($cdom,$cnum,$filename) =
1.811 albertel 14275: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14276: my $uri="/uploaded/$cdom/$cnum/$filename";
14277: if (-e "$file") {
1.828 www 14278: # we already have a local copy, check it out
1.538 albertel 14279: my @fileinfo = stat($file);
1.828 www 14280: my $rtncode;
14281: my $info;
1.538 albertel 14282: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14283: if ($lwpresp ne 'ok') {
1.828 www 14284: # there is no such file anymore, even though we had a local copy
1.482 albertel 14285: if ($rtncode eq '404') {
1.538 albertel 14286: unlink($file);
1.482 albertel 14287: }
14288: return -1;
14289: }
14290: if ($info < $fileinfo[9]) {
1.828 www 14291: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14292: return 'ok';
1.828 www 14293: } else {
14294: # the file is outdated, get rid of it
14295: unlink($file);
1.482 albertel 14296: }
1.828 www 14297: }
14298: # one way or the other, at this point, we don't have the file
14299: # construct the correct path for the file
14300: my @parts = ($cdom,$cnum);
14301: if ($filename =~ m|^(.+)/[^/]+$|) {
14302: push @parts, split(/\//,$1);
14303: }
14304: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14305: foreach my $part (@parts) {
14306: $path .= '/'.$part;
14307: if (!-e $path) {
14308: mkdir($path,0770);
1.482 albertel 14309: }
14310: }
1.828 www 14311: # now the path exists for sure
14312: # get a user agent
14313: my $ua=new LWP::UserAgent;
14314: my $transferfile=$file.'.in.transfer';
14315: # FIXME: this should flock
14316: if (-e $transferfile) { return 'ok'; }
14317: my $request;
14318: $uri=~s/^\///;
1.980 raeburn 14319: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 14320: my $hostname = &hostname($homeserver);
1.980 raeburn 14321: my $protocol = $protocol{$homeserver};
14322: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14323: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 14324: my $response=$ua->request($request,$transferfile);
14325: # did it work?
14326: if ($response->is_error()) {
14327: unlink($transferfile);
14328: &logthis("Userfile repcopy failed for $uri");
14329: return -1;
14330: }
14331: # worked, rename the transfer file
14332: rename($transferfile,$file);
1.607 raeburn 14333: return 'ok';
1.481 raeburn 14334: }
14335:
1.517 albertel 14336: sub tokenwrapper {
14337: my $uri=shift;
1.980 raeburn 14338: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14339: $uri=~s|^/||;
1.620 albertel 14340: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14341: my $token=$1;
1.552 albertel 14342: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14343: if ($udom && $uname && $file) {
14344: $file=~s|(\?\.*)*$||;
1.949 raeburn 14345: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14346: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 14347: my $hostname = &hostname($homeserver);
1.980 raeburn 14348: my $protocol = $protocol{$homeserver};
14349: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14350: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14351: (($uri=~/\?/)?'&':'?').'token='.$token.
14352: '&tokenissued='.$perlvar{'lonHostID'};
14353: } else {
14354: return '/adm/notfound.html';
14355: }
14356: }
14357:
1.828 www 14358: # call with reqtype HEAD: get last modification time
14359: # call with reqtype GET: get the file contents
14360: # Do not call this with reqtype GET for large files! It loads everything into memory
14361: #
1.481 raeburn 14362: sub getuploaded {
14363: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14364: $uri=~s/^\///;
1.980 raeburn 14365: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 14366: my $hostname = &hostname($homeserver);
1.980 raeburn 14367: my $protocol = $protocol{$homeserver};
14368: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 14369: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14370: my $ua=new LWP::UserAgent;
14371: my $request=new HTTP::Request($reqtype,$uri);
14372: my $response=$ua->request($request);
14373: $$rtncode = $response->code;
1.482 albertel 14374: if (! $response->is_success()) {
14375: return 'failed';
14376: }
14377: if ($reqtype eq 'HEAD') {
1.486 www 14378: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14379: } elsif ($reqtype eq 'GET') {
14380: $$info = $response->content;
1.472 albertel 14381: }
1.482 albertel 14382: return 'ok';
1.36 albertel 14383: }
14384:
1.481 raeburn 14385: sub readfile {
14386: my $file = shift;
14387: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14388: my $fh;
1.1172.2.96 raeburn 14389: open($fh,"<",$file);
1.481 raeburn 14390: my $a='';
1.800 albertel 14391: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14392: return $a;
14393: }
14394:
1.36 albertel 14395: sub filelocation {
1.590 banghart 14396: my ($dir,$file) = @_;
14397: my $location;
14398: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14399:
14400: if ($file =~ m-^/adm/-) {
14401: $file=~s-^/adm/wrapper/-/-;
14402: $file=~s-^/adm/coursedocs/showdoc/-/-;
14403: }
1.882 albertel 14404:
1.1139 www 14405: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14406: $location = $file;
1.609 banghart 14407: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14408: my ($udom,$uname,$filename)=
1.811 albertel 14409: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14410: my $home=&homeserver($uname,$udom);
14411: my $is_me=0;
14412: my @ids=¤t_machine_ids();
14413: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14414: if ($is_me) {
1.1117 foxr 14415: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14416: } else {
14417: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14418: $udom.'/'.$uname.'/'.$filename;
14419: }
1.882 albertel 14420: } elsif ($file =~ m-^/adm/-) {
14421: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14422: } else {
14423: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14424: $file=~s:^/(res|priv)/:/:;
14425: my $space=$1;
1.590 banghart 14426: if ( !( $file =~ m:^/:) ) {
14427: $location = $dir. '/'.$file;
14428: } else {
1.1142 raeburn 14429: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14430: }
1.59 albertel 14431: }
1.590 banghart 14432: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14433: while ($location=~m{/\.\./}) {
14434: if ($location =~ m{/[^/]+/\.\./}) {
14435: $location=~ s{/[^/]+/\.\./}{/}g;
14436: } else {
14437: $location=~ s{/\.\./}{/}g;
14438: }
14439: } #remove dir/..
1.590 banghart 14440: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14441: return $location;
1.46 www 14442: }
1.36 albertel 14443:
1.46 www 14444: sub hreflocation {
14445: my ($dir,$file)=@_;
1.980 raeburn 14446: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14447: $file=filelocation($dir,$file);
1.700 albertel 14448: } elsif ($file=~m-^/adm/-) {
14449: $file=~s-^/adm/wrapper/-/-;
14450: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14451: }
14452: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14453: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14454: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14455: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14456: {/uploaded/$1/$2/}x;
1.46 www 14457: }
1.913 albertel 14458: if ($file=~ m{^/userfiles/}) {
14459: $file =~ s{^/userfiles/}{/uploaded/};
14460: }
1.462 albertel 14461: return $file;
1.465 albertel 14462: }
14463:
1.1139 www 14464:
14465:
14466:
14467:
1.465 albertel 14468: sub current_machine_domains {
1.853 albertel 14469: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14470: }
14471:
14472: sub machine_domains {
14473: my ($hostname) = @_;
1.465 albertel 14474: my @domains;
1.838 albertel 14475: my %hostname = &all_hostnames();
1.465 albertel 14476: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14477: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14478: if ($hostname eq $name) {
1.844 albertel 14479: push(@domains,&host_domain($id));
1.465 albertel 14480: }
14481: }
14482: return @domains;
14483: }
14484:
14485: sub current_machine_ids {
1.853 albertel 14486: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14487: }
14488:
14489: sub machine_ids {
14490: my ($hostname) = @_;
14491: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14492: my @ids;
1.888 albertel 14493: my %name_to_host = &all_names();
1.889 albertel 14494: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14495: return @{ $name_to_host{$hostname} };
14496: }
14497: return;
1.31 www 14498: }
14499:
1.824 raeburn 14500: sub additional_machine_domains {
14501: my @domains;
1.1172.2.142 raeburn 14502: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14503: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14504: while( my $line = <$fh>) {
14505: chomp($line);
14506: $line =~ s/\s//g;
14507: push(@domains,$line);
14508: }
14509: close($fh);
14510: }
1.824 raeburn 14511: }
14512: return @domains;
14513: }
14514:
14515: sub default_login_domain {
14516: my $domain = $perlvar{'lonDefDomain'};
14517: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14518: foreach my $posdom (¤t_machine_domains(),
14519: &additional_machine_domains()) {
14520: if (lc($posdom) eq lc($testdomain)) {
14521: $domain=$posdom;
14522: last;
14523: }
14524: }
14525: return $domain;
14526: }
14527:
1.1172.2.106 raeburn 14528: sub shared_institution {
1.1172.2.136 raeburn 14529: my ($dom,$lonhost) = @_;
14530: if ($lonhost eq '') {
14531: $lonhost = $perlvar{'lonHostID'};
14532: }
1.1172.2.106 raeburn 14533: my $same_intdom;
1.1172.2.136 raeburn 14534: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 14535: if ($hostintdom ne '') {
14536: my %iphost = &get_iphost();
14537: my $primary_id = &domain($dom,'primary');
14538: my $primary_ip = &get_host_ip($primary_id);
14539: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14540: foreach my $id (@{$iphost{$primary_ip}}) {
14541: my $intdom = &internet_dom($id);
14542: if ($intdom eq $hostintdom) {
14543: $same_intdom = 1;
14544: last;
14545: }
14546: }
14547: }
14548: }
14549: return $same_intdom;
14550: }
14551:
1.1172.2.120 raeburn 14552: sub uses_sts {
14553: my ($ignore_cache) = @_;
14554: my $lonhost = $perlvar{'lonHostID'};
14555: my $hostname = &hostname($lonhost);
14556: my $sts_on;
14557: if ($protocol{$lonhost} eq 'https') {
14558: my $cachetime = 12*3600;
14559: if (!$ignore_cache) {
14560: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14561: if (defined($cached)) {
14562: return $sts_on;
14563: }
14564: }
1.1172.2.121 raeburn 14565: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 14566: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14567: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 14568: my $response=$ua->request($request);
1.1172.2.120 raeburn 14569: if ($response->is_success) {
14570: my $has_sts = $response->header('Strict-Transport-Security');
14571: if ($has_sts eq '') {
14572: $sts_on = 0;
14573: } else {
14574: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14575: my $maxage = $1;
14576: if ($maxage) {
14577: $sts_on = 1;
14578: } else {
14579: $sts_on = 0;
14580: }
14581: } else {
14582: $sts_on = 0;
14583: }
14584: }
14585: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14586: }
14587: }
14588: return;
14589: }
14590:
1.1172.2.142 raeburn 14591: sub waf_allssl {
14592: my ($host_name) = @_;
14593: my $alias = &get_proxy_alias();
14594: if ($host_name eq '') {
14595: $host_name = $ENV{'SERVER_NAME'};
14596: }
14597: if (($host_name ne '') && ($alias eq $host_name)) {
14598: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14599: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14600: if ($defdomdefaults{'waf_sslopt'}) {
14601: return $defdomdefaults{'waf_sslopt'};
14602: }
14603: }
14604: return;
14605: }
14606:
1.1172.2.134 raeburn 14607: sub get_requestor_ip {
14608: my ($r,$nolookup,$noproxy) = @_;
14609: my $from_ip;
14610: if (ref($r)) {
1.1172.2.142 raeburn 14611: if ($r->can('useragent_ip')) {
14612: if ($noproxy && $r->can('client_ip')) {
14613: $from_ip = $r->client_ip();
14614: } else {
14615: $from_ip = $r->useragent_ip();
14616: }
14617: } elsif ($r->connection->can('remote_ip')) {
14618: $from_ip = $r->connection->remote_ip();
14619: } else {
14620: $from_ip = $r->get_remote_host($nolookup);
14621: }
1.1172.2.134 raeburn 14622: } else {
14623: $from_ip = $ENV{'REMOTE_ADDR'};
14624: }
1.1172.2.142 raeburn 14625: return $from_ip if ($noproxy);
14626: # Who controls proxy settings for server
14627: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14628: my $proxyinfo = &get_proxy_settings($dom_in_use);
14629: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14630: if ($proxyinfo->{'vpnint'}) {
14631: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14632: return $from_ip;
14633: }
14634: }
14635: if ($proxyinfo->{'trusted'}) {
14636: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14637: my $ipheader = $proxyinfo->{'ipheader'};
14638: my ($ip,$xfor);
14639: if (ref($r)) {
14640: if ($ipheader) {
14641: $ip = $r->headers_in->{$ipheader};
14642: }
14643: $xfor = $r->headers_in->{'X-Forwarded-For'};
14644: } else {
14645: if ($ipheader) {
14646: $ip = $ENV{'HTTP_'.uc($ipheader)};
14647: }
14648: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14649: }
14650: if (($ip eq '') && ($xfor ne '')) {
14651: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14652: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14653: $ip = $poss_ip;
14654: last;
14655: }
14656: }
14657: }
14658: if ($ip ne '') {
14659: return $ip;
14660: }
14661: }
14662: }
14663: }
1.1172.2.134 raeburn 14664: return $from_ip;
14665: }
14666:
1.1172.2.142 raeburn 14667: sub get_proxy_settings {
14668: my ($dom_in_use) = @_;
14669: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14670: my $proxyinfo = {
14671: ipheader => $domdefaults{'waf_ipheader'},
14672: trusted => $domdefaults{'waf_trusted'},
14673: vpnint => $domdefaults{'waf_vpnint'},
14674: vpnext => $domdefaults{'waf_vpnext'},
14675: sslopt => $domdefaults{'waf_sslopt'},
14676: };
14677: return $proxyinfo;
14678: }
14679:
14680: sub ip_match {
14681: my ($ip,$pattern_str) = @_;
14682: $ip=Net::CIDR::cidrvalidate($ip);
14683: if ($ip) {
14684: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14685: }
14686: return;
14687: }
14688:
14689: sub get_proxy_alias {
14690: my ($lonid) = @_;
14691: if ($lonid eq '') {
14692: $lonid = $perlvar{'lonHostID'};
14693: }
14694: if (!defined(&hostname($lonid))) {
14695: return;
14696: }
14697: if ($lonid ne '') {
14698: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14699: if ($cached) {
14700: return $alias;
14701: }
14702: my $dom = &Apache::lonnet::host_domain($lonid);
14703: if ($dom ne '') {
14704: my $cachetime = 60*60*24;
14705: my %domconfig =
14706: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14707: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14708: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14709: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14710: }
14711: }
14712: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14713: }
14714: }
14715: return;
14716: }
14717:
14718: sub use_proxy_alias {
14719: my ($r,$lonid) = @_;
14720: my $alias = &get_proxy_alias($lonid);
14721: if ($alias) {
14722: my $dom = &host_domain($lonid);
14723: if ($dom ne '') {
14724: my $proxyinfo = &get_proxy_settings($dom);
14725: my ($vpnint,$remote_ip);
14726: if (ref($proxyinfo) eq 'HASH') {
14727: $vpnint = $proxyinfo->{'vpnint'};
14728: if ($vpnint) {
14729: $remote_ip = &get_requestor_ip($r,1,1);
14730: }
14731: }
14732: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14733: return $alias;
14734: }
14735: }
14736: }
14737: return;
14738: }
14739:
14740: sub alias_sso {
14741: my ($lonid) = @_;
14742: if ($lonid eq '') {
14743: $lonid = $perlvar{'lonHostID'};
14744: }
14745: if (!defined(&hostname($lonid))) {
14746: return;
14747: }
14748: if ($lonid ne '') {
14749: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14750: if ($cached) {
14751: return $use_alias;
14752: }
14753: my $dom = &Apache::lonnet::host_domain($lonid);
14754: if ($dom ne '') {
14755: my $cachetime = 60*60*24;
14756: my %domconfig =
14757: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14758: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14759: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14760: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14761: }
14762: }
14763: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14764: }
14765: }
14766: return;
14767: }
14768:
14769: sub get_saml_landing {
14770: my ($lonid) = @_;
14771: if ($lonid eq '') {
14772: my $defdom = &default_login_domain();
14773: my @hosts = ¤t_machine_ids();
14774: if (@hosts > 1) {
14775: foreach my $hostid (@hosts) {
14776: if (&host_domain($hostid) eq $defdom) {
14777: $lonid = $hostid;
14778: last;
14779: }
14780: }
14781: } else {
14782: $lonid = $perlvar{'lonHostID'};
14783: }
14784: if ($lonid) {
14785: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14786: return;
14787: }
14788: } else {
14789: return;
14790: }
14791: } elsif (!defined(&hostname($lonid))) {
14792: return;
14793: }
14794: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14795: if ($cached) {
14796: return $landing;
14797: }
14798: my $dom = &Apache::lonnet::host_domain($lonid);
14799: if ($dom ne '') {
14800: my $cachetime = 60*60*24;
14801: my %domconfig =
14802: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14803: if (ref($domconfig{'login'}) eq 'HASH') {
14804: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14805: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14806: $landing = 1;
14807: }
14808: }
14809: }
14810: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14811: }
14812: return;
14813: }
14814:
1.31 www 14815: # ------------------------------------------------------------- Declutters URLs
14816:
14817: sub declutter {
14818: my $thisfn=shift;
1.569 albertel 14819: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 14820: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14821: $thisfn=~s{^/home/httpd/html}{};
14822: }
1.31 www 14823: $thisfn=~s/^\///;
1.697 albertel 14824: $thisfn=~s|^adm/wrapper/||;
14825: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14826: $thisfn=~s/^res\///;
1.1172 bisitz 14827: $thisfn=~s/^priv\///;
1.1032 raeburn 14828: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14829: $thisfn=~s/\?.+$//;
14830: }
1.268 www 14831: return $thisfn;
14832: }
14833:
14834: # ------------------------------------------------------------- Clutter up URLs
14835:
14836: sub clutter {
14837: my $thisfn='/'.&declutter(shift);
1.887 albertel 14838: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14839: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14840: $thisfn='/res'.$thisfn;
14841: }
1.1031 raeburn 14842: if ($thisfn !~m|^/adm|) {
14843: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14844: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14845: } else {
14846: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14847: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14848: if ($embstyle eq 'ssi'
14849: || ($embstyle eq 'hdn')
14850: || ($embstyle eq 'rat')
14851: || ($embstyle eq 'prv')
14852: || ($embstyle eq 'ign')) {
14853: #do nothing with these
14854: } elsif (($embstyle eq 'img')
1.695 albertel 14855: || ($embstyle eq 'emb')
14856: || ($embstyle eq 'wrp')) {
14857: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14858: } elsif ($embstyle eq 'unk'
14859: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14860: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14861: } else {
1.718 www 14862: # &logthis("Got a blank emb style");
1.695 albertel 14863: }
1.694 albertel 14864: }
1.1172.2.146. .1(raebu 14865:22): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14866:22): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14867: }
1.31 www 14868: return $thisfn;
1.12 www 14869: }
14870:
1.787 albertel 14871: sub clutter_with_no_wrapper {
14872: my $uri = &clutter(shift);
14873: if ($uri =~ m-^/adm/-) {
14874: $uri =~ s-^/adm/wrapper/-/-;
14875: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14876: }
14877: return $uri;
14878: }
14879:
1.557 albertel 14880: sub freeze_escape {
14881: my ($value)=@_;
14882: if (ref($value)) {
14883: $value=&nfreeze($value);
14884: return '__FROZEN__'.&escape($value);
14885: }
14886: return &escape($value);
14887: }
14888:
1.11 www 14889:
1.557 albertel 14890: sub thaw_unescape {
14891: my ($value)=@_;
14892: if ($value =~ /^__FROZEN__/) {
14893: substr($value,0,10,undef);
14894: $value=&unescape($value);
14895: return &thaw($value);
14896: }
14897: return &unescape($value);
14898: }
14899:
1.436 albertel 14900: sub correct_line_ends {
14901: my ($result)=@_;
14902: $$result =~s/\r\n/\n/mg;
14903: $$result =~s/\r/\n/mg;
1.415 albertel 14904: }
1.1 albertel 14905: # ================================================================ Main Program
14906:
1.184 www 14907: sub goodbye {
1.204 albertel 14908: &logthis("Starting Shut down");
1.443 albertel 14909: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14910: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14911: #converted
1.599 albertel 14912: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14913: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14914: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14915: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14916: #1.1 only
1.870 albertel 14917: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14918: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14919: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14920: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14921: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14922: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14923: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14924: &flushcourselogs();
14925: &logthis("Shutting down");
14926: }
14927:
1.852 albertel 14928: sub get_dns {
1.1172.2.17 raeburn 14929: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14930: if (!$ignore_cache) {
14931: my ($content,$cached)=
14932: &Apache::lonnet::is_cached_new('dns',$url);
14933: if ($cached) {
1.1172.2.17 raeburn 14934: &$func($content,$hashref);
1.869 albertel 14935: return;
14936: }
14937: }
14938:
14939: my %alldns;
1.1172.2.96 raeburn 14940: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14941: foreach my $dns (<$config>) {
14942: next if ($dns !~ /^\^(\S*)/x);
14943: my $line = $1;
14944: my ($host,$protocol) = split(/:/,$line);
14945: if ($protocol ne 'https') {
14946: $protocol = 'http';
14947: }
14948: $alldns{$host} = $protocol;
1.979 raeburn 14949: }
1.1172.2.96 raeburn 14950: close($config);
1.869 albertel 14951: }
14952: while (%alldns) {
1.1172.2.52 raeburn 14953: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 14954: my @content;
14955: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14956: my $command = (split('/',$url))[3];
14957: my ($dir,$file) = &parse_getdns_url($command,$url);
14958: delete($alldns{$dns});
14959: next if (($dir eq '') || ($file eq ''));
14960: if (open(my $config,'<',"$dir/$file")) {
14961: @content = <$config>;
14962: close($config);
14963: }
14964: } else {
14965: my $ua=new LWP::UserAgent;
14966: $ua->timeout(30);
14967: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14968: my $response=$ua->request($request);
14969: delete($alldns{$dns});
14970: next if ($response->is_error());
14971: @content = split("\n",$response->content);
14972: }
1.1172.2.17 raeburn 14973: unless ($nocache) {
1.1172.2.23 raeburn 14974: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 14975: }
14976: &$func(\@content,$hashref);
1.869 albertel 14977: return;
1.852 albertel 14978: }
1.871 albertel 14979: my $which = (split('/',$url))[3];
14980: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 14981: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14982: my @content = <$config>;
14983: &$func(\@content,$hashref);
14984: }
1.1172.2.17 raeburn 14985: return;
14986: }
14987:
14988: # ------------------------------------------------------Get DNS checksums file
14989: sub parse_dns_checksums_tab {
14990: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14991: my $lonhost = $perlvar{'lonHostID'};
14992: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14993: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14994: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14995: my $webconfdir = '/etc/httpd/conf';
14996: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14997: $webconfdir = '/etc/apache2';
14998: } elsif ($distro =~ /^sles(\d+)$/) {
14999: if ($1 >= 10) {
15000: $webconfdir = '/etc/apache2';
15001: }
15002: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15003: if ($1 >= 10.0) {
15004: $webconfdir = '/etc/apache2';
15005: }
15006: }
1.1172.2.17 raeburn 15007: my ($release,$timestamp) = split(/\-/,$loncaparev);
15008: my (%chksum,%revnum);
15009: if (ref($lines) eq 'ARRAY') {
15010: chomp(@{$lines});
1.1172.2.34 raeburn 15011: my $version = shift(@{$lines});
15012: if ($version eq $release) {
1.1172.2.17 raeburn 15013: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 15014: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 15015: if ($file =~ m{^/etc/httpd/conf}) {
15016: if ($webconfdir eq '/etc/apache2') {
15017: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15018: }
15019: }
1.1172.2.34 raeburn 15020: $chksum{$file} = $shasum;
15021: $revnum{$file} = $version;
1.1172.2.17 raeburn 15022: }
15023: if (ref($hashref) eq 'HASH') {
15024: %{$hashref} = (
15025: sums => \%chksum,
15026: versions => \%revnum,
15027: );
15028: }
15029: }
15030: }
1.869 albertel 15031: return;
1.852 albertel 15032: }
1.1172.2.17 raeburn 15033:
15034: sub fetch_dns_checksums {
15035: my %checksums;
1.1172.2.34 raeburn 15036: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 15037: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 15038: my ($release,$timestamp) = split(/\-/,$loncaparev);
15039: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 15040: \%checksums);
15041: return \%checksums;
15042: }
15043:
1.1172.2.142 raeburn 15044: sub parse_getdns_url {
15045: my ($command,$url) = @_;
15046: my $dir = $perlvar{'lonTabDir'};
15047: my $file;
15048: if ($command eq 'hosts') {
15049: $file = 'dns_hosts.tab';
15050: } elsif ($command eq 'domain') {
15051: $file = 'dns_domain.tab';
15052: } elsif ($command eq 'checksums') {
15053: my $version = (split('/',$url))[4];
15054: $file = "dns_checksums/$version.tab",
15055: }
15056: return ($dir,$file);
15057: }
15058:
1.327 albertel 15059: # ------------------------------------------------------------ Read domain file
15060: {
1.852 albertel 15061: my $loaded;
1.846 albertel 15062: my %domain;
15063:
1.852 albertel 15064: sub parse_domain_tab {
15065: my ($lines) = @_;
15066: foreach my $line (@$lines) {
15067: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15068:
1.846 albertel 15069: chomp($line);
1.852 albertel 15070: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15071: my %this_domain;
15072: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15073: 'lang_def', 'city', 'longi', 'lati',
15074: 'primary') {
15075: $this_domain{$field} = shift(@elements);
15076: }
15077: $domain{$name} = \%this_domain;
1.852 albertel 15078: }
15079: }
1.864 albertel 15080:
15081: sub reset_domain_info {
15082: undef($loaded);
15083: undef(%domain);
15084: }
15085:
1.852 albertel 15086: sub load_domain_tab {
1.1172.2.70 raeburn 15087: my ($ignore_cache,$nocache) = @_;
15088: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15089: my $fh;
1.1172.2.96 raeburn 15090: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15091: my @lines = <$fh>;
15092: &parse_domain_tab(\@lines);
1.448 albertel 15093: }
1.852 albertel 15094: close($fh);
15095: $loaded = 1;
1.327 albertel 15096: }
1.846 albertel 15097:
15098: sub domain {
1.852 albertel 15099: &load_domain_tab() if (!$loaded);
15100:
1.846 albertel 15101: my ($name,$what) = @_;
15102: return if ( !exists($domain{$name}) );
15103:
15104: if (!$what) {
15105: return $domain{$name}{'description'};
15106: }
15107: return $domain{$name}{$what};
15108: }
1.974 raeburn 15109:
15110: sub domain_info {
15111: &load_domain_tab() if (!$loaded);
15112: return %domain;
15113: }
15114:
1.327 albertel 15115: }
15116:
15117:
1.1 albertel 15118: # ------------------------------------------------------------- Read hosts file
15119: {
1.838 albertel 15120: my %hostname;
1.844 albertel 15121: my %hostdom;
1.845 albertel 15122: my %libserv;
1.852 albertel 15123: my $loaded;
1.888 albertel 15124: my %name_to_host;
1.1074 raeburn 15125: my %internetdom;
1.1107 raeburn 15126: my %LC_dns_serv;
1.852 albertel 15127:
15128: sub parse_hosts_tab {
15129: my ($file) = @_;
15130: foreach my $configline (@$file) {
15131: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15132: chomp($configline);
15133: if ($configline =~ /^\^/) {
15134: if ($configline =~ /^\^([\w.\-]+)/) {
15135: $LC_dns_serv{$1} = 1;
15136: }
15137: next;
15138: }
1.1074 raeburn 15139: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15140: $name=~s/\s//g;
15141: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 15142: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15143: my $curr = $hostname{$id};
15144: my $skip;
15145: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15146: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15147: $skip = 1;
15148: } else {
15149: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15150: }
15151: }
15152: unless ($skip) {
15153: push(@{$name_to_host{$name}},$id);
15154: }
15155: } else {
15156: push(@{$name_to_host{$name}},$id);
15157: }
1.852 albertel 15158: $hostname{$id}=$name;
15159: $hostdom{$id}=$domain;
15160: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15161: if (defined($protocol)) {
15162: if ($protocol eq 'https') {
15163: $protocol{$id} = $protocol;
15164: } else {
15165: $protocol{$id} = 'http';
15166: }
1.968 raeburn 15167: } else {
1.969 raeburn 15168: $protocol{$id} = 'http';
1.968 raeburn 15169: }
1.1074 raeburn 15170: if (defined($intdom)) {
15171: $internetdom{$id} = $intdom;
15172: }
1.852 albertel 15173: }
15174: }
15175: }
1.864 albertel 15176:
15177: sub reset_hosts_info {
1.897 albertel 15178: &purge_remembered();
1.864 albertel 15179: &reset_domain_info();
15180: &reset_hosts_ip_info();
1.892 albertel 15181: undef(%name_to_host);
1.864 albertel 15182: undef(%hostname);
15183: undef(%hostdom);
15184: undef(%libserv);
15185: undef($loaded);
15186: }
1.1 albertel 15187:
1.852 albertel 15188: sub load_hosts_tab {
1.1172.2.70 raeburn 15189: my ($ignore_cache,$nocache) = @_;
15190: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 15191: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15192: my @config = <$config>;
15193: &parse_hosts_tab(\@config);
15194: close($config);
15195: $loaded=1;
1.1 albertel 15196: }
1.852 albertel 15197:
1.838 albertel 15198: sub hostname {
1.852 albertel 15199: &load_hosts_tab() if (!$loaded);
15200:
1.838 albertel 15201: my ($lonid) = @_;
15202: return $hostname{$lonid};
15203: }
1.845 albertel 15204:
1.838 albertel 15205: sub all_hostnames {
1.852 albertel 15206: &load_hosts_tab() if (!$loaded);
15207:
1.838 albertel 15208: return %hostname;
15209: }
1.845 albertel 15210:
1.888 albertel 15211: sub all_names {
1.1172.2.70 raeburn 15212: my ($ignore_cache,$nocache) = @_;
15213: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15214:
15215: return %name_to_host;
15216: }
15217:
1.974 raeburn 15218: sub all_host_domain {
15219: &load_hosts_tab() if (!$loaded);
15220: return %hostdom;
15221: }
15222:
1.845 albertel 15223: sub is_library {
1.852 albertel 15224: &load_hosts_tab() if (!$loaded);
15225:
1.845 albertel 15226: return exists($libserv{$_[0]});
15227: }
15228:
15229: sub all_library {
1.852 albertel 15230: &load_hosts_tab() if (!$loaded);
15231:
1.845 albertel 15232: return %libserv;
15233: }
15234:
1.1062 droeschl 15235: sub unique_library {
15236: #2x reverse removes all hostnames that appear more than once
15237: my %unique = reverse &all_library();
15238: return reverse %unique;
15239: }
15240:
1.841 albertel 15241: sub get_servers {
1.852 albertel 15242: &load_hosts_tab() if (!$loaded);
15243:
1.841 albertel 15244: my ($domain,$type) = @_;
15245: my %possible_hosts = ($type eq 'library') ? %libserv
15246: : %hostname;
15247: my %result;
1.842 albertel 15248: if (ref($domain) eq 'ARRAY') {
15249: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15250: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15251: $result{$host} = $hostname;
15252: }
15253: }
15254: } else {
15255: while ( my ($host,$hostname) = each(%possible_hosts)) {
15256: if ($hostdom{$host} eq $domain) {
15257: $result{$host} = $hostname;
15258: }
1.841 albertel 15259: }
15260: }
15261: return %result;
15262: }
1.845 albertel 15263:
1.1062 droeschl 15264: sub get_unique_servers {
15265: my %unique = reverse &get_servers(@_);
15266: return reverse %unique;
15267: }
15268:
1.844 albertel 15269: sub host_domain {
1.852 albertel 15270: &load_hosts_tab() if (!$loaded);
15271:
1.844 albertel 15272: my ($lonid) = @_;
15273: return $hostdom{$lonid};
15274: }
15275:
1.841 albertel 15276: sub all_domains {
1.852 albertel 15277: &load_hosts_tab() if (!$loaded);
15278:
1.841 albertel 15279: my %seen;
15280: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15281: return @uniq;
15282: }
1.1074 raeburn 15283:
15284: sub internet_dom {
15285: &load_hosts_tab() if (!$loaded);
15286:
15287: my ($lonid) = @_;
15288: return $internetdom{$lonid};
15289: }
1.1107 raeburn 15290:
15291: sub is_LC_dns {
15292: &load_hosts_tab() if (!$loaded);
15293:
15294: my ($hostname) = @_;
15295: return exists($LC_dns_serv{$hostname});
15296: }
15297:
1.1 albertel 15298: }
15299:
1.847 albertel 15300: {
15301: my %iphost;
1.856 albertel 15302: my %name_to_ip;
15303: my %lonid_to_ip;
1.869 albertel 15304:
1.847 albertel 15305: sub get_hosts_from_ip {
15306: my ($ip) = @_;
15307: my %iphosts = &get_iphost();
15308: if (ref($iphosts{$ip})) {
15309: return @{$iphosts{$ip}};
15310: }
15311: return;
1.839 albertel 15312: }
1.864 albertel 15313:
15314: sub reset_hosts_ip_info {
15315: undef(%iphost);
15316: undef(%name_to_ip);
15317: undef(%lonid_to_ip);
15318: }
1.856 albertel 15319:
15320: sub get_host_ip {
15321: my ($lonid) = @_;
15322: if (exists($lonid_to_ip{$lonid})) {
15323: return $lonid_to_ip{$lonid};
15324: }
15325: my $name=&hostname($lonid);
15326: my $ip = gethostbyname($name);
15327: return if (!$ip || length($ip) ne 4);
15328: $ip=inet_ntoa($ip);
15329: $name_to_ip{$name} = $ip;
15330: $lonid_to_ip{$lonid} = $ip;
15331: return $ip;
15332: }
1.847 albertel 15333:
15334: sub get_iphost {
1.1172.2.70 raeburn 15335: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15336:
1.869 albertel 15337: if (!$ignore_cache) {
15338: if (%iphost) {
15339: return %iphost;
15340: }
15341: my ($ip_info,$cached)=
15342: &Apache::lonnet::is_cached_new('iphost','iphost');
15343: if ($cached) {
15344: %iphost = %{$ip_info->[0]};
15345: %name_to_ip = %{$ip_info->[1]};
15346: %lonid_to_ip = %{$ip_info->[2]};
15347: return %iphost;
15348: }
15349: }
1.894 albertel 15350:
15351: # get yesterday's info for fallback
15352: my %old_name_to_ip;
15353: my ($ip_info,$cached)=
15354: &Apache::lonnet::is_cached_new('iphost','iphost');
15355: if ($cached) {
15356: %old_name_to_ip = %{$ip_info->[1]};
15357: }
15358:
1.1172.2.70 raeburn 15359: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15360: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15361: my $ip;
15362: if (!exists($name_to_ip{$name})) {
15363: $ip = gethostbyname($name);
15364: if (!$ip || length($ip) ne 4) {
1.894 albertel 15365: if (defined($old_name_to_ip{$name})) {
15366: $ip = $old_name_to_ip{$name};
15367: &logthis("Can't find $name defaulting to old $ip");
15368: } else {
15369: &logthis("Name $name no IP found");
15370: next;
15371: }
15372: } else {
15373: $ip=inet_ntoa($ip);
1.847 albertel 15374: }
15375: $name_to_ip{$name} = $ip;
15376: } else {
15377: $ip = $name_to_ip{$name};
1.653 albertel 15378: }
1.888 albertel 15379: foreach my $id (@{ $name_to_host{$name} }) {
15380: $lonid_to_ip{$id} = $ip;
15381: }
15382: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15383: }
1.1172.2.70 raeburn 15384: unless ($nocache) {
15385: &do_cache_new('iphost','iphost',
15386: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15387: 48*60*60);
15388: }
1.869 albertel 15389:
1.847 albertel 15390: return %iphost;
1.598 albertel 15391: }
15392:
1.992 raeburn 15393: #
15394: # Given a DNS returns the loncapa host name for that DNS
15395: #
15396: sub host_from_dns {
15397: my ($dns) = @_;
15398: my @hosts;
15399: my $ip;
15400:
1.993 raeburn 15401: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15402: $ip = $name_to_ip{$dns};
15403: }
15404: if (!$ip) {
15405: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15406: if (length($ip) == 4) {
15407: $ip = &IO::Socket::inet_ntoa($ip);
15408: }
15409: }
15410: if ($ip) {
15411: @hosts = get_hosts_from_ip($ip);
15412: return $hosts[0];
15413: }
15414: return undef;
1.986 foxr 15415: }
1.992 raeburn 15416:
1.1074 raeburn 15417: sub get_internet_names {
15418: my ($lonid) = @_;
15419: return if ($lonid eq '');
15420: my ($idnref,$cached)=
15421: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15422: if ($cached) {
15423: return $idnref;
15424: }
15425: my $ip = &get_host_ip($lonid);
15426: my @hosts = &get_hosts_from_ip($ip);
15427: my %iphost = &get_iphost();
15428: my (@idns,%seen);
15429: foreach my $id (@hosts) {
15430: my $dom = &host_domain($id);
15431: my $prim_id = &domain($dom,'primary');
15432: my $prim_ip = &get_host_ip($prim_id);
15433: next if ($seen{$prim_ip});
15434: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15435: foreach my $id (@{$iphost{$prim_ip}}) {
15436: my $intdom = &internet_dom($id);
15437: unless (grep(/^\Q$intdom\E$/,@idns)) {
15438: push(@idns,$intdom);
15439: }
15440: }
15441: }
15442: $seen{$prim_ip} = 1;
15443: }
1.1172.2.23 raeburn 15444: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15445: }
15446:
1.986 foxr 15447: }
15448:
1.1079 raeburn 15449: sub all_loncaparevs {
1.1172.2.39 raeburn 15450: 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 15451: }
15452:
1.1172.2.27 raeburn 15453: # ------------------------------------------------------- Read loncaparev table
15454: {
15455: sub load_loncaparevs {
15456: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 15457: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 15458: while (my $configline=<$config>) {
15459: chomp($configline);
15460: my ($hostid,$loncaparev)=split(/:/,$configline);
15461: $loncaparevs{$hostid}=$loncaparev;
15462: }
15463: close($config);
15464: }
15465: }
15466: }
15467: }
15468:
15469: # ----------------------------------------------------- Read serverhostID table
15470: {
15471: sub load_serverhomeIDs {
15472: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 15473: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 15474: while (my $configline=<$config>) {
15475: chomp($configline);
15476: my ($name,$id)=split(/:/,$configline);
15477: $serverhomeIDs{$name}=$id;
15478: }
15479: close($config);
15480: }
15481: }
15482: }
15483: }
15484:
15485:
1.862 albertel 15486: BEGIN {
15487:
15488: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15489: unless ($readit) {
15490: {
15491: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15492: %perlvar = (%perlvar,%{$configvars});
15493: }
15494:
15495:
1.1 albertel 15496: # ------------------------------------------------------ Read spare server file
15497: {
1.1172.2.96 raeburn 15498: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15499:
15500: while (my $configline=<$config>) {
15501: chomp($configline);
1.284 matthew 15502: if ($configline) {
1.784 albertel 15503: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15504: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15505: push(@{ $spareid{$type} }, $host);
1.1 albertel 15506: }
15507: }
1.448 albertel 15508: close($config);
1.1 albertel 15509: }
1.11 www 15510: # ------------------------------------------------------------ Read permissions
15511: {
1.1172.2.96 raeburn 15512: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15513:
15514: while (my $configline=<$config>) {
1.448 albertel 15515: chomp($configline);
15516: if ($configline) {
15517: my ($role,$perm)=split(/ /,$configline);
15518: if ($perm ne '') { $pr{$role}=$perm; }
15519: }
1.11 www 15520: }
1.448 albertel 15521: close($config);
1.11 www 15522: }
15523:
15524: # -------------------------------------------- Read plain texts for permissions
15525: {
1.1172.2.96 raeburn 15526: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15527:
15528: while (my $configline=<$config>) {
1.448 albertel 15529: chomp($configline);
15530: if ($configline) {
1.742 raeburn 15531: my ($short,@plain)=split(/:/,$configline);
15532: %{$prp{$short}} = ();
15533: if (@plain > 0) {
15534: $prp{$short}{'std'} = $plain[0];
15535: for (my $i=1; $i<@plain; $i++) {
15536: $prp{$short}{'alt'.$i} = $plain[$i];
15537: }
15538: }
1.448 albertel 15539: }
1.135 www 15540: }
1.448 albertel 15541: close($config);
1.135 www 15542: }
15543:
15544: # ---------------------------------------------------------- Read package table
15545: {
1.1172.2.96 raeburn 15546: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15547:
15548: while (my $configline=<$config>) {
1.483 albertel 15549: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15550: chomp($configline);
15551: my ($short,$plain)=split(/:/,$configline);
15552: my ($pack,$name)=split(/\&/,$short);
15553: if ($plain ne '') {
15554: $packagetab{$pack.'&'.$name.'&name'}=$name;
15555: $packagetab{$short}=$plain;
15556: }
1.11 www 15557: }
1.448 albertel 15558: close($config);
1.329 matthew 15559: }
15560:
1.1172.2.27 raeburn 15561: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 15562:
1.1172.2.27 raeburn 15563: &load_loncaparevs();
15564:
15565: # ------------------------------------------------------- Read serverhostID table
15566:
15567: &load_serverhomeIDs();
1.1074 raeburn 15568:
1.1172.2.27 raeburn 15569: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15570: {
15571: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15572: if (-e $file) {
15573: my $parser = HTML::LCParser->new($file);
15574: while (my $token = $parser->get_token()) {
15575: if ($token->[0] eq 'S') {
15576: my $item = $token->[1];
15577: my $name = $token->[2]{'name'};
15578: my $value = $token->[2]{'value'};
15579: if ($item ne '' && $name ne '' && $value ne '') {
15580: my $release = $parser->get_text();
15581: $release =~ s/(^\s*|\s*$ )//gx;
15582: $needsrelease{$item.':'.$name.':'.$value} = $release;
15583: }
15584: }
15585: }
15586: }
1.1073 raeburn 15587: }
15588:
1.1138 raeburn 15589: # ---------------------------------------------------------- Read managers table
15590: {
15591: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 15592: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15593: while (my $configline=<$config>) {
15594: chomp($configline);
15595: next if ($configline =~ /^\#/);
15596: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15597: $managerstab{$configline} = 1;
15598: }
15599: }
15600: close($config);
15601: }
15602: }
15603: }
15604:
1.329 matthew 15605: # ------------- set up temporary directory
15606: {
1.1117 foxr 15607: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15608:
1.11 www 15609: }
15610:
1.1172.2.104 raeburn 15611: # ------------- set default texengine (domain default overrides this)
15612: {
15613: $deftex = LONCAPA::texengine();
15614: }
15615:
1.1172.2.114 raeburn 15616: # ------------- set default minimum length for passwords for internal auth users
15617: {
15618: $passwdmin = LONCAPA::passwd_min();
15619: }
15620:
1.794 albertel 15621: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15622: 'compress_threshold'=> 20_000,
15623: });
1.185 www 15624:
1.281 www 15625: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15626: $dumpcount=0;
1.958 www 15627: $locknum=0;
1.22 www 15628:
1.163 harris41 15629: &logtouch();
1.672 albertel 15630: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15631: $readit=1;
1.564 albertel 15632: {
15633: use integer;
15634: my $test=(2**32)+1;
1.568 albertel 15635: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15636: &logthis(" Detected 64bit platform ($_64bit)");
15637: }
1.195 www 15638: }
1.1 albertel 15639: }
1.179 www 15640:
1.1 albertel 15641: 1;
1.191 harris41 15642: __END__
15643:
1.243 albertel 15644: =pod
15645:
1.191 harris41 15646: =head1 NAME
15647:
1.243 albertel 15648: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15649:
15650: =head1 SYNOPSIS
15651:
1.243 albertel 15652: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15653:
15654: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15655:
1.243 albertel 15656: Common parameters:
15657:
15658: =over 4
15659:
15660: =item *
15661:
15662: $uname : an internal username (if $cname expecting a course Id specifically)
15663:
15664: =item *
15665:
15666: $udom : a domain (if $cdom expecting a course's domain specifically)
15667:
15668: =item *
15669:
15670: $symb : a resource instance identifier
15671:
15672: =item *
15673:
15674: $namespace : the name of a .db file that contains the data needed or
15675: being set.
15676:
15677: =back
15678:
1.394 bowersj2 15679: =head1 OVERVIEW
1.191 harris41 15680:
1.394 bowersj2 15681: lonnet provides subroutines which interact with the
15682: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15683: about classes, users, and resources.
1.243 albertel 15684:
15685: For many of these objects you can also use this to store data about
15686: them or modify them in various ways.
1.191 harris41 15687:
1.394 bowersj2 15688: =head2 Symbs
1.191 harris41 15689:
1.394 bowersj2 15690: To identify a specific instance of a resource, LON-CAPA uses symbols
15691: or "symbs"X<symb>. These identifiers are built from the URL of the
15692: map, the resource number of the resource in the map, and the URL of
15693: the resource itself. The latter is somewhat redundant, but might help
15694: if maps change.
15695:
15696: An example is
15697:
15698: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15699:
15700: The respective map entry is
15701:
15702: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15703: title="Problem 2">
15704: </resource>
15705:
15706: Symbs are used by the random number generator, as well as to store and
15707: restore data specific to a certain instance of for example a problem.
15708:
15709: =head2 Storing And Retrieving Data
15710:
15711: X<store()>X<cstore()>X<restore()>Three of the most important functions
15712: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15713: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15714: is is the non-critical message twin of cstore. These functions are for
15715: handlers to store a perl hash to a user's permanent data space in an
15716: easy manner, and to retrieve it again on another call. It is expected
15717: that a handler would use this once at the beginning to retrieve data,
15718: and then again once at the end to send only the new data back.
15719:
15720: The data is stored in the user's data directory on the user's
15721: homeserver under the ID of the course.
15722:
15723: The hash that is returned by restore will have all of the previous
15724: value for all of the elements of the hash.
15725:
15726: Example:
15727:
15728: #creating a hash
15729: my %hash;
15730: $hash{'foo'}='bar';
15731:
15732: #storing it
15733: &Apache::lonnet::cstore(\%hash);
15734:
15735: #changing a value
15736: $hash{'foo'}='notbar';
15737:
15738: #adding a new value
15739: $hash{'bar'}='foo';
15740: &Apache::lonnet::cstore(\%hash);
15741:
15742: #retrieving the hash
15743: my %history=&Apache::lonnet::restore();
15744:
15745: #print the hash
15746: foreach my $key (sort(keys(%history))) {
15747: print("\%history{$key} = $history{$key}");
15748: }
15749:
15750: Will print out:
1.191 harris41 15751:
1.394 bowersj2 15752: %history{1:foo} = bar
15753: %history{1:keys} = foo:timestamp
15754: %history{1:timestamp} = 990455579
15755: %history{2:bar} = foo
15756: %history{2:foo} = notbar
15757: %history{2:keys} = foo:bar:timestamp
15758: %history{2:timestamp} = 990455580
15759: %history{bar} = foo
15760: %history{foo} = notbar
15761: %history{timestamp} = 990455580
15762: %history{version} = 2
15763:
15764: Note that the special hash entries C<keys>, C<version> and
15765: C<timestamp> were added to the hash. C<version> will be equal to the
15766: total number of versions of the data that have been stored. The
15767: C<timestamp> attribute will be the UNIX time the hash was
15768: stored. C<keys> is available in every historical section to list which
15769: keys were added or changed at a specific historical revision of a
15770: hash.
15771:
15772: B<Warning>: do not store the hash that restore returns directly. This
15773: will cause a mess since it will restore the historical keys as if the
15774: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15775:
1.394 bowersj2 15776: Calling convention:
1.191 harris41 15777:
1.1172.2.27 raeburn 15778: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 15779: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15780:
1.394 bowersj2 15781: For more detailed information, see lonnet specific documentation.
1.191 harris41 15782:
1.394 bowersj2 15783: =head1 RETURN MESSAGES
1.191 harris41 15784:
1.394 bowersj2 15785: =over 4
1.191 harris41 15786:
1.394 bowersj2 15787: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15788:
1.394 bowersj2 15789: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15790: when the connection is brought back up
1.191 harris41 15791:
1.394 bowersj2 15792: =item * B<con_failed>: unable to contact remote host and unable to save message
15793: for later delivery
1.191 harris41 15794:
1.967 bisitz 15795: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15796:
1.394 bowersj2 15797: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15798: that was requested
1.191 harris41 15799:
1.243 albertel 15800: =back
1.191 harris41 15801:
1.243 albertel 15802: =head1 PUBLIC SUBROUTINES
1.191 harris41 15803:
1.243 albertel 15804: =head2 Session Environment Functions
1.191 harris41 15805:
1.243 albertel 15806: =over 4
1.191 harris41 15807:
1.394 bowersj2 15808: =item *
15809: X<appenv()>
1.949 raeburn 15810: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15811: the user envirnoment file, and will be restored for each access this
1.620 albertel 15812: user makes during this session, also modifies the %env for the current
1.949 raeburn 15813: process. Optional rolesarrayref - if defined contains a reference to an array
15814: of roles which are exempt from the restriction on modifying user.role entries
15815: in the user's environment.db and in %env.
1.191 harris41 15816:
15817: =item *
1.394 bowersj2 15818: X<delenv()>
1.987 raeburn 15819: B<delenv($delthis,$regexp)>: removes all items from the session
15820: environment file that begin with $delthis. If the
15821: optional second arg - $regexp - is true, $delthis is treated as a
15822: regular expression, otherwise \Q$delthis\E is used.
15823: The values are also deleted from the current processes %env.
1.191 harris41 15824:
1.795 albertel 15825: =item * get_env_multiple($name)
15826:
15827: gets $name from the %env hash, it seemlessly handles the cases where multiple
15828: values may be defined and end up as an array ref.
15829:
15830: returns an array of values
15831:
1.243 albertel 15832: =back
15833:
15834: =head2 User Information
1.191 harris41 15835:
1.243 albertel 15836: =over 4
1.191 harris41 15837:
15838: =item *
1.394 bowersj2 15839: X<queryauthenticate()>
15840: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15841: authentication scheme
15842:
15843: =item *
1.394 bowersj2 15844: X<authenticate()>
1.1073 raeburn 15845: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15846: authenticate user from domain's lib servers (first use the current
15847: one). C<$upass> should be the users password.
1.1073 raeburn 15848: $checkdefauth is optional (value is 1 if a check should be made to
15849: authenticate user using default authentication method, and allow
15850: account creation if username does not have account in the domain).
15851: $clientcancheckhost is optional (value is 1 if checking whether the
15852: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15853:
15854: =item *
1.394 bowersj2 15855: X<homeserver()>
15856: B<homeserver($uname,$udom)>: find the server which has
15857: the user's directory and files (there must be only one), this caches
15858: the answer, and also caches if there is a borken connection.
1.191 harris41 15859:
15860: =item *
1.394 bowersj2 15861: X<idget()>
15862: B<idget($udom,@ids)>: find the usernames behind a list of IDs
15863: (IDs are a unique resource in a domain, there must be only 1 ID per
15864: username, and only 1 username per ID in a specific domain) (returns
15865: hash: id=>name,id=>name)
1.191 harris41 15866:
15867: =item *
1.394 bowersj2 15868: X<idrget()>
15869: B<idrget($udom,@unames)>: find the IDs behind a list of
15870: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15871:
15872: =item *
1.394 bowersj2 15873: X<idput()>
15874: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 15875:
15876: =item *
1.394 bowersj2 15877: X<rolesinit()>
1.1169 droeschl 15878: B<rolesinit($udom,$username)>: get user privileges.
15879: returns user role, first access and timer interval hashes
1.243 albertel 15880:
15881: =item *
1.1171 droeschl 15882: X<privileged()>
15883: B<privileged($username,$domain)>: returns a true if user has a
15884: privileged and active role (i.e. su or dc), false otherwise.
15885:
15886: =item *
1.551 albertel 15887: X<getsection()>
15888: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15889: course $cname, return section name/number or '' for "not in course"
15890: and '-1' for "no section"
15891:
15892: =item *
1.394 bowersj2 15893: X<userenvironment()>
15894: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15895: passed in @what from the requested user's environment, returns a hash
15896:
1.858 raeburn 15897: =item *
15898: X<userlog_query()>
1.859 albertel 15899: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15900: activity.log file. %filters defines filters applied when parsing the
15901: log file. These can be start or end timestamps, or the type of action
15902: - log to look for Login or Logout events, check for Checkin or
15903: Checkout, role for role selection. The response is in the form
15904: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15905: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15906:
1.243 albertel 15907: =back
15908:
15909: =head2 User Roles
15910:
15911: =over 4
15912:
15913: =item *
15914:
1.1172.2.65 raeburn 15915: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15916: returns codes for allowed actions.
15917:
15918: The first argument is required, all others are optional.
15919:
15920: $priv is the privilege being checked.
15921: $uri contains additional information about what is being checked for access (e.g.,
15922: URL, course ID etc.).
15923: $symb is the unique resource instance identifier in a course; if needed,
15924: but not provided, it will be retrieved via a call to &symbread().
15925: $role is the role for which a priv is being checked (only used if priv is evb).
15926: $clientip is the user's IP address (only used when checking for access to portfolio
15927: files).
15928: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15929: prevents recursive calls to &allowed.
15930:
1.243 albertel 15931: F: full access
15932: U,I,K: authentication modes (cxx only)
15933: '': forbidden
15934: 1: user needs to choose course
15935: 2: browse allowed
1.766 albertel 15936: A: passphrase authentication needed
1.1172.2.65 raeburn 15937: B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146. .1(raebu 15938:22): D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15939:
15940: =item *
15941:
1.1172.2.13 raeburn 15942: constructaccess($url,$setpriv) : check for access to construction space URL
15943:
15944: See if the owner domain and name in the URL match those in the
15945: expected environment. If so, return three element list
15946: ($ownername,$ownerdomain,$ownerhome).
15947:
15948: Otherwise return the null string.
15949:
15950: If second argument 'setpriv' is true, it assigns the privileges,
15951: and returns the same three element list, unless the owner has
15952: blocked "ad hoc" Domain Coordinator access to the Author Space,
15953: in which case the null string is returned.
15954:
15955: =item *
15956:
1.1172.2.84 raeburn 15957: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15958: define a custom role rolename set privileges in format of lonTabs/roles.tab
15959: for system, domain, and course level. $uname and $udom are optional (current
15960: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15961:
15962: =item *
15963:
1.988 raeburn 15964: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15965: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15966: $type is Course (default) or Community.
1.988 raeburn 15967: If $forcedefault evaluates to true, text returned will be default
15968: text for $type. Otherwise, if this is a course, the text returned
15969: will be a custom name for the role (if defined in the course's
15970: environment). If no custom name is defined the default is returned.
15971:
1.832 raeburn 15972: =item *
15973:
1.1172.2.23 raeburn 15974: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15975: All arguments are optional. Returns a hash of a roles, either for
15976: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15977: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15978: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15979: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15980: For each key, value is set to colon-separated start and end times for
15981: the role. If no username and domain are specified, will default to
1.934 raeburn 15982: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15983: of role statuses (active, future or previous), roles
15984: (e.g., cc,in, st etc.) and domains of the roles which can be used
15985: to restrict the list of roles reported. If no array ref is
15986: provided for types, will default to return only active roles.
1.834 albertel 15987:
1.1172.2.13 raeburn 15988: =item *
15989:
15990: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15991: user: $uname:$udom has a role in the course: $cdom_$cnum.
15992:
15993: Additional optional arguments are: $type (if role checking is to be restricted
15994: to certain user status types -- previous (expired roles), active (currently
15995: available roles) or future (roles available in the future), and
15996: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15997: have active Domain Coordinator role in course's domain or in additional
15998: domains (specified in 'Domains to check for privileged users' in course
15999: environment -- set via: Course Settings -> Classlists and staff listing).
16000:
16001: =item *
16002:
16003: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16004: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16005: $possdomains and $possroles are optional array refs -- to domains to check and
16006: roles to check. If $possdomains is not specified, a dump will be done of the
16007: users' roles.db to check for a dc or su role in any domain. This can be
16008: time consuming if &privileged is called repeatedly (e.g., when displaying a
16009: classlist), so in such cases, supplying a $possdomains array is preferred, as
16010: this then allows &privileged_by_domain() to be used, which caches the identity
16011: of privileged users, eliminating the need for repeated calls to &dump().
16012:
16013: =item *
16014:
16015: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16016: where the outer hash keys are domains specified in the $possdomains array ref,
16017: next inner hash keys are privileged roles specified in the $roles array ref,
16018: and the innermost hash contains key = value pairs for username:domain = end:start
16019: for active or future "privileged" users with that role in that domain. To avoid
16020: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16021: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 16022:
1.243 albertel 16023: =back
16024:
16025: =head2 User Modification
16026:
16027: =over 4
16028:
16029: =item *
16030:
1.957 raeburn 16031: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16032: user for the level given by URL. Optional start and end dates (leave empty
16033: string or zero for "no date")
1.191 harris41 16034:
16035: =item *
16036:
1.243 albertel 16037: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16038: change a users, password, possible return values are: ok,
16039: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16040: refused
1.191 harris41 16041:
16042: =item *
16043:
1.243 albertel 16044: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16045:
16046: =item *
16047:
1.1058 raeburn 16048: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16049: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16050:
16051: will update user information (firstname,middlename,lastname,generation,
16052: permanentemail), and if forceid is true, student/employee ID also.
16053: A user's institutional affiliation(s) can also be updated.
16054: User information fields will not be overwritten with empty entries
16055: unless the field is included in the $candelete array reference.
16056: This array is included when a single user is modified via "Manage Users",
16057: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16058:
16059: =item *
16060:
1.286 matthew 16061: modifystudent
16062:
1.957 raeburn 16063: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 16064: The course id is resolved based on the current user's environment.
16065: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16066: associated with a course.
16067:
1.297 matthew 16068: This call is essentially a wrapper for lonnet::modifyuser and
16069: lonnet::modify_student_enrollment
1.286 matthew 16070:
16071: Inputs:
16072:
16073: =over 4
16074:
1.957 raeburn 16075: =item B<$udom> Student's loncapa domain
1.286 matthew 16076:
1.957 raeburn 16077: =item B<$uname> Student's loncapa login name
1.286 matthew 16078:
1.964 bisitz 16079: =item B<$uid> Student/Employee ID
1.286 matthew 16080:
1.957 raeburn 16081: =item B<$umode> Student's authentication mode
1.286 matthew 16082:
1.957 raeburn 16083: =item B<$upass> Student's password
1.286 matthew 16084:
1.957 raeburn 16085: =item B<$first> Student's first name
1.286 matthew 16086:
1.957 raeburn 16087: =item B<$middle> Student's middle name
1.286 matthew 16088:
1.957 raeburn 16089: =item B<$last> Student's last name
1.286 matthew 16090:
1.957 raeburn 16091: =item B<$gene> Student's generation
1.286 matthew 16092:
1.957 raeburn 16093: =item B<$usec> Student's section in course
1.286 matthew 16094:
16095: =item B<$end> Unix time of the roles expiration
16096:
16097: =item B<$start> Unix time of the roles start date
16098:
16099: =item B<$forceid> If defined, allow $uid to be changed
16100:
16101: =item B<$desiredhome> server to use as home server for student
16102:
1.957 raeburn 16103: =item B<$email> Student's permanent e-mail address
16104:
16105: =item B<$type> Type of enrollment (auto or manual)
16106:
1.963 raeburn 16107: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16108:
16109: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16110:
1.963 raeburn 16111: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16112:
1.963 raeburn 16113: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16114:
1.1172.2.19 raeburn 16115: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16116:
16117: =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 16118:
1.286 matthew 16119: =back
1.297 matthew 16120:
16121: =item *
16122:
16123: modify_student_enrollment
16124:
1.1172.2.31 raeburn 16125: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16126: 'role.request.course' must be defined for this function to proceed.
16127:
16128: Inputs:
16129:
16130: =over 4
16131:
1.1172.2.31 raeburn 16132: =item $udom, student's domain
1.297 matthew 16133:
1.1172.2.31 raeburn 16134: =item $uname, student's name
1.297 matthew 16135:
1.1172.2.31 raeburn 16136: =item $uid, student's user id
1.297 matthew 16137:
1.1172.2.31 raeburn 16138: =item $first, student's first name
1.297 matthew 16139:
16140: =item $middle
16141:
16142: =item $last
16143:
16144: =item $gene
16145:
16146: =item $usec
16147:
16148: =item $end
16149:
16150: =item $start
16151:
1.957 raeburn 16152: =item $type
16153:
16154: =item $locktype
16155:
16156: =item $cid
16157:
16158: =item $selfenroll
16159:
16160: =item $context
16161:
1.1172.2.19 raeburn 16162: =item $credits, number of credits student will earn from this class
16163:
1.1172.2.76 raeburn 16164: =item $instsec, institutional course section code for student
16165:
1.297 matthew 16166: =back
16167:
1.191 harris41 16168:
16169: =item *
16170:
1.243 albertel 16171: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16172: custom role; give a custom role to a user for the level given by URL. Specify
16173: name and domain of role author, and role name
1.191 harris41 16174:
16175: =item *
16176:
1.243 albertel 16177: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16178:
16179: =item *
16180:
1.243 albertel 16181: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16182:
16183: =back
16184:
16185: =head2 Course Infomation
16186:
16187: =over 4
1.191 harris41 16188:
16189: =item *
16190:
1.1118 foxr 16191: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16192: specified course id, including all environment settings for the
16193: course, the description of the course will be in the hash under the
16194: key 'description'
1.191 harris41 16195:
1.1118 foxr 16196: $options is an optional parameter that if supplied is a hash reference that controls
16197: what how this function works. It has the following key/values:
16198:
16199: =over 4
16200:
16201: =item freshen_cache
16202:
16203: If defined, and the environment cache for the course is valid, it is
16204: returned in the returned hash.
16205:
16206: =item one_time
16207:
16208: If defined, the last cache time is set to _now_
16209:
16210: =item user
16211:
16212: If defined, the supplied username is used instead of the current user.
16213:
16214:
16215: =back
16216:
1.191 harris41 16217: =item *
16218:
1.624 albertel 16219: resdata($name,$domain,$type,@which) : request for current parameter
16220: setting for a specific $type, where $type is either 'course' or 'user',
16221: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 16222: answers for 10 minutes.
1.243 albertel 16223:
1.877 foxr 16224: =item *
16225:
16226: get_courseresdata($courseid, $domain) : dump the entire course resource
16227: data base, returning a hash that is keyed by the resource name and has
16228: values that are the resource value. I believe that the timestamps and
16229: versions are also returned.
16230:
1.243 albertel 16231: =back
16232:
16233: =head2 Course Modification
16234:
16235: =over 4
1.191 harris41 16236:
16237: =item *
16238:
1.243 albertel 16239: writecoursepref($courseid,%prefs) : write preferences (environment
16240: database) for a course
1.191 harris41 16241:
16242: =item *
16243:
1.1011 raeburn 16244: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16245:
16246: =item *
16247:
1.1038 raeburn 16248: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16249:
1.1167 droeschl 16250: =item *
16251:
16252: is_course($courseid), is_course($cdom, $cnum)
16253:
16254: Accepts either a combined $courseid (in the form of domain_courseid) or the
16255: two component version $cdom, $cnum. It checks if the specified course exists.
16256:
16257: Returns:
16258: undef if the course doesn't exist, otherwise
16259: in scalar context the combined courseid.
16260: in list context the two components of the course identifier, domain and
16261: courseid.
16262:
1.243 albertel 16263: =back
16264:
1.1172.2.109 raeburn 16265: =head2 Bubblesheet Configuration
16266:
16267: =over 4
16268:
16269: =item *
16270:
16271: get_scantron_config($which)
16272:
16273: $which - the name of the configuration to parse from the file.
16274:
16275: Parses and returns the bubblesheet configuration line selected as a
16276: hash of configuration file fields.
16277:
16278:
16279: Returns:
16280: If the named configuration is not in the file, an empty
16281: hash is returned.
16282:
16283: a hash with the fields
16284: name - internal name for the this configuration setup
16285: description - text to display to operator that describes this config
16286: CODElocation - if 0 or the string 'none'
16287: - no CODE exists for this config
16288: if -1 || the string 'letter'
16289: - a CODE exists for this config and is
16290: a string of letters
16291: Unsupported value (but planned for future support)
16292: if a positive integer
16293: - The CODE exists as the first n items from
16294: the question section of the form
16295: if the string 'number'
16296: - The CODE exists for this config and is
16297: a string of numbers
16298: CODEstart - (only matter if a CODE exists) column in the line where
16299: the CODE starts
16300: CODElength - length of the CODE
16301: IDstart - column where the student/employee ID starts
16302: IDlength - length of the student/employee ID info
16303: Qstart - column where the information from the bubbled
16304: 'questions' start
16305: Qlength - number of columns comprising a single bubble line from
16306: the sheet. (usually either 1 or 10)
16307: Qon - either a single character representing the character used
16308: to signal a bubble was chosen in the positional setup, or
16309: the string 'letter' if the letter of the chosen bubble is
16310: in the final, or 'number' if a number representing the
16311: chosen bubble is in the file (1->A 0->J)
16312: Qoff - the character used to represent that a bubble was
16313: left blank
16314: PaperID - if the scanning process generates a unique number for each
16315: sheet scanned the column that this ID number starts in
16316: PaperIDlength - number of columns that comprise the unique ID number
16317: for the sheet of paper
16318: FirstName - column that the first name starts in
16319: FirstNameLength - number of columns that the first name spans
16320: LastName - column that the last name starts in
16321: LastNameLength - number of columns that the last name spans
16322: BubblesPerRow - number of bubbles available in each row used to
16323: bubble an answer. (If not specified, 10 assumed).
16324:
16325:
16326: =item *
16327:
16328: get_scantronformat_file($cdom)
16329:
16330: $cdom - the course's domain (optional); if not supplied, uses
16331: domain for current $env{'request.course.id'}.
16332:
16333: Returns an array containing lines from the scantron format file for
16334: the domain of the course.
16335:
16336: If a url for a custom.tab file is listed in domain's configuration.db,
16337: lines are from this file.
16338:
16339: Otherwise, if a default.tab has been published in RES space by the
16340: domainconfig user, lines are from this file.
16341:
16342: Otherwise, fall back to getting lines from the legacy file on the
16343: local server: /home/httpd/lonTabs/default_scantronformat.tab
16344:
16345: =back
16346:
1.243 albertel 16347: =head2 Resource Subroutines
16348:
16349: =over 4
1.191 harris41 16350:
16351: =item *
16352:
1.243 albertel 16353: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16354:
16355: =item *
16356:
1.243 albertel 16357: repcopy($filename) : subscribes to the requested file, and attempts to
16358: replicate from the owning library server, Might return
1.607 raeburn 16359: 'unavailable', 'not_found', 'forbidden', 'ok', or
16360: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16361: resource. Expects the local filesystem pathname
16362: (/home/httpd/html/res/....)
16363:
16364: =back
16365:
16366: =head2 Resource Information
16367:
16368: =over 4
1.191 harris41 16369:
16370: =item *
16371:
1.1172.2.28 raeburn 16372: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16373: and returns the value of a variety of different possible values,
16374: $varname should be a request string, and the other parameters can be
16375: used to specify who and what one is asking about. Ordinarily, $cid
16376: does not need to be specified, as it is retrived from
16377: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16378: within lonuserstate::loadmap() when initializing a course, before
16379: $env{'request.course.id'} has been set, so it needs to be provided
16380: in that one case.
1.243 albertel 16381:
16382: Possible values for $varname are environment.lastname (or other item
16383: from the envirnment hash), user.name (or someother aspect about the
16384: user), resource.0.maxtries (or some other part and parameter of a
16385: resource)
1.204 albertel 16386:
16387: =item *
16388:
1.243 albertel 16389: directcondval($number) : get current value of a condition; reads from a state
16390: string
1.204 albertel 16391:
16392: =item *
16393:
1.243 albertel 16394: condval($condidx) : value of condition index based on state
1.204 albertel 16395:
16396: =item *
16397:
1.1172.2.146. .13(raeb 16398:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16399: resource's metadata, $what should be either a specific key, or either
16400: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146. .13(raeb 16401:-23): packages that this resource currently uses, the last 3 arguments are
16402:-23): only used internally for recursive metadata.
16403:-23):
16404:-23): the toolsymb is only used where the uri is for an external tool (for which
16405:-23): the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16406:
16407: this function automatically caches all requests
1.191 harris41 16408:
16409: =item *
16410:
1.243 albertel 16411: metadata_query($query,$custom,$customshow) : make a metadata query against the
16412: network of library servers; returns file handle of where SQL and regex results
16413: will be stored for query
1.191 harris41 16414:
16415: =item *
16416:
1.1172.2.66 raeburn 16417: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16418: return symbolic list entry (all arguments optional).
16419:
16420: Args: filename is the filename (including path) for the file for which a symb
16421: is required; donotrecurse, if true will prevent calls to allowed() being made
16422: to check access status if more than one resource was found in the bighash
16423: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16424: a randompick); ignorecachednull, if true will prevent a symb of '' being
16425: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16426: cause possible symbs to be checked to determine if they are subject to content
16427: blocking, if so they will not be included as possible symbs; possibles is a
16428: ref to a hash, which, as a side effect, will be populated with all possible
16429: symbs (content blocking not tested).
16430:
1.243 albertel 16431: returns the data handle
1.191 harris41 16432:
16433: =item *
16434:
1.1172.2.17 raeburn 16435: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 16436: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16437: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 16438: on failure, user must be in a course, as it assumes the existence of
16439: the course initial hash, and uses $env('request.course.id'}. The third
16440: arg is an optional reference to a scalar. If this arg is passed in the
16441: call to symbverify, it will be set to 1 if the symb has been set to be
16442: encrypted; otherwise it will be null.
1.243 albertel 16443:
1.191 harris41 16444: =item *
16445:
1.243 albertel 16446: symbclean($symb) : removes versions numbers from a symb, returns the
16447: cleaned symb
1.191 harris41 16448:
16449: =item *
16450:
1.243 albertel 16451: is_on_map($uri) : checks if the $uri is somewhere on the current
16452: course map, user must be in a course for it to work.
1.191 harris41 16453:
16454: =item *
16455:
1.243 albertel 16456: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16457:
16458: =item *
16459:
1.243 albertel 16460: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16461: a random seed, all arguments are optional, if they aren't sent it uses the
16462: environment to derive them. Note: if symb isn't sent and it can't get one
16463: from &symbread it will use the current time as its return value
1.191 harris41 16464:
16465: =item *
16466:
1.243 albertel 16467: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16468: unfakeable, receipt
1.191 harris41 16469:
16470: =item *
16471:
1.620 albertel 16472: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16473:
16474: =item *
16475:
1.243 albertel 16476: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16477:
16478: =item *
16479:
1.243 albertel 16480: 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 16481:
16482: =item *
16483:
1.243 albertel 16484: 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 16485:
16486: =item *
16487:
1.243 albertel 16488: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16489:
16490: =item *
16491:
1.243 albertel 16492: devalidate($symb) : devalidate temporary spreadsheet calculations,
16493: forcing spreadsheet to reevaluate the resource scores next time.
16494:
1.1172.2.13 raeburn 16495: =item *
16496:
16497: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16498: when viewing in course context.
16499:
16500: input: six args -- filename (decluttered), course number, course domain,
16501: url, symb (if registered) and group (if this is a
16502: group item -- e.g., bulletin board, group page etc.).
16503:
16504: output: array of five scalars --
16505: $cfile -- url for file editing if editable on current server
16506: $home -- homeserver of resource (i.e., for author if published,
16507: or course if uploaded.).
16508: $switchserver -- 1 if server switch will be needed.
16509: $forceedit -- 1 if icon/link should be to go to edit mode
16510: $forceview -- 1 if icon/link should be to go to view mode
16511:
16512: =item *
16513:
16514: is_course_upload($file,$cnum,$cdom)
16515:
16516: Used in course context to determine if current file was uploaded to
16517: the course (i.e., would be found in /userfiles/docs on the course's
16518: homeserver.
16519:
16520: input: 3 args -- filename (decluttered), course number and course domain.
16521: output: boolean -- 1 if file was uploaded.
16522:
1.243 albertel 16523: =back
16524:
16525: =head2 Storing/Retreiving Data
16526:
16527: =over 4
1.191 harris41 16528:
16529: =item *
16530:
1.1172.2.64 raeburn 16531: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16532: permanently for this url; hashref needs to be given and should be a \%hashname;
16533: the remaining args aren't required and if they aren't passed or are '' they will
16534: be derived from the env (with the exception of $laststore, which is an
16535: optional arg used when a user's submission is stored in grading).
16536: $laststore is $version=$timestamp, where $version is the most recent version
16537: number retrieved for the corresponding $symb in the $namespace db file, and
16538: $timestamp is the timestamp for that transaction (UNIX time).
16539: $laststore is currently only passed when cstore() is called by
16540: structuretags::finalize_storage().
1.191 harris41 16541:
16542: =item *
16543:
1.1172.2.64 raeburn 16544: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16545: but uses critical subroutine
1.191 harris41 16546:
16547: =item *
16548:
1.243 albertel 16549: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16550: all args are optional
1.191 harris41 16551:
16552: =item *
16553:
1.717 albertel 16554: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16555: dumps the complete (or key matching regexp) namespace into a hash
16556: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16557: normally &store()ed into
16558:
16559: $range should be either an integer '100' (give me the first 100
16560: matching records)
16561: or be two integers sperated by a - with no spaces
16562: '30-50' (give me the 30th through the 50th matching
16563: records)
16564:
16565:
16566: =item *
16567:
1.1172.2.59 raeburn 16568: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16569: replaces a &store() version of data with a replacement set of data
16570: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 16571: reference. If $tolog is true, the transaction is logged in the courselog
16572: with an action=PUTSTORE.
1.717 albertel 16573:
16574: =item *
16575:
1.243 albertel 16576: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16577: works very similar to store/cstore, but all data is stored in a
16578: temporary location and can be reset using tmpreset, $storehash should
16579: be a hash reference, returns nothing on success
1.191 harris41 16580:
16581: =item *
16582:
1.243 albertel 16583: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16584: similar to restore, but all data is stored in a temporary location and
16585: can be reset using tmpreset. Returns a hash of values on success,
16586: error string otherwise.
1.191 harris41 16587:
16588: =item *
16589:
1.243 albertel 16590: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16591: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16592:
16593: =item *
16594:
1.243 albertel 16595: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16596: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16597:
16598: =item *
16599:
1.243 albertel 16600: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16601: namesp ($udom and $uname are optional)
1.191 harris41 16602:
16603: =item *
16604:
1.702 albertel 16605: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16606: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16607: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16608:
1.702 albertel 16609: $range should be either an integer '100' (give me the first 100
16610: matching records)
16611: or be two integers sperated by a - with no spaces
16612: '30-50' (give me the 30th through the 50th matching
16613: records)
1.449 matthew 16614: =item *
16615:
16616: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16617: $store can be a scalar, an array reference, or if the amount to be
16618: incremented is > 1, a hash reference.
16619:
16620: ($udom and $uname are optional)
1.191 harris41 16621:
16622: =item *
16623:
1.243 albertel 16624: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16625: ($udom and $uname are optional)
1.191 harris41 16626:
16627: =item *
16628:
1.243 albertel 16629: cput($namespace,$storehash,$udom,$uname) : critical put
16630: ($udom and $uname are optional)
1.191 harris41 16631:
16632: =item *
16633:
1.748 albertel 16634: newput($namespace,$storehash,$udom,$uname) :
16635:
16636: Attempts to store the items in the $storehash, but only if they don't
16637: currently exist, if this succeeds you can be certain that you have
16638: successfully created a new key value pair in the $namespace db.
16639:
16640:
16641: Args:
16642: $namespace: name of database to store values to
16643: $storehash: hashref to store to the db
16644: $udom: (optional) domain of user containing the db
16645: $uname: (optional) name of user caontaining the db
16646:
16647: Returns:
16648: 'ok' -> succeeded in storing all keys of $storehash
16649: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16650: least <key> already existed in the db (other
16651: requested keys may also already exist)
1.967 bisitz 16652: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16653: 'con_lost' -> unable to contact request server
16654: 'refused' -> action was not allowed by remote machine
16655:
16656:
16657: =item *
16658:
1.243 albertel 16659: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16660: reference filled in from namesp (encrypts the return communication)
16661: ($udom and $uname are optional)
1.191 harris41 16662:
16663: =item *
16664:
1.243 albertel 16665: log($udom,$name,$home,$message) : write to permanent log for user; use
16666: critical subroutine
16667:
1.806 raeburn 16668: =item *
16669:
1.860 raeburn 16670: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16671: array reference filled in from namespace found in domain level on either
16672: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16673:
16674: =item *
16675:
1.860 raeburn 16676: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16677: domain level either on specified domain server ($uhome) or primary domain
16678: server ($udom and $uhome are optional)
1.806 raeburn 16679:
1.943 raeburn 16680: =item *
16681:
1.1172.2.35 raeburn 16682: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16683: for: authentication, language, quotas, timezone, date locale, and portal URL in
16684: the target domain.
16685:
16686: May also include additional key => value pairs for the following groups:
16687:
16688: =over
16689:
16690: =item
16691: disk quotas (MB allocated by default to portfolios and authoring spaces).
16692:
16693: =over
16694:
16695: =item defaultquota, authorquota
16696:
16697: =back
16698:
16699: =item
16700: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16701: portfolio for users).
16702:
16703: =over
16704:
16705: =item
16706: aboutme, blog, webdav, portfolio
16707:
16708: =back
16709:
16710: =item
16711: requestcourses: ability to request courses, and how requests are processed.
16712:
16713: =over
16714:
16715: =item
1.1172.2.37 raeburn 16716: official, unofficial, community, textbook
1.1172.2.35 raeburn 16717:
16718: =back
16719:
16720: =item
16721: inststatus: types of institutional affiliation, and order in which they are displayed.
16722:
16723: =over
16724:
16725: =item
1.1172.2.44 raeburn 16726: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 16727:
16728: =back
16729:
16730: =item
16731: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16732: for course's uploaded content.
16733:
16734: =over
16735:
16736: =item
1.1172.2.68 raeburn 16737: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
16738: communityquota, textbookquota
1.1172.2.35 raeburn 16739:
16740: =back
16741:
16742: =item
16743: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16744: on your servers.
16745:
16746: =over
16747:
16748: =item
16749: remotesessions, hostedsessions
16750:
16751: =back
16752:
16753: =back
16754:
16755: In cases where a domain coordinator has never used the "Set Domain Configuration"
16756: utility to create a configuration.db file on a domain's primary library server
16757: only the following domain defaults: auth_def, auth_arg_def, lang_def
16758: -- corresponding values are authentication type (internal, krb4, krb5,
16759: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16760: will be available. Values are retrieved from cache (if current), unless the
16761: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16762: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16763:
16764: Typical usage:
1.943 raeburn 16765:
1.1172.2.35 raeburn 16766: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16767:
1.243 albertel 16768: =back
16769:
16770: =head2 Network Status Functions
16771:
16772: =over 4
1.191 harris41 16773:
16774: =item *
16775:
1.1137 raeburn 16776: dirlist() : return directory list based on URI (first arg).
16777:
16778: Inputs: 1 required, 5 optional.
16779:
16780: =over
16781:
16782: =item
16783: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16784:
16785: =item
16786: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16787:
16788: =item
16789: $username - username of user/course to be listed. Extracted from $uri if absent.
16790:
16791: =item
16792: $getpropath - boolean: 1 if prepend path using &propath().
16793:
16794: =item
16795: $getuserdir - boolean: 1 if prepend path for "userfiles".
16796:
16797: =item
16798: $alternateRoot - path to prepend in place of path from $uri.
16799:
16800: =back
16801:
16802: Returns: Array of up to two items.
16803:
16804: =over
16805:
16806: a reference to an array of files/subdirectories
16807:
16808: =over
16809:
16810: Each element in the array of files/subdirectories is a & separated list of
16811: item name and the result of running stat on the item. If dirlist was requested
16812: for a file instead of a directory, the item name will be ''. For a directory
16813: listing, if the item is a metadata file, the element will end &N&M
16814: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16815: default copyright set (1).
16816:
16817: =back
16818:
16819: a scalar containing error condition (if encountered).
16820:
16821: =over
16822:
16823: =item
16824: no_host (no homeserver identified for $username:$domain).
16825:
16826: =item
16827: no_such_host (server contacted for listing not identified as valid host).
16828:
16829: =item
16830: con_lost (connection to remote server failed).
16831:
16832: =item
16833: refused (invalid $username:$domain received on lond side).
16834:
16835: =item
16836: no_such_dir (directory at specified path on lond side does not exist).
16837:
16838: =item
16839: empty (directory at specified path on lond side is empty).
16840:
16841: =over
16842:
16843: This is currently not encountered because the &ls3, &ls2,
16844: &ls (_handler) routines on the lond side do not filter out
16845: . and .. from a directory listing.
16846:
16847: =back
16848:
16849: =back
16850:
16851: =back
1.191 harris41 16852:
16853: =item *
16854:
1.243 albertel 16855: spareserver() : find server with least workload from spare.tab
16856:
1.986 foxr 16857:
16858: =item *
16859:
16860: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16861: if there is no corresponding loncapa host.
16862:
1.243 albertel 16863: =back
16864:
1.986 foxr 16865:
1.243 albertel 16866: =head2 Apache Request
16867:
16868: =over 4
1.191 harris41 16869:
16870: =item *
16871:
1.243 albertel 16872: ssi($url,%hash) : server side include, does a complete request cycle on url to
16873: localhost, posts hash
16874:
16875: =back
16876:
16877: =head2 Data to String to Data
16878:
16879: =over 4
1.191 harris41 16880:
16881: =item *
16882:
1.243 albertel 16883: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16884: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16885:
16886: =item *
16887:
1.243 albertel 16888: hashref2str($hashref) : convert a hashref into a string complete with
16889: escaping and '=' and '&' separators, supports elements that are
16890: arrayrefs and hashrefs
1.191 harris41 16891:
16892: =item *
16893:
1.243 albertel 16894: arrayref2str($arrayref) : convert an arrayref into a string complete
16895: with escaping and '&' separators, supports elements that are arrayrefs
16896: and hashrefs
1.191 harris41 16897:
16898: =item *
16899:
1.243 albertel 16900: str2hash($string) : convert string to hash using unescaping and
16901: splitting on '=' and '&', supports elements that are arrayrefs and
16902: hashrefs
1.191 harris41 16903:
16904: =item *
16905:
1.243 albertel 16906: str2array($string) : convert string to hash using unescaping and
16907: splitting on '&', supports elements that are arrayrefs and hashrefs
16908:
16909: =back
16910:
16911: =head2 Logging Routines
16912:
16913:
16914: These routines allow one to make log messages in the lonnet.log and
16915: lonnet.perm logfiles.
1.191 harris41 16916:
1.1119 foxr 16917: =over 4
16918:
1.191 harris41 16919: =item *
16920:
1.243 albertel 16921: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16922:
16923: =item *
16924:
1.243 albertel 16925: logthis() : append message to the normal lonnet.log file, it gets
16926: preiodically rolled over and deleted.
1.191 harris41 16927:
16928: =item *
16929:
1.243 albertel 16930: logperm() : append a permanent message to lonnet.perm.log, this log
16931: file never gets deleted by any automated portion of the system, only
16932: messages of critical importance should go in here.
16933:
1.1119 foxr 16934:
1.243 albertel 16935: =back
16936:
16937: =head2 General File Helper Routines
16938:
16939: =over 4
1.191 harris41 16940:
16941: =item *
16942:
1.481 raeburn 16943: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16944: (a) files in /uploaded
16945: (i) If a local copy of the file exists -
16946: compares modification date of local copy with last-modified date for
16947: definitive version stored on home server for course. If local copy is
16948: stale, requests a new version from the home server and stores it.
16949: If the original has been removed from the home server, then local copy
16950: is unlinked.
16951: (ii) If local copy does not exist -
16952: requests the file from the home server and stores it.
16953:
16954: If $caller is 'uploadrep':
16955: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16956: for request for files originally uploaded via DOCS.
16957: - returns 'ok' if fresh local copy now available, -1 otherwise.
16958:
16959: Otherwise:
16960: This indicates a call from the content generation phase of the request.
16961: - returns the entire contents of the file or -1.
16962:
16963: (b) files in /res
16964: - returns the entire contents of a file or -1;
16965: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16966:
1.712 albertel 16967:
16968: =item *
16969:
16970: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16971: reference
16972:
16973: returns either a stat() list of data about the file or an empty list
16974: if the file doesn't exist or couldn't find out about it (connection
16975: problems or user unknown)
16976:
1.191 harris41 16977: =item *
16978:
1.243 albertel 16979: filelocation($dir,$file) : returns file system location of a file
16980: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16981: directory that relative $file lookups are to looked in ($dir of /a/dir
16982: and a file of ../bob will become /a/bob)
1.191 harris41 16983:
16984: =item *
16985:
16986: hreflocation($dir,$file) : returns file system location or a URL; same as
16987: filelocation except for hrefs
16988:
16989: =item *
16990:
1.1172.2.49 raeburn 16991: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16992: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16993:
1.243 albertel 16994: =back
16995:
1.608 albertel 16996: =head2 Usererfile file routines (/uploaded*)
16997:
16998: =over 4
16999:
17000: =item *
17001:
17002: userfileupload(): main rotine for putting a file in a user or course's
17003: filespace, arguments are,
17004:
1.620 albertel 17005: formname - required - this is the name of the element in $env where the
1.608 albertel 17006: filename, and the contents of the file to create/modifed exist
1.620 albertel 17007: the filename is in $env{'form.'.$formname.'.filename'} and the
17008: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17009: context - if coursedoc, store the file in the course of the active role
17010: of the current user;
17011: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17012: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17013: subdir - required - subdirectory to put the file in under ../userfiles/
17014: if undefined, it will be placed in "unknown"
17015:
17016: (This routine calls clean_filename() to remove any dangerous
17017: characters from the filename, and then calls finuserfileupload() to
17018: complete the transaction)
17019:
17020: returns either the url of the uploaded file (/uploaded/....) if successful
17021: and /adm/notfound.html if unsuccessful
17022:
17023: =item *
17024:
17025: clean_filename(): routine for cleaing a filename up for storage in
17026: userfile space, argument is:
17027:
17028: filename - proposed filename
17029:
17030: returns: the new clean filename
17031:
17032: =item *
17033:
1.1090 raeburn 17034: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17035: userspace, probably shouldn't be called directly
17036:
17037: docuname: username or courseid of destination for the file
17038: docudom: domain of user/course of destination for the file
17039: formname: same as for userfileupload()
1.1090 raeburn 17040: fname: filename (including subdirectories) for the file
17041: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 17042: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17043: allfiles: reference to hash used to store objects found by parser
17044: codebase: reference to hash used for codebases of java objects found by parser
17045: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17046: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17047: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17048: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17049: context: if 'overwrite', will move the uploaded file from its temporary location to
17050: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17051: mimetype: reference to scalar to accommodate mime type determined
17052: from File::MMagic if $parser = parse.
1.608 albertel 17053:
17054: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17055: and /adm/notfound.html if unsuccessful (or an error message if context
17056: was 'overwrite').
17057:
1.608 albertel 17058:
17059: =item *
17060:
17061: renameuserfile(): renames an existing userfile to a new name
17062:
17063: Args:
17064: docuname: username or courseid of destination for the file
17065: docudom: domain of user/course of destination for the file
17066: old: current file name (including any subdirs under userfiles)
17067: new: desired file name (including any subdirs under userfiles)
17068:
17069: =item *
17070:
17071: mkdiruserfile(): creates a directory is a userfiles dir
17072:
17073: Args:
17074: docuname: username or courseid of destination for the file
17075: docudom: domain of user/course of destination for the file
17076: dir: dir to create (including any subdirs under userfiles)
17077:
17078: =item *
17079:
17080: removeuserfile(): removes a file that exists in userfiles
17081:
17082: Args:
17083: docuname: username or courseid of destination for the file
17084: docudom: domain of user/course of destination for the file
17085: fname: filname to delete (including any subdirs under userfiles)
17086:
17087: =item *
17088:
17089: removeuploadedurl(): convience function for removeuserfile()
17090:
17091: Args:
17092: url: a full /uploaded/... url to delete
17093:
1.747 albertel 17094: =item *
17095:
17096: get_portfile_permissions():
17097: Args:
17098: domain: domain of user or course contain the portfolio files
17099: user: name of user or num of course contain the portfolio files
17100: Returns:
17101: hashref of a dump of the proper file_permissions.db
17102:
17103:
17104: =item *
17105:
17106: get_access_controls():
17107:
17108: Args:
17109: current_permissions: the hash ref returned from get_portfile_permissions()
17110: group: (optional) the group you want the files associated with
17111: file: (optional) the file you want access info on
17112:
17113: Returns:
1.749 raeburn 17114: a hash (keys are file names) of hashes containing
17115: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17116: values are XML containing access control settings (see below)
1.747 albertel 17117:
17118: Internal notes:
17119:
1.749 raeburn 17120: access controls are stored in file_permissions.db as key=value pairs.
17121: key -> path to file/file_name\0uniqueID:scope_end_start
17122: where scope -> public,guest,course,group,domains or users.
17123: end -> UNIX time for end of access (0 -> no end date)
17124: start -> UNIX time for start of access
17125:
17126: value -> XML description of access control
17127: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17128: <start></start>
17129: <end></end>
17130:
17131: <password></password> for scope type = guest
17132:
17133: <domain></domain> for scope type = course or group
17134: <number></number>
17135: <roles id="">
17136: <role></role>
17137: <access></access>
17138: <section></section>
17139: <group></group>
17140: </roles>
17141:
17142: <dom></dom> for scope type = domains
17143:
17144: <users> for scope type = users
17145: <user>
17146: <uname></uname>
17147: <udom></udom>
17148: </user>
17149: </users>
17150: </scope>
17151:
17152: Access data is also aggregated for each file in an additional key=value pair:
17153: key -> path to file/file_name\0accesscontrol
17154: value -> reference to hash
17155: hash contains key = value pairs
17156: where key = uniqueID:scope_end_start
17157: value = UNIX time record was last updated
17158:
17159: Used to improve speed of look-ups of access controls for each file.
17160:
17161: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17162:
1.1172.2.13 raeburn 17163: =item *
17164:
1.749 raeburn 17165: modify_access_controls():
17166:
17167: Modifies access controls for a portfolio file
17168: Args
17169: 1. file name
17170: 2. reference to hash of required changes,
17171: 3. domain
17172: 4. username
17173: where domain,username are the domain of the portfolio owner
17174: (either a user or a course)
17175:
17176: Returns:
17177: 1. result of additions or updates ('ok' or 'error', with error message).
17178: 2. result of deletions ('ok' or 'error', with error message).
17179: 3. reference to hash of any new or updated access controls.
17180: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17181: key = integer (inbound ID)
1.1172.2.13 raeburn 17182: value = uniqueID
17183:
17184: =item *
17185:
17186: get_timebased_id():
17187:
17188: Attempts to get a unique timestamp-based suffix for use with items added to a
17189: course via the Course Editor (e.g., folders, composite pages,
17190: group bulletin boards).
17191:
17192: Args: (first three required; six others optional)
17193:
17194: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17195: docssequence, or name of group
17196:
17197: 2. keyid (alphanumeric): name of temporary locking key in hash,
17198: e.g., num, boardids
17199:
17200: 3. namespace: name of gdbm file used to store suffixes already assigned;
17201: file will be named nohist_namespace.db
17202:
17203: 4. cdom: domain of course; default is current course domain from %env
17204:
17205: 5. cnum: course number; default is current course number from %env
17206:
17207: 6. idtype: set to concat if an additional digit is to be appended to the
17208: unix timestamp to form the suffix, if the plain timestamp is already
17209: in use. Default is to not do this, but simply increment the unix
17210: timestamp by 1 until a unique key is obtained.
17211:
17212: 7. who: holder of locking key; defaults to user:domain for user.
17213:
17214: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17215: retrying); default is 3.
17216:
17217: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17218:
17219: Returns:
17220:
17221: 1. suffix obtained (numeric)
17222:
17223: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17224:
17225: 3. error: contains (localized) error message if an error occurred.
17226:
1.747 albertel 17227:
1.608 albertel 17228: =back
17229:
1.243 albertel 17230: =head2 HTTP Helper Routines
17231:
17232: =over 4
17233:
1.191 harris41 17234: =item *
17235:
17236: escape() : unpack non-word characters into CGI-compatible hex codes
17237:
17238: =item *
17239:
17240: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17241:
1.243 albertel 17242: =back
17243:
17244: =head1 PRIVATE SUBROUTINES
17245:
17246: =head2 Underlying communication routines (Shouldn't call)
17247:
17248: =over 4
17249:
17250: =item *
17251:
17252: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17253:
17254: =item *
17255:
17256: reply() : uses subreply to send a message to remote machine, logs all failures
17257:
17258: =item *
17259:
17260: critical() : passes a critical message to another server; if cannot
17261: get through then place message in connection buffer directory and
17262: returns con_delayed, if incapable of saving message, returns
17263: con_failed
17264:
17265: =item *
17266:
17267: reconlonc() : tries to reconnect lonc client processes.
17268:
17269: =back
17270:
17271: =head2 Resource Access Logging
17272:
17273: =over 4
17274:
17275: =item *
17276:
17277: flushcourselogs() : flush (save) buffer logs and access logs
17278:
17279: =item *
17280:
17281: courselog($what) : save message for course in hash
17282:
17283: =item *
17284:
17285: courseacclog($what) : save message for course using &courselog(). Perform
17286: special processing for specific resource types (problems, exams, quizzes, etc).
17287:
1.191 harris41 17288: =item *
17289:
17290: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17291: as a PerlChildExitHandler
1.243 albertel 17292:
17293: =back
17294:
17295: =head2 Other
17296:
17297: =over 4
17298:
17299: =item *
17300:
17301: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17302:
17303: =back
17304:
17305: =cut
1.877 foxr 17306:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>