Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.37
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.37! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.36 2013/12/13 02:28:45 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;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
674: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
888: my ($try_server, $spare_server, $lowest_load) = @_;
889:
890: my $loadans = &reply('load', $try_server);
891: my $userloadans = &reply('userload',$try_server);
892:
893: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 894: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 895: }
896:
897: my $load;
898: if ($loadans =~ /\d/) {
899: if ($userloadans =~ /\d/) {
900: #both are numbers, pick the bigger one
901: $load = ($loadans > $userloadans) ? $loadans
902: : $userloadans;
1.411 albertel 903: } else {
1.784 albertel 904: $load = $loadans;
1.411 albertel 905: }
1.784 albertel 906: } else {
907: $load = $userloadans;
908: }
909:
910: if (($load =~ /\d/) && ($load < $lowest_load)) {
911: $spare_server = $try_server;
912: $lowest_load = $load;
1.370 albertel 913: }
1.784 albertel 914: return ($spare_server,$lowest_load);
1.202 matthew 915: }
1.914 albertel 916:
917: # --------------------------- ask offload servers if user already has a session
918: sub find_existing_session {
919: my ($udom,$uname) = @_;
1.1123 raeburn 920: my $spareshash = &this_host_spares($udom);
921: if (ref($spareshash) eq 'HASH') {
922: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
923: foreach my $try_server (@{ $spareshash->{'primary'} }) {
924: return $try_server if (&has_user_session($try_server, $udom, $uname));
925: }
926: }
927: if (ref($spareshash->{'default'}) eq 'ARRAY') {
928: foreach my $try_server (@{ $spareshash->{'default'} }) {
929: return $try_server if (&has_user_session($try_server, $udom, $uname));
930: }
931: }
1.914 albertel 932: }
933: return;
934: }
935:
936: # -------------------------------- ask if server already has a session for user
937: sub has_user_session {
938: my ($lonid,$udom,$uname) = @_;
939: my $result = &reply(join(':','userhassession',
940: map {&escape($_)} ($udom,$uname)),$lonid);
941: return 1 if ($result eq 'ok');
942:
943: return 0;
944: }
945:
1.1076 raeburn 946: # --------- determine least loaded server in a user's domain which allows login
947:
948: sub choose_server {
1.1115 raeburn 949: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 950: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 951: my %servers = &get_servers($udom);
1.1076 raeburn 952: my $lowest_load = 30000;
1.1151 raeburn 953: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 954: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 955: my $loginvia;
956: if ($checkloginvia) {
957: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 958: if ($loginvia) {
959: my ($server,$path) = split(/:/,$loginvia);
960: ($login_host, $lowest_load) =
961: &compare_server_load($server, $login_host, $lowest_load);
962: if ($login_host eq $server) {
963: $portal_path = $path;
1.1151 raeburn 964: $isredirect = 1;
1.1116 raeburn 965: }
966: } else {
967: ($login_host, $lowest_load) =
968: &compare_server_load($lonhost, $login_host, $lowest_load);
969: if ($login_host eq $lonhost) {
970: $portal_path = '';
1.1151 raeburn 971: $isredirect = '';
1.1116 raeburn 972: }
973: }
974: } else {
1.1076 raeburn 975: ($login_host, $lowest_load) =
1.1116 raeburn 976: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 977: }
978: }
979: if ($login_host ne '') {
1.1116 raeburn 980: $hostname = &hostname($login_host);
1.1076 raeburn 981: }
1.1151 raeburn 982: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 983: }
984:
1.202 matthew 985: # --------------------------------------------- Try to change a user's password
986:
987: sub changepass {
1.799 raeburn 988: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 989: $currentpass = &escape($currentpass);
990: $newpass = &escape($newpass);
1.1030 raeburn 991: my $lonhost = $perlvar{'lonHostID'};
992: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 993: $server);
994: if (! $answer) {
995: &logthis("No reply on password change request to $server ".
996: "by $uname in domain $udom.");
997: } elsif ($answer =~ "^ok") {
998: &logthis("$uname in $udom successfully changed their password ".
999: "on $server.");
1000: } elsif ($answer =~ "^pwchange_failure") {
1001: &logthis("$uname in $udom was unable to change their password ".
1002: "on $server. The action was blocked by either lcpasswd ".
1003: "or pwchange");
1004: } elsif ($answer =~ "^non_authorized") {
1005: &logthis("$uname in $udom did not get their password correct when ".
1006: "attempting to change it on $server.");
1007: } elsif ($answer =~ "^auth_mode_error") {
1008: &logthis("$uname in $udom attempted to change their password despite ".
1009: "not being locally or internally authenticated on $server.");
1010: } elsif ($answer =~ "^unknown_user") {
1011: &logthis("$uname in $udom attempted to change their password ".
1012: "on $server but were unable to because $server is not ".
1013: "their home server.");
1014: } elsif ($answer =~ "^refused") {
1015: &logthis("$server refused to change $uname in $udom password because ".
1016: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1017: } elsif ($answer =~ "invalid_client") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1020: }
1021: return $answer;
1.1 albertel 1022: }
1023:
1.169 harris41 1024: # ----------------------- Try to determine user's current authentication scheme
1025:
1026: sub queryauthenticate {
1027: my ($uname,$udom)=@_;
1.456 albertel 1028: my $uhome=&homeserver($uname,$udom);
1029: if (!$uhome) {
1030: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1031: return 'no_host';
1032: }
1033: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1034: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1035: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1036: }
1.456 albertel 1037: return $answer;
1.169 harris41 1038: }
1039:
1.1 albertel 1040: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1041:
1.1 albertel 1042: sub authenticate {
1.1073 raeburn 1043: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1044: $upass=&escape($upass);
1045: $uname= &LONCAPA::clean_username($uname);
1.836 www 1046: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1047: my $newhome;
1.836 www 1048: if ((!$uhome) || ($uhome eq 'no_host')) {
1049: # Maybe the machine was offline and only re-appeared again recently?
1050: &reconlonc();
1051: # One more
1.952 raeburn 1052: $uhome=&homeserver($uname,$udom,1);
1053: if (($uhome eq 'no_host') && $checkdefauth) {
1054: if (defined(&domain($udom,'primary'))) {
1055: $newhome=&domain($udom,'primary');
1056: }
1057: if ($newhome ne '') {
1058: $uhome = $newhome;
1059: }
1060: }
1.836 www 1061: if ((!$uhome) || ($uhome eq 'no_host')) {
1062: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1063: return 'no_host';
1064: }
1.1 albertel 1065: }
1.1073 raeburn 1066: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1067: if ($answer eq 'authorized') {
1.952 raeburn 1068: if ($newhome) {
1069: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1070: return 'no_account_on_host';
1071: } else {
1072: &logthis("User $uname at $udom authorized by $uhome");
1073: return $uhome;
1074: }
1.471 albertel 1075: }
1076: if ($answer eq 'non_authorized') {
1077: &logthis("User $uname at $udom rejected by $uhome");
1078: return 'no_host';
1.9 www 1079: }
1.471 albertel 1080: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1081: return 'no_host';
1082: }
1083:
1.1073 raeburn 1084: sub can_host_session {
1.1074 raeburn 1085: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1086: my $canhost = 1;
1.1074 raeburn 1087: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1088: if (ref($remotesessions) eq 'HASH') {
1089: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1090: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1091: $canhost = 0;
1092: } else {
1093: $canhost = 1;
1094: }
1095: }
1096: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1097: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1098: $canhost = 1;
1099: } else {
1100: $canhost = 0;
1101: }
1102: }
1103: if ($canhost) {
1104: if ($remotesessions->{'version'} ne '') {
1105: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1106: if ($reqmajor ne '' && $reqminor ne '') {
1107: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1108: my $major = $1;
1109: my $minor = $2;
1110: if (($major < $reqmajor ) ||
1111: (($major == $reqmajor) && ($minor < $reqminor))) {
1112: $canhost = 0;
1113: }
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: }
1121: if ($canhost) {
1122: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1123: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1124: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1125: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1126: if (($uint_dom ne '') &&
1127: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1128: $canhost = 0;
1129: } else {
1130: $canhost = 1;
1131: }
1132: }
1133: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1134: if (($uint_dom ne '') &&
1135: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1136: $canhost = 1;
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: return $canhost;
1144: }
1145:
1.1083 raeburn 1146: sub spare_can_host {
1147: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1148: my $canhost=1;
1149: my @intdoms;
1150: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1151: if (ref($internet_names) eq 'ARRAY') {
1152: @intdoms = @{$internet_names};
1153: }
1154: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1155: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1156: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1157: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1158: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1159: $canhost = &can_host_session($udom,$try_server,$remoterev,
1160: $remotesessions,
1161: $defdomdefaults{'hostedsessions'});
1162: }
1163: return $canhost;
1164: }
1165:
1.1123 raeburn 1166: sub this_host_spares {
1167: my ($dom) = @_;
1.1126 raeburn 1168: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1169: my @hosts = ¤t_machine_ids();
1170: foreach my $lonhost (@hosts) {
1171: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1172: $dom_in_use = $dom;
1173: $lonhost_in_use = $lonhost;
1.1123 raeburn 1174: last;
1175: }
1176: }
1.1126 raeburn 1177: if ($dom_in_use ne '') {
1178: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1179: }
1180: if (ref($result) ne 'HASH') {
1181: $lonhost_in_use = $perlvar{'lonHostID'};
1182: $dom_in_use = &host_domain($lonhost_in_use);
1183: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1184: if (ref($result) ne 'HASH') {
1185: $result = \%spareid;
1186: }
1187: }
1188: return $result;
1189: }
1190:
1191: sub spares_for_offload {
1192: my ($dom_in_use,$lonhost_in_use) = @_;
1193: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1194: if (defined($cached)) {
1195: return $result;
1196: } else {
1.1126 raeburn 1197: my $cachetime = 60*60*24;
1198: my %domconfig =
1199: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1200: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1201: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1202: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1203: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1204: }
1205: }
1206: }
1207: }
1.1126 raeburn 1208: return;
1.1123 raeburn 1209: }
1210:
1.1129 raeburn 1211: sub get_lonbalancer_config {
1212: my ($servers) = @_;
1213: my ($currbalancer,$currtargets);
1214: if (ref($servers) eq 'HASH') {
1215: foreach my $server (keys(%{$servers})) {
1216: my %what = (
1217: spareid => 1,
1218: perlvar => 1,
1219: );
1220: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1221: if ($result eq 'ok') {
1222: if (ref($returnhash) eq 'HASH') {
1223: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1224: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1225: $currbalancer = $server;
1226: $currtargets = {};
1227: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1228: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1229: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1230: }
1231: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1232: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1233: }
1234: }
1235: last;
1236: }
1237: }
1238: }
1239: }
1240: }
1241: }
1242: return ($currbalancer,$currtargets);
1243: }
1244:
1245: sub check_loadbalancing {
1246: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1247: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1248: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1249: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1250: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1251: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1252: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1253: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1254: my $serverhomedom = &host_domain($lonhost);
1255:
1256: my $cachetime = 60*60*24;
1257:
1258: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1259: $dom_in_use = $udom;
1260: $homeintdom = 1;
1261: } else {
1262: $dom_in_use = $serverhomedom;
1263: }
1264: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1265: unless (defined($cached)) {
1266: my %domconfig =
1267: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1268: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1269: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1270: }
1271: }
1272: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1273: ($is_balancer,$currtargets,$currrules) =
1274: &check_balancer_result($result,@hosts);
1.1129 raeburn 1275: if ($is_balancer) {
1276: if (ref($currrules) eq 'HASH') {
1277: if ($homeintdom) {
1278: if ($uname ne '') {
1279: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1280: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1281: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1282: $rule_in_effect = $currrules->{'_LC_author'};
1283: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1284: $rule_in_effect = $currrules->{'_LC_adv'}
1285: }
1286: }
1287: if ($rule_in_effect eq '') {
1288: my %userenv = &userenvironment($udom,$uname,'inststatus');
1289: if ($userenv{'inststatus'} ne '') {
1290: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1291: my ($othertitle,$usertypes,$types) =
1292: &Apache::loncommon::sorted_inst_types($udom);
1293: if (ref($types) eq 'ARRAY') {
1294: foreach my $type (@{$types}) {
1295: if (grep(/^\Q$type\E$/,@statuses)) {
1296: if (exists($currrules->{$type})) {
1297: $rule_in_effect = $currrules->{$type};
1298: }
1299: }
1300: }
1301: }
1302: } else {
1303: if (exists($currrules->{'default'})) {
1304: $rule_in_effect = $currrules->{'default'};
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: } else {
1314: if ($currrules->{'_LC_external'} ne '') {
1315: $rule_in_effect = $currrules->{'_LC_external'};
1316: }
1317: }
1318: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1319: $uname,$udom);
1320: }
1321: }
1322: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1323: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1324: unless (defined($cached)) {
1325: my %domconfig =
1326: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1327: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1328: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1329: }
1330: }
1331: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1332: ($is_balancer,$currtargets,$currrules) =
1333: &check_balancer_result($result,@hosts);
1334: if ($is_balancer) {
1.1129 raeburn 1335: if (ref($currrules) eq 'HASH') {
1336: if ($currrules->{'_LC_internetdom'} ne '') {
1337: $rule_in_effect = $currrules->{'_LC_internetdom'};
1338: }
1339: }
1340: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1341: $uname,$udom);
1342: }
1343: } else {
1344: if ($perlvar{'lonBalancer'} eq 'yes') {
1345: $is_balancer = 1;
1346: $offloadto = &this_host_spares($dom_in_use);
1347: }
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1.1172.2.5 raeburn 1355: if ($is_balancer) {
1356: my $lowest_load = 30000;
1357: if (ref($offloadto) eq 'HASH') {
1358: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1359: foreach my $try_server (@{$offloadto->{'primary'}}) {
1360: ($otherserver,$lowest_load) =
1361: &compare_server_load($try_server,$otherserver,$lowest_load);
1362: }
1.1129 raeburn 1363: }
1.1172.2.5 raeburn 1364: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1365:
1.1172.2.5 raeburn 1366: if (!$found_server) {
1367: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1368: foreach my $try_server (@{$offloadto->{'default'}}) {
1369: ($otherserver,$lowest_load) =
1370: &compare_server_load($try_server,$otherserver,$lowest_load);
1371: }
1372: }
1373: }
1374: } elsif (ref($offloadto) eq 'ARRAY') {
1375: if (@{$offloadto} == 1) {
1376: $otherserver = $offloadto->[0];
1377: } elsif (@{$offloadto} > 1) {
1378: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1.1172.2.5 raeburn 1384: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1385: $is_balancer = 0;
1386: if ($uname ne '' && $udom ne '') {
1387: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1388:
1389: &appenv({'user.loadbalexempt' => $lonhost,
1390: 'user.loadbalcheck.time' => time});
1391: }
1.1129 raeburn 1392: }
1393: }
1394: }
1395: return ($is_balancer,$otherserver);
1396: }
1397:
1.1172.2.12 raeburn 1398: sub check_balancer_result {
1399: my ($result,@hosts) = @_;
1400: my ($is_balancer,$currtargets,$currrules);
1401: if (ref($result) eq 'HASH') {
1402: if ($result->{'lonhost'} ne '') {
1403: my $currbalancer = $result->{'lonhost'};
1404: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1405: $is_balancer = 1;
1406: $currtargets = $result->{'targets'};
1407: $currrules = $result->{'rules'};
1408: }
1409: } else {
1410: foreach my $key (keys(%{$result})) {
1411: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1412: (ref($result->{$key}) eq 'HASH')) {
1413: $is_balancer = 1;
1414: $currrules = $result->{$key}{'rules'};
1415: $currtargets = $result->{$key}{'targets'};
1416: last;
1417: }
1418: }
1419: }
1420: }
1421: return ($is_balancer,$currtargets,$currrules);
1422: }
1423:
1.1129 raeburn 1424: sub get_loadbalancer_targets {
1425: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1426: my $offloadto;
1.1172.2.4 raeburn 1427: if ($rule_in_effect eq 'none') {
1428: return [$perlvar{'lonHostID'}];
1429: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1430: $offloadto = $currtargets;
1431: } else {
1432: if ($rule_in_effect eq 'homeserver') {
1433: my $homeserver = &homeserver($uname,$udom);
1434: if ($homeserver ne 'no_host') {
1435: $offloadto = [$homeserver];
1436: }
1437: } elsif ($rule_in_effect eq 'externalbalancer') {
1438: my %domconfig =
1439: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1440: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1441: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1442: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1443: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1444: }
1445: }
1446: } else {
1.1172.2.7 raeburn 1447: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1448: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1449: if (&hostname($remotebalancer) ne '') {
1450: $offloadto = [$remotebalancer];
1451: }
1452: }
1453: } elsif (&hostname($rule_in_effect) ne '') {
1454: $offloadto = [$rule_in_effect];
1455: }
1456: }
1457: return $offloadto;
1458: }
1459:
1.1127 raeburn 1460: sub internet_dom_servers {
1461: my ($dom) = @_;
1462: my (%uniqservers,%servers);
1463: my $primaryserver = &hostname(&domain($dom,'primary'));
1464: my @machinedoms = &machine_domains($primaryserver);
1465: foreach my $mdom (@machinedoms) {
1466: my %currservers = %servers;
1467: my %server = &get_servers($mdom);
1468: %servers = (%currservers,%server);
1469: }
1470: my %by_hostname;
1471: foreach my $id (keys(%servers)) {
1472: push(@{$by_hostname{$servers{$id}}},$id);
1473: }
1474: foreach my $hostname (sort(keys(%by_hostname))) {
1475: if (@{$by_hostname{$hostname}} > 1) {
1476: my $match = 0;
1477: foreach my $id (@{$by_hostname{$hostname}}) {
1478: if (&host_domain($id) eq $dom) {
1479: $uniqservers{$id} = $hostname;
1480: $match = 1;
1481: }
1482: }
1483: unless ($match) {
1484: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1485: }
1486: } else {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: }
1490: return %uniqservers;
1491: }
1492:
1.1 albertel 1493: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1494:
1.599 albertel 1495: my %homecache;
1.1 albertel 1496: sub homeserver {
1.230 stredwic 1497: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1498: my $index="$uname:$udom";
1.426 albertel 1499:
1.599 albertel 1500: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1501:
1502: my %servers = &get_servers($udom,'library');
1503: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1504: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1505: exists($badServerCache{$tryserver}));
1.841 albertel 1506:
1507: my $answer=reply("home:$udom:$uname",$tryserver);
1508: if ($answer eq 'found') {
1509: delete($badServerCache{$tryserver});
1510: return $homecache{$index}=$tryserver;
1511: } elsif ($answer eq 'no_host') {
1512: $badServerCache{$tryserver}=1;
1513: }
1.1 albertel 1514: }
1515: return 'no_host';
1.70 www 1516: }
1517:
1518: # ------------------------------------- Find the usernames behind a list of IDs
1519:
1520: sub idget {
1521: my ($udom,@ids)=@_;
1522: my %returnhash=();
1523:
1.841 albertel 1524: my %servers = &get_servers($udom,'library');
1525: foreach my $tryserver (keys(%servers)) {
1526: my $idlist=join('&',@ids);
1527: $idlist=~tr/A-Z/a-z/;
1528: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1529: my @answer=();
1530: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1531: @answer=split(/\&/,$reply);
1532: } ;
1533: my $i;
1534: for ($i=0;$i<=$#ids;$i++) {
1535: if ($answer[$i]) {
1536: $returnhash{$ids[$i]}=$answer[$i];
1537: }
1538: }
1539: }
1.70 www 1540: return %returnhash;
1541: }
1542:
1543: # ------------------------------------- Find the IDs behind a list of usernames
1544:
1545: sub idrget {
1546: my ($udom,@unames)=@_;
1547: my %returnhash=();
1.800 albertel 1548: foreach my $uname (@unames) {
1549: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1550: }
1.70 www 1551: return %returnhash;
1552: }
1553:
1554: # ------------------------------- Store away a list of names and associated IDs
1555:
1556: sub idput {
1557: my ($udom,%ids)=@_;
1558: my %servers=();
1.800 albertel 1559: foreach my $uname (keys(%ids)) {
1560: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1561: my $uhom=&homeserver($uname,$udom);
1.70 www 1562: if ($uhom ne 'no_host') {
1.800 albertel 1563: my $id=&escape($ids{$uname});
1.70 www 1564: $id=~tr/A-Z/a-z/;
1.800 albertel 1565: my $esc_unam=&escape($uname);
1.70 www 1566: if ($servers{$uhom}) {
1.800 albertel 1567: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1568: } else {
1.800 albertel 1569: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1570: }
1571: }
1.191 harris41 1572: }
1.800 albertel 1573: foreach my $server (keys(%servers)) {
1574: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1575: }
1.344 www 1576: }
1577:
1.1172.2.30 raeburn 1578: # ---------------------------------------- Delete unwanted IDs from ids.db file
1579:
1580: sub iddel {
1581: my ($udom,$idshashref,$uhome)=@_;
1582: my %result=();
1583: unless (ref($idshashref) eq 'HASH') {
1584: return %result;
1585: }
1586: my %servers=();
1587: while (my ($id,$uname) = each(%{$idshashref})) {
1588: my $uhom;
1589: if ($uhome) {
1590: $uhom = $uhome;
1591: } else {
1592: $uhom=&homeserver($uname,$udom);
1593: }
1594: if ($uhom ne 'no_host') {
1595: if ($servers{$uhom}) {
1596: $servers{$uhom}.='&'.&escape($id);
1597: } else {
1598: $servers{$uhom}=&escape($id);
1599: }
1600: }
1601: }
1602: foreach my $server (keys(%servers)) {
1603: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1604: }
1605: return %result;
1606: }
1607:
1.1023 raeburn 1608: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1609: sub dump_dom {
1.1165 droeschl 1610: my ($namespace, $udom, $regexp) = @_;
1611:
1612: $udom ||= $env{'user.domain'};
1613:
1614: return () unless $udom;
1615:
1616: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1617: }
1618:
1.1023 raeburn 1619: # ------------------------------------------ get items from domain db files
1.806 raeburn 1620:
1621: sub get_dom {
1.860 raeburn 1622: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1623: my $items='';
1624: foreach my $item (@$storearr) {
1625: $items.=&escape($item).'&';
1626: }
1627: $items=~s/\&$//;
1.860 raeburn 1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: if (defined(&domain($udom,'primary'))) {
1631: $uhome=&domain($udom,'primary');
1632: } else {
1.874 albertel 1633: undef($uhome);
1.860 raeburn 1634: }
1635: } else {
1636: if (!$uhome) {
1637: if (defined(&domain($udom,'primary'))) {
1638: $uhome=&domain($udom,'primary');
1639: }
1640: }
1641: }
1642: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1643: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1644: my %returnhash;
1.875 albertel 1645: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1646: return %returnhash;
1647: }
1.806 raeburn 1648: my @pairs=split(/\&/,$rep);
1649: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1650: return @pairs;
1651: }
1652: my $i=0;
1653: foreach my $item (@$storearr) {
1654: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1655: $i++;
1656: }
1657: return %returnhash;
1658: } else {
1.880 banghart 1659: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1660: }
1661: }
1662:
1663: # -------------------------------------------- put items in domain db files
1664:
1665: sub put_dom {
1.860 raeburn 1666: my ($namespace,$storehash,$udom,$uhome)=@_;
1667: if (!$udom) {
1668: $udom=$env{'user.domain'};
1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: } else {
1.874 albertel 1672: undef($uhome);
1.860 raeburn 1673: }
1674: } else {
1675: if (!$uhome) {
1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: }
1679: }
1680: }
1681: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1682: my $items='';
1683: foreach my $item (keys(%$storehash)) {
1684: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1685: }
1686: $items=~s/\&$//;
1687: return &reply("putdom:$udom:$namespace:$items",$uhome);
1688: } else {
1.860 raeburn 1689: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1690: }
1691: }
1692:
1.1023 raeburn 1693: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1694: sub newput_dom {
1.1023 raeburn 1695: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1696: my $result;
1697: if (!$udom) {
1698: $udom=$env{'user.domain'};
1699: }
1.1023 raeburn 1700: if ($udom) {
1701: my $uname = &get_domainconfiguser($udom);
1702: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1703: }
1704: return $result;
1705: }
1706:
1.1023 raeburn 1707: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1708: sub del_dom {
1.1023 raeburn 1709: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1710: if (ref($storearr) eq 'ARRAY') {
1711: if (!$udom) {
1712: $udom=$env{'user.domain'};
1713: }
1.1023 raeburn 1714: if ($udom) {
1715: my $uname = &get_domainconfiguser($udom);
1716: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1717: }
1718: }
1719: }
1720:
1.1023 raeburn 1721: # ----------------------------------construct domainconfig user for a domain
1722: sub get_domainconfiguser {
1723: my ($udom) = @_;
1724: return $udom.'-domainconfig';
1725: }
1726:
1.837 raeburn 1727: sub retrieve_inst_usertypes {
1728: my ($udom) = @_;
1729: my (%returnhash,@order);
1.989 raeburn 1730: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1731: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1732: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1733: %returnhash = %{$domdefs{'inststatustypes'}};
1734: @order = @{$domdefs{'inststatusorder'}};
1735: } else {
1736: if (defined(&domain($udom,'primary'))) {
1737: my $uhome=&domain($udom,'primary');
1738: my $rep=&reply("inst_usertypes:$udom",$uhome);
1739: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1740: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1741: return (\%returnhash,\@order);
1742: }
1743: my ($hashitems,$orderitems) = split(/:/,$rep);
1744: my @pairs=split(/\&/,$hashitems);
1745: foreach my $item (@pairs) {
1746: my ($key,$value)=split(/=/,$item,2);
1747: $key = &unescape($key);
1748: next if ($key =~ /^error: 2 /);
1749: $returnhash{$key}=&thaw_unescape($value);
1750: }
1751: my @esc_order = split(/\&/,$orderitems);
1752: foreach my $item (@esc_order) {
1753: push(@order,&unescape($item));
1754: }
1755: } else {
1756: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1757: }
1758: }
1759: return (\%returnhash,\@order);
1760: }
1761:
1.868 raeburn 1762: sub is_domainimage {
1763: my ($url) = @_;
1764: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1765: if (&domain($1) ne '') {
1766: return '1';
1767: }
1768: }
1769: return;
1770: }
1771:
1.899 raeburn 1772: sub inst_directory_query {
1773: my ($srch) = @_;
1774: my $udom = $srch->{'srchdomain'};
1775: my %results;
1776: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1777: my $outcome;
1.899 raeburn 1778: if ($homeserver ne '') {
1.904 albertel 1779: my $queryid=&reply("querysend:instdirsearch:".
1780: &escape($srch->{'srchby'}).':'.
1781: &escape($srch->{'srchterm'}).':'.
1782: &escape($srch->{'srchtype'}),$homeserver);
1783: my $host=&hostname($homeserver);
1784: if ($queryid !~/^\Q$host\E\_/) {
1785: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1786: return;
1787: }
1788: my $response = &get_query_reply($queryid);
1789: my $maxtries = 5;
1790: my $tries = 1;
1791: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1792: $response = &get_query_reply($queryid);
1793: $tries ++;
1794: }
1795:
1796: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1797: if ($response eq 'unavailable') {
1798: $outcome = $response;
1799: } else {
1800: $outcome = 'ok';
1801: my @matches = split(/\n/,$response);
1802: foreach my $match (@matches) {
1803: my ($key,$value) = split(/=/,$match);
1804: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1805: }
1.899 raeburn 1806: }
1807: }
1808: }
1.909 raeburn 1809: return ($outcome,%results);
1.899 raeburn 1810: }
1811:
1812: sub usersearch {
1813: my ($srch) = @_;
1814: my $dom = $srch->{'srchdomain'};
1815: my %results;
1816: my %libserv = &all_library();
1817: my $query = 'usersearch';
1818: foreach my $tryserver (keys(%libserv)) {
1819: if (&host_domain($tryserver) eq $dom) {
1820: my $host=&hostname($tryserver);
1821: my $queryid=
1.911 raeburn 1822: &reply("querysend:".&escape($query).':'.
1823: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1824: &escape($srch->{'srchtype'}).':'.
1825: &escape($srch->{'srchterm'}),$tryserver);
1826: if ($queryid !~/^\Q$host\E\_/) {
1827: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1828: next;
1.899 raeburn 1829: }
1830: my $reply = &get_query_reply($queryid);
1831: my $maxtries = 1;
1832: my $tries = 1;
1833: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1834: $reply = &get_query_reply($queryid);
1835: $tries ++;
1836: }
1837: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1838: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1839: } else {
1.911 raeburn 1840: my @matches;
1841: if ($reply =~ /\n/) {
1842: @matches = split(/\n/,$reply);
1843: } else {
1844: @matches = split(/\&/,$reply);
1845: }
1.899 raeburn 1846: foreach my $match (@matches) {
1847: my ($uname,$udom,%userhash);
1.911 raeburn 1848: foreach my $entry (split(/:/,$match)) {
1849: my ($key,$value) =
1850: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1851: $userhash{$key} = $value;
1852: if ($key eq 'username') {
1853: $uname = $value;
1854: } elsif ($key eq 'domain') {
1855: $udom = $value;
1.911 raeburn 1856: }
1.899 raeburn 1857: }
1858: $results{$uname.':'.$udom} = \%userhash;
1859: }
1860: }
1861: }
1862: }
1863: return %results;
1864: }
1865:
1.912 raeburn 1866: sub get_instuser {
1867: my ($udom,$uname,$id) = @_;
1868: my $homeserver = &domain($udom,'primary');
1869: my ($outcome,%results);
1870: if ($homeserver ne '') {
1871: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1872: &escape($id).':'.&escape($udom),$homeserver);
1873: my $host=&hostname($homeserver);
1874: if ($queryid !~/^\Q$host\E\_/) {
1875: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1876: return;
1877: }
1878: my $response = &get_query_reply($queryid);
1879: my $maxtries = 5;
1880: my $tries = 1;
1881: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1882: $response = &get_query_reply($queryid);
1883: $tries ++;
1884: }
1885: if (!&error($response) && $response ne 'refused') {
1886: if ($response eq 'unavailable') {
1887: $outcome = $response;
1888: } else {
1889: $outcome = 'ok';
1890: my @matches = split(/\n/,$response);
1891: foreach my $match (@matches) {
1892: my ($key,$value) = split(/=/,$match);
1893: $results{&unescape($key)} = &thaw_unescape($value);
1894: }
1895: }
1896: }
1897: }
1898: my %userinfo;
1899: if (ref($results{$uname}) eq 'HASH') {
1900: %userinfo = %{$results{$uname}};
1901: }
1902: return ($outcome,%userinfo);
1903: }
1904:
1905: sub inst_rulecheck {
1.923 raeburn 1906: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1907: my %returnhash;
1908: if ($udom ne '') {
1909: if (ref($rules) eq 'ARRAY') {
1910: @{$rules} = map {&escape($_);} (@{$rules});
1911: my $rulestr = join(':',@{$rules});
1912: my $homeserver=&domain($udom,'primary');
1913: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1914: my $response;
1915: if ($item eq 'username') {
1916: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1917: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1918: $homeserver));
1.923 raeburn 1919: } elsif ($item eq 'id') {
1920: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1921: ':'.&escape($id).':'.$rulestr,
1922: $homeserver));
1.945 raeburn 1923: } elsif ($item eq 'selfcreate') {
1924: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1925: &escape($udom).':'.&escape($uname).
1926: ':'.$rulestr,$homeserver));
1.923 raeburn 1927: }
1.912 raeburn 1928: if ($response ne 'refused') {
1929: my @pairs=split(/\&/,$response);
1930: foreach my $item (@pairs) {
1931: my ($key,$value)=split(/=/,$item,2);
1932: $key = &unescape($key);
1933: next if ($key =~ /^error: 2 /);
1934: $returnhash{$key}=&thaw_unescape($value);
1935: }
1936: }
1937: }
1938: }
1939: }
1940: return %returnhash;
1941: }
1942:
1943: sub inst_userrules {
1.923 raeburn 1944: my ($udom,$check) = @_;
1.912 raeburn 1945: my (%ruleshash,@ruleorder);
1946: if ($udom ne '') {
1947: my $homeserver=&domain($udom,'primary');
1948: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1949: my $response;
1950: if ($check eq 'id') {
1951: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1952: $homeserver);
1.943 raeburn 1953: } elsif ($check eq 'email') {
1954: $response=&reply('instemailrules:'.&escape($udom),
1955: $homeserver);
1.923 raeburn 1956: } else {
1957: $response=&reply('instuserrules:'.&escape($udom),
1958: $homeserver);
1959: }
1.912 raeburn 1960: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1961: ($response ne 'unknown_cmd') &&
1.912 raeburn 1962: ($response ne 'no_such_host')) {
1963: my ($hashitems,$orderitems) = split(/:/,$response);
1964: my @pairs=split(/\&/,$hashitems);
1965: foreach my $item (@pairs) {
1966: my ($key,$value)=split(/=/,$item,2);
1967: $key = &unescape($key);
1968: next if ($key =~ /^error: 2 /);
1969: $ruleshash{$key}=&thaw_unescape($value);
1970: }
1971: my @esc_order = split(/\&/,$orderitems);
1972: foreach my $item (@esc_order) {
1973: push(@ruleorder,&unescape($item));
1974: }
1975: }
1976: }
1977: }
1978: return (\%ruleshash,\@ruleorder);
1979: }
1980:
1.976 raeburn 1981: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1982:
1983: sub get_domain_defaults {
1.1172.2.35 raeburn 1984: my ($domain,$ignore_cache) = @_;
1985: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1986: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1987: unless ($ignore_cache) {
1988: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1989: if (defined($cached)) {
1990: if (ref($result) eq 'HASH') {
1991: return %{$result};
1992: }
1.943 raeburn 1993: }
1994: }
1995: my %domdefaults;
1996: my %domconfig =
1.989 raeburn 1997: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1998: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1999: 'coursedefaults','usersessions',
2000: 'requestauthor'],$domain);
1.943 raeburn 2001: if (ref($domconfig{'defaults'}) eq 'HASH') {
2002: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2003: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2004: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2005: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2006: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2007: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2008: } else {
2009: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2010: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2011: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2012: }
1.976 raeburn 2013: if (ref($domconfig{'quotas'}) eq 'HASH') {
2014: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2015: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2016: } else {
2017: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2018: }
1.1172.2.6 raeburn 2019: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2020: foreach my $item (@usertools) {
2021: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2022: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2023: }
2024: }
1.1172.2.29 raeburn 2025: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2026: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2027: }
1.976 raeburn 2028: }
1.985 raeburn 2029: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37! raeburn 2030: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2031: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2032: }
2033: }
1.1172.2.9 raeburn 2034: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2035: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2036: }
1.989 raeburn 2037: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2038: foreach my $item ('inststatustypes','inststatusorder') {
2039: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2040: }
2041: }
1.1047 raeburn 2042: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19 raeburn 2043: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2044: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2045: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1172.2.37! raeburn 2046: $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
1.1047 raeburn 2047: }
1.1172.2.30 raeburn 2048: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2049: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2050: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2051: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
1.1172.2.37! raeburn 2052: $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
1.1172.2.30 raeburn 2053: }
1.1047 raeburn 2054: }
1.1073 raeburn 2055: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2056: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2057: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2058: }
2059: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2060: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2061: }
2062: }
1.1172.2.23 raeburn 2063: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2064: return %domdefaults;
2065: }
2066:
1.344 www 2067: # --------------------------------------------------- Assign a key to a student
2068:
2069: sub assign_access_key {
1.364 www 2070: #
2071: # a valid key looks like uname:udom#comments
2072: # comments are being appended
2073: #
1.498 www 2074: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2075: $kdom=
1.620 albertel 2076: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2077: $knum=
1.620 albertel 2078: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2079: $cdom=
1.620 albertel 2080: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2081: $cnum=
1.620 albertel 2082: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2083: $udom=$env{'user.name'} unless (defined($udom));
2084: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2085: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2086: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2087: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2088: # assigned to this person
2089: # - this should not happen,
1.345 www 2090: # unless something went wrong
2091: # the first time around
2092: # ready to assign
1.364 www 2093: $logentry=$1.'; '.$logentry;
1.496 www 2094: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2095: $kdom,$knum) eq 'ok') {
1.345 www 2096: # key now belongs to user
1.346 www 2097: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2098: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2099: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2100: return 'ok';
2101: } else {
2102: return
2103: 'error: Count not permanently assign key, will need to be re-entered later.';
2104: }
2105: } else {
2106: return 'error: Could not assign key, try again later.';
2107: }
1.364 www 2108: } elsif (!$existing{$ckey}) {
1.345 www 2109: # the key does not exist
2110: return 'error: The key does not exist';
2111: } else {
2112: # the key is somebody else's
2113: return 'error: The key is already in use';
2114: }
1.344 www 2115: }
2116:
1.364 www 2117: # ------------------------------------------ put an additional comment on a key
2118:
2119: sub comment_access_key {
2120: #
2121: # a valid key looks like uname:udom#comments
2122: # comments are being appended
2123: #
2124: my ($ckey,$cdom,$cnum,$logentry)=@_;
2125: $cdom=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2127: $cnum=
1.620 albertel 2128: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2129: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2130: if ($existing{$ckey}) {
2131: $existing{$ckey}.='; '.$logentry;
2132: # ready to assign
1.367 www 2133: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2134: $cdom,$cnum) eq 'ok') {
2135: return 'ok';
2136: } else {
2137: return 'error: Count not store comment.';
2138: }
2139: } else {
2140: # the key does not exist
2141: return 'error: The key does not exist';
2142: }
2143: }
2144:
1.344 www 2145: # ------------------------------------------------------ Generate a set of keys
2146:
2147: sub generate_access_keys {
1.364 www 2148: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2149: $cdom=
1.620 albertel 2150: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2151: $cnum=
1.620 albertel 2152: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2153: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2154: unless (($cdom) && ($cnum)) { return 0; }
2155: if ($number>10000) { return 0; }
2156: sleep(2); # make sure don't get same seed twice
2157: srand(time()^($$+($$<<15))); # from "Programming Perl"
2158: my $total=0;
2159: for (my $i=1;$i<=$number;$i++) {
2160: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2161: sprintf("%lx",int(100000*rand)).'-'.
2162: sprintf("%lx",int(100000*rand));
2163: $newkey=~s/1/g/g; # folks mix up 1 and l
2164: $newkey=~s/0/h/g; # and also 0 and O
2165: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2166: if ($existing{$newkey}) {
2167: $i--;
2168: } else {
1.364 www 2169: if (&put('accesskeys',
2170: { $newkey => '# generated '.localtime().
1.620 albertel 2171: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2172: '; '.$logentry },
2173: $cdom,$cnum) eq 'ok') {
1.344 www 2174: $total++;
2175: }
2176: }
2177: }
1.620 albertel 2178: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2179: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2180: return $total;
2181: }
2182:
2183: # ------------------------------------------------------- Validate an accesskey
2184:
2185: sub validate_access_key {
2186: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2187: $cdom=
1.620 albertel 2188: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2189: $cnum=
1.620 albertel 2190: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2191: $udom=$env{'user.domain'} unless (defined($udom));
2192: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2193: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2194: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2195: }
2196:
2197: # ------------------------------------- Find the section of student in a course
1.652 albertel 2198: sub devalidate_getsection_cache {
2199: my ($udom,$unam,$courseid)=@_;
2200: my $hashid="$udom:$unam:$courseid";
2201: &devalidate_cache_new('getsection',$hashid);
2202: }
1.298 matthew 2203:
1.815 albertel 2204: sub courseid_to_courseurl {
2205: my ($courseid) = @_;
2206: #already url style courseid
2207: return $courseid if ($courseid =~ m{^/});
2208:
2209: if (exists($env{'course.'.$courseid.'.num'})) {
2210: my $cnum = $env{'course.'.$courseid.'.num'};
2211: my $cdom = $env{'course.'.$courseid.'.domain'};
2212: return "/$cdom/$cnum";
2213: }
2214:
2215: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2216: if (exists($courseinfo{'num'})) {
2217: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2218: }
2219:
2220: return undef;
2221: }
2222:
1.298 matthew 2223: sub getsection {
2224: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2225: my $cachetime=1800;
1.551 albertel 2226:
2227: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2228: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2229: if (defined($cached)) { return $result; }
2230:
1.298 matthew 2231: my %Pending;
2232: my %Expired;
2233: #
2234: # Each role can either have not started yet (pending), be active,
2235: # or have expired.
2236: #
2237: # If there is an active role, we are done.
2238: #
2239: # If there is more than one role which has not started yet,
2240: # choose the one which will start sooner
2241: # If there is one role which has not started yet, return it.
2242: #
2243: # If there is more than one expired role, choose the one which ended last.
2244: # If there is a role which has expired, return it.
2245: #
1.815 albertel 2246: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2247: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2248: foreach my $key (keys(%roleshash)) {
1.479 albertel 2249: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2250: my $section=$1;
2251: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2252: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2253: my $now=time;
1.548 albertel 2254: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2255: $Expired{$end}=$section;
2256: next;
2257: }
1.548 albertel 2258: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2259: $Pending{$start}=$section;
2260: next;
2261: }
1.599 albertel 2262: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2263: }
2264: #
2265: # Presumedly there will be few matching roles from the above
2266: # loop and the sorting time will be negligible.
2267: if (scalar(keys(%Pending))) {
2268: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2269: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2270: }
2271: if (scalar(keys(%Expired))) {
2272: my @sorted = sort {$a <=> $b} keys(%Expired);
2273: my $time = pop(@sorted);
1.599 albertel 2274: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2275: }
1.599 albertel 2276: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2277: }
1.70 www 2278:
1.599 albertel 2279: sub save_cache {
2280: &purge_remembered();
1.722 albertel 2281: #&Apache::loncommon::validate_page();
1.620 albertel 2282: undef(%env);
1.780 albertel 2283: undef($env_loaded);
1.599 albertel 2284: }
1.452 albertel 2285:
1.599 albertel 2286: my $to_remember=-1;
2287: my %remembered;
2288: my %accessed;
2289: my $kicks=0;
2290: my $hits=0;
1.849 albertel 2291: sub make_key {
2292: my ($name,$id) = @_;
1.872 albertel 2293: if (length($id) > 65
2294: && length(&escape($id)) > 200) {
2295: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2296: }
1.849 albertel 2297: return &escape($name.':'.$id);
2298: }
2299:
1.599 albertel 2300: sub devalidate_cache_new {
2301: my ($name,$id,$debug) = @_;
2302: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2303: $id=&make_key($name,$id);
1.599 albertel 2304: $memcache->delete($id);
2305: delete($remembered{$id});
2306: delete($accessed{$id});
2307: }
2308:
2309: sub is_cached_new {
2310: my ($name,$id,$debug) = @_;
1.849 albertel 2311: $id=&make_key($name,$id);
1.599 albertel 2312: if (exists($remembered{$id})) {
1.1133 foxr 2313: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2314: $accessed{$id}=[&gettimeofday()];
2315: $hits++;
2316: return ($remembered{$id},1);
2317: }
2318: my $value = $memcache->get($id);
2319: if (!(defined($value))) {
2320: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2321: return (undef,undef);
1.416 albertel 2322: }
1.599 albertel 2323: if ($value eq '__undef__') {
2324: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2325: $value=undef;
2326: }
2327: &make_room($id,$value,$debug);
2328: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2329: return ($value,1);
2330: }
2331:
2332: sub do_cache_new {
2333: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2334: $id=&make_key($name,$id);
1.599 albertel 2335: my $setvalue=$value;
2336: if (!defined($setvalue)) {
2337: $setvalue='__undef__';
2338: }
1.623 albertel 2339: if (!defined($time) ) {
2340: $time=600;
2341: }
1.599 albertel 2342: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2343: my $result = $memcache->set($id,$setvalue,$time);
2344: if (! $result) {
1.872 albertel 2345: &logthis("caching of id -> $id failed");
1.910 albertel 2346: $memcache->disconnect_all();
1.872 albertel 2347: }
1.600 albertel 2348: # need to make a copy of $value
1.919 albertel 2349: &make_room($id,$value,$debug);
1.599 albertel 2350: return $value;
2351: }
2352:
2353: sub make_room {
2354: my ($id,$value,$debug)=@_;
1.919 albertel 2355:
2356: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2357: : $value;
1.599 albertel 2358: if ($to_remember<0) { return; }
2359: $accessed{$id}=[&gettimeofday()];
2360: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2361: my $to_kick;
2362: my $max_time=0;
2363: foreach my $other (keys(%accessed)) {
2364: if (&tv_interval($accessed{$other}) > $max_time) {
2365: $to_kick=$other;
2366: $max_time=&tv_interval($accessed{$other});
2367: }
2368: }
2369: delete($remembered{$to_kick});
2370: delete($accessed{$to_kick});
2371: $kicks++;
2372: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2373: return;
2374: }
2375:
1.599 albertel 2376: sub purge_remembered {
1.604 albertel 2377: #&logthis("Tossing ".scalar(keys(%remembered)));
2378: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2379: undef(%remembered);
2380: undef(%accessed);
1.428 albertel 2381: }
1.70 www 2382: # ------------------------------------- Read an entry from a user's environment
2383:
2384: sub userenvironment {
2385: my ($udom,$unam,@what)=@_;
1.976 raeburn 2386: my $items;
2387: foreach my $item (@what) {
2388: $items.=&escape($item).'&';
2389: }
2390: $items=~s/\&$//;
1.70 www 2391: my %returnhash=();
1.1009 raeburn 2392: my $uhome = &homeserver($unam,$udom);
2393: unless ($uhome eq 'no_host') {
2394: my @answer=split(/\&/,
2395: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2396: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2397: return %returnhash;
2398: }
1.1009 raeburn 2399: my $i;
2400: for ($i=0;$i<=$#what;$i++) {
2401: $returnhash{$what[$i]}=&unescape($answer[$i]);
2402: }
1.70 www 2403: }
2404: return %returnhash;
1.1 albertel 2405: }
2406:
1.617 albertel 2407: # ---------------------------------------------------------- Get a studentphoto
2408: sub studentphoto {
2409: my ($udom,$unam,$ext) = @_;
2410: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2411: if (defined($env{'request.course.id'})) {
1.708 raeburn 2412: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2413: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2414: return(&retrievestudentphoto($udom,$unam,$ext));
2415: } else {
2416: my ($result,$perm_reqd)=
1.707 albertel 2417: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2418: if ($result eq 'ok') {
2419: if (!($perm_reqd eq 'yes')) {
2420: return(&retrievestudentphoto($udom,$unam,$ext));
2421: }
2422: }
2423: }
2424: }
2425: } else {
2426: my ($result,$perm_reqd) =
1.707 albertel 2427: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2428: if ($result eq 'ok') {
2429: if (!($perm_reqd eq 'yes')) {
2430: return(&retrievestudentphoto($udom,$unam,$ext));
2431: }
2432: }
2433: }
2434: return '/adm/lonKaputt/lonlogo_broken.gif';
2435: }
2436:
2437: sub retrievestudentphoto {
2438: my ($udom,$unam,$ext,$type) = @_;
2439: my $home=&Apache::lonnet::homeserver($unam,$udom);
2440: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2441: if ($ret eq 'ok') {
2442: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2443: if ($type eq 'thumbnail') {
2444: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2445: }
2446: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2447: return $tokenurl;
2448: } else {
2449: if ($type eq 'thumbnail') {
2450: return '/adm/lonKaputt/genericstudent_tn.gif';
2451: } else {
2452: return '/adm/lonKaputt/lonlogo_broken.gif';
2453: }
1.617 albertel 2454: }
2455: }
2456:
1.263 www 2457: # -------------------------------------------------------------------- New chat
2458:
2459: sub chatsend {
1.724 raeburn 2460: my ($newentry,$anon,$group)=@_;
1.620 albertel 2461: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2462: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2463: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2464: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2465: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2466: &escape($newentry)).':'.$group,$chome);
1.292 www 2467: }
2468:
2469: # ------------------------------------------ Find current version of a resource
2470:
2471: sub getversion {
2472: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2473: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2474: return ¤tversion(&filelocation('',$fname));
2475: }
2476:
2477: sub currentversion {
2478: my $fname=shift;
2479: my $author=$fname;
2480: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2481: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2482: my $home=&homeserver($uname,$udom);
1.292 www 2483: if ($home eq 'no_host') {
2484: return -1;
2485: }
1.1112 www 2486: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2487: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2488: return -1;
2489: }
1.1112 www 2490: return $answer;
1.263 www 2491: }
2492:
1.1111 www 2493: #
2494: # Return special version number of resource if set by override, empty otherwise
2495: #
2496: sub usedversion {
2497: my $fname=shift;
2498: unless ($fname) { $fname=$env{'request.uri'}; }
2499: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2500: if ($urlversion) { return $urlversion; }
2501: return '';
2502: }
2503:
1.1 albertel 2504: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2505:
1.1 albertel 2506: sub subscribe {
2507: my $fname=shift;
1.761 raeburn 2508: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2509: $fname=~s/[\n\r]//g;
1.1 albertel 2510: my $author=$fname;
2511: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2512: my ($udom,$uname)=split(/\//,$author);
2513: my $home=homeserver($uname,$udom);
1.335 albertel 2514: if ($home eq 'no_host') {
2515: return 'not_found';
1.1 albertel 2516: }
2517: my $answer=reply("sub:$fname",$home);
1.64 www 2518: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2519: $answer.=' by '.$home;
2520: }
1.1 albertel 2521: return $answer;
2522: }
2523:
1.8 www 2524: # -------------------------------------------------------------- Replicate file
2525:
2526: sub repcopy {
2527: my $filename=shift;
1.23 www 2528: $filename=~s/\/+/\//g;
1.1142 raeburn 2529: my $londocroot = $perlvar{'lonDocRoot'};
2530: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2531: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2532: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2533: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2534: return &repcopy_userfile($filename);
2535: }
1.532 albertel 2536: $filename=~s/[\n\r]//g;
1.8 www 2537: my $transname="$filename.in.transfer";
1.828 www 2538: # FIXME: this should flock
1.607 raeburn 2539: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2540: my $remoteurl=subscribe($filename);
1.64 www 2541: if ($remoteurl =~ /^con_lost by/) {
2542: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2543: return 'unavailable';
1.8 www 2544: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2545: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2546: return 'not_found';
1.64 www 2547: } elsif ($remoteurl =~ /^rejected by/) {
2548: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2549: return 'forbidden';
1.20 www 2550: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2551: return 'ok';
1.8 www 2552: } else {
1.290 www 2553: my $author=$filename;
2554: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2555: my ($udom,$uname)=split(/\//,$author);
2556: my $home=homeserver($uname,$udom);
2557: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2558: my @parts=split(/\//,$filename);
2559: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2560: if ($path ne "$londocroot/res") {
1.8 www 2561: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2562: return 'bad_request';
1.8 www 2563: }
2564: my $count;
2565: for ($count=5;$count<$#parts;$count++) {
2566: $path.="/$parts[$count]";
2567: if ((-e $path)!=1) {
2568: mkdir($path,0777);
2569: }
2570: }
2571: my $ua=new LWP::UserAgent;
2572: my $request=new HTTP::Request('GET',"$remoteurl");
2573: my $response=$ua->request($request,$transname);
2574: if ($response->is_error()) {
2575: unlink($transname);
2576: my $message=$response->status_line;
1.672 albertel 2577: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2578: ." LWP get: $message: $filename</font>");
1.607 raeburn 2579: return 'unavailable';
1.8 www 2580: } else {
1.16 www 2581: if ($remoteurl!~/\.meta$/) {
2582: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2583: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2584: if ($mresponse->is_error()) {
2585: unlink($filename.'.meta');
2586: &logthis(
1.672 albertel 2587: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2588: }
2589: }
1.8 www 2590: rename($transname,$filename);
1.607 raeburn 2591: return 'ok';
1.8 www 2592: }
1.290 www 2593: }
1.8 www 2594: }
1.330 www 2595: }
2596:
2597: # ------------------------------------------------ Get server side include body
2598: sub ssi_body {
1.381 albertel 2599: my ($filelink,%form)=@_;
1.606 matthew 2600: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2601: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2602: }
1.953 www 2603: my $output='';
2604: my $response;
1.980 raeburn 2605: if ($filelink=~/^https?\:/) {
1.954 raeburn 2606: ($output,$response)=&externalssi($filelink);
1.953 www 2607: } else {
1.1004 droeschl 2608: $filelink .= $filelink=~/\?/ ? '&' : '?';
2609: $filelink .= 'inhibitmenu=yes';
1.953 www 2610: ($output,$response)=&ssi($filelink,%form);
2611: }
1.778 albertel 2612: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2613: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2614: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2615: if (wantarray) {
2616: return ($output, $response);
2617: } else {
2618: return $output;
2619: }
1.8 www 2620: }
2621:
1.15 www 2622: # --------------------------------------------------------- Server Side Include
2623:
1.782 albertel 2624: sub absolute_url {
2625: my ($host_name) = @_;
2626: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2627: if ($host_name eq '') {
2628: $host_name = $ENV{'SERVER_NAME'};
2629: }
2630: return $protocol.$host_name;
2631: }
2632:
1.942 foxr 2633: #
2634: # Server side include.
2635: # Parameters:
2636: # fn Possibly encrypted resource name/id.
2637: # form Hash that describes how the rendering should be done
2638: # and other things.
1.944 foxr 2639: # Returns:
1.950 raeburn 2640: # Scalar context: The content of the response.
2641: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2642: #
1.15 www 2643: sub ssi {
2644:
1.944 foxr 2645: my ($fn,%form)=@_;
1.15 www 2646: my $ua=new LWP::UserAgent;
1.23 www 2647: my $request;
1.711 albertel 2648:
2649: $form{'no_update_last_known'}=1;
1.895 albertel 2650: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2651: if (%form) {
1.782 albertel 2652: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2653: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2654: } else {
1.782 albertel 2655: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2656: }
2657:
1.15 www 2658: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2659: my $response= $ua->request($request);
1.944 foxr 2660: if (wantarray) {
1.1172.2.3 raeburn 2661: return ($response->content, $response);
1.944 foxr 2662: } else {
1.1172.2.3 raeburn 2663: return $response->content;
1.942 foxr 2664: }
1.324 www 2665: }
2666:
2667: sub externalssi {
2668: my ($url)=@_;
2669: my $ua=new LWP::UserAgent;
2670: my $request=new HTTP::Request('GET',$url);
2671: my $response=$ua->request($request);
1.954 raeburn 2672: if (wantarray) {
2673: return ($response->content, $response);
2674: } else {
2675: return $response->content;
2676: }
1.15 www 2677: }
1.254 www 2678:
1.492 albertel 2679: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2680:
2681: sub allowuploaded {
2682: my ($srcurl,$url)=@_;
2683: $url=&clutter(&declutter($url));
2684: my $dir=$url;
2685: $dir=~s/\/[^\/]+$//;
2686: my %httpref=();
2687: my $httpurl=&hreflocation('',$url);
2688: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2689: &Apache::lonnet::appenv(\%httpref);
1.254 www 2690: }
1.477 raeburn 2691:
1.1172.2.13 raeburn 2692: #
2693: # Determine if the current user should be able to edit a particular resource,
2694: # when viewing in course context.
2695: # (a) When viewing resource used to determine if "Edit" item is included in
2696: # Functions.
2697: # (b) When displaying folder contents in course editor, used to determine if
2698: # "Edit" link will be displayed alongside resource.
2699: #
2700: # input: six args -- filename (decluttered), course number, course domain,
2701: # url, symb (if registered) and group (if this is a group
2702: # item -- e.g., bulletin board, group page etc.).
2703: # output: array of five scalars --
2704: # $cfile -- url for file editing if editable on current server
2705: # $home -- homeserver of resource (i.e., for author if published,
2706: # or course if uploaded.).
2707: # $switchserver -- 1 if server switch will be needed.
2708: # $forceedit -- 1 if icon/link should be to go to edit mode
2709: # $forceview -- 1 if icon/link should be to go to view mode
2710: #
2711:
2712: sub can_edit_resource {
2713: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2714: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2715: #
2716: # For aboutme pages user can only edit his/her own.
2717: #
2718: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2719: my ($sdom,$sname) = ($1,$2);
2720: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2721: $home = $env{'user.home'};
2722: $cfile = $resurl;
2723: if ($env{'form.forceedit'}) {
2724: $forceview = 1;
2725: } else {
2726: $forceedit = 1;
2727: }
2728: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2729: } else {
2730: return;
2731: }
2732: }
2733:
2734: if ($env{'request.course.id'}) {
2735: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2736: if ($group ne '') {
2737: # if this is a group homepage or group bulletin board, check group privs
2738: my $allowed = 0;
2739: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2740: if ((&allowed('mdg',$env{'request.course.id'}.
2741: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2742: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2743: $allowed = 1;
2744: }
2745: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2746: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2747: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2748: $allowed = 1;
2749: }
2750: }
2751: if ($allowed) {
2752: $home=&homeserver($cnum,$cdom);
2753: if ($env{'form.forceedit'}) {
2754: $forceview = 1;
2755: } else {
2756: $forceedit = 1;
2757: }
2758: $cfile = $resurl;
2759: } else {
2760: return;
2761: }
2762: } else {
1.1172.2.15 raeburn 2763: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2764: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2765: return;
2766: }
2767: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2768: #
2769: # No edit allowed where CC has switched to student role.
2770: #
2771: return;
2772: }
2773: }
2774: }
2775:
2776: if ($file ne '') {
2777: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2778: if (&is_course_upload($file,$cnum,$cdom)) {
2779: $uploaded = 1;
2780: $incourse = 1;
2781: if ($file =~/\.(htm|html|css|js|txt)$/) {
2782: $cfile = &hreflocation('',$file);
2783: if ($env{'form.forceedit'}) {
2784: $forceview = 1;
2785: } else {
2786: $forceedit = 1;
2787: }
2788: }
2789: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2790: $incourse = 1;
2791: if ($env{'form.forceedit'}) {
2792: $forceview = 1;
2793: } else {
2794: $forceedit = 1;
2795: }
2796: $cfile = $resurl;
2797: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2798: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2799: $incourse = 1;
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2807: $incourse = 1;
2808: $cfile = $resurl.'/smpedit';
2809: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2810: $incourse = 1;
2811: if ($env{'form.forceedit'}) {
2812: $forceview = 1;
2813: } else {
2814: $forceedit = 1;
2815: }
2816: $cfile = $resurl;
1.1172.2.15 raeburn 2817: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2818: $incourse = 1;
2819: if ($env{'form.forceedit'}) {
2820: $forceview = 1;
2821: } else {
2822: $forceedit = 1;
2823: }
2824: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2825: }
2826: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2827: my $template = '/res/lib/templates/simpleproblem.problem';
2828: if (&is_on_map($template)) {
2829: $incourse = 1;
2830: $forceview = 1;
2831: $cfile = $template;
2832: }
2833: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2834: $incourse = 1;
2835: if ($env{'form.forceedit'}) {
2836: $forceview = 1;
2837: } else {
2838: $forceedit = 1;
2839: }
2840: $cfile = $resurl;
2841: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2842: $incourse = 1;
2843: $forceview = 1;
2844: if ($symb) {
2845: my ($map,$id,$res)=&decode_symb($symb);
2846: $env{'request.symb'} = $symb;
2847: $cfile = &clutter($res);
2848: } else {
2849: $cfile = $env{'form.suppurl'};
2850: $cfile =~ s{^http://}{};
2851: $cfile = '/adm/wrapper/ext/'.$cfile;
2852: }
1.1172.2.31 raeburn 2853: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2854: if ($env{'form.forceedit'}) {
2855: $forceview = 1;
2856: } else {
2857: $forceedit = 1;
2858: }
2859: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2860: }
2861: }
2862: if ($uploaded || $incourse) {
2863: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2864: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2865: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2866: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2867: # Check that the user has permission to edit this resource
2868: my $setpriv = 1;
2869: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2870: if (defined($cfudom)) {
2871: $home=&homeserver($cfuname,$cfudom);
2872: $cfile=$file;
2873: }
2874: }
2875: if (($cfile ne '') && (!$incourse || $uploaded) &&
2876: (($home ne '') && ($home ne 'no_host'))) {
2877: my @ids=¤t_machine_ids();
2878: unless (grep(/^\Q$home\E$/,@ids)) {
2879: $switchserver=1;
2880: }
2881: }
2882: }
2883: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2884: }
2885:
2886: sub is_course_upload {
2887: my ($file,$cnum,$cdom) = @_;
2888: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2889: $uploadpath =~ s{^\/}{};
2890: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2891: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2892: return 1;
2893: }
2894: return;
2895: }
2896:
2897: sub in_course {
2898: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2899: if ($hideprivileged) {
2900: my $skipuser;
1.1172.2.23 raeburn 2901: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2902: my @possdoms = ($cdom);
2903: if ($coursehash{'checkforpriv'}) {
2904: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2905: }
2906: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2907: $skipuser = 1;
2908: if ($coursehash{'nothideprivileged'}) {
2909: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2910: my $user;
2911: if ($item =~ /:/) {
2912: $user = $item;
2913: } else {
2914: $user = join(':',split(/[\@]/,$item));
2915: }
2916: if ($user eq $uname.':'.$udom) {
2917: undef($skipuser);
2918: last;
2919: }
2920: }
2921: }
2922: if ($skipuser) {
2923: return 0;
2924: }
2925: }
2926: }
2927: $type ||= 'any';
2928: if (!defined($cdom) || !defined($cnum)) {
2929: my $cid = $env{'request.course.id'};
2930: $cdom = $env{'course.'.$cid.'.domain'};
2931: $cnum = $env{'course.'.$cid.'.num'};
2932: }
2933: my $typesref;
2934: if (($type eq 'any') || ($type eq 'all')) {
2935: $typesref = ['active','previous','future'];
2936: } elsif ($type eq 'previous' || $type eq 'future') {
2937: $typesref = [$type];
2938: }
2939: my %roles = &get_my_roles($uname,$udom,'userroles',
2940: $typesref,undef,[$cdom]);
2941: my ($tmp) = keys(%roles);
2942: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2943: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2944: if (@course_roles > 0) {
2945: return 1;
2946: }
2947: return 0;
2948: }
2949:
1.478 albertel 2950: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2951: # input: action, courseID, current domain, intended
1.637 raeburn 2952: # path to file, source of file, instruction to parse file for objects,
2953: # ref to hash for embedded objects,
2954: # ref to hash for codebase of java objects.
1.1095 raeburn 2955: # reference to scalar to accommodate mime type determined
2956: # from File::MMagic if $parser = parse.
1.637 raeburn 2957: #
1.485 raeburn 2958: # output: url to file (if action was uploaddoc),
2959: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2960: #
1.478 albertel 2961: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2962: # course.
1.477 raeburn 2963: #
1.478 albertel 2964: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2965: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2966: # course's home server.
1.477 raeburn 2967: #
1.478 albertel 2968: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2969: # be copied from $source (current location) to
2970: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2971: # and will then be copied to
2972: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2973: # course's home server.
1.485 raeburn 2974: #
1.481 raeburn 2975: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2976: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2977: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2978: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2979: # in course's home server.
1.637 raeburn 2980: #
1.477 raeburn 2981:
2982: sub process_coursefile {
1.1095 raeburn 2983: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2984: $mimetype)=@_;
1.477 raeburn 2985: my $fetchresult;
1.638 albertel 2986: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2987: if ($action eq 'propagate') {
1.638 albertel 2988: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2989: $home);
1.481 raeburn 2990: } else {
1.477 raeburn 2991: my $fpath = '';
2992: my $fname = $file;
1.478 albertel 2993: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2994: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2995: my $filepath = &build_filepath($fpath);
1.481 raeburn 2996: if ($action eq 'copy') {
2997: if ($source eq '') {
2998: $fetchresult = 'no source file';
2999: return $fetchresult;
3000: } else {
3001: my $destination = $filepath.'/'.$fname;
3002: rename($source,$destination);
3003: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3004: $home);
1.481 raeburn 3005: }
3006: } elsif ($action eq 'uploaddoc') {
3007: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3008: print $fh $env{'form.'.$source};
1.481 raeburn 3009: close($fh);
1.637 raeburn 3010: if ($parser eq 'parse') {
1.1024 raeburn 3011: my $mm = new File::MMagic;
1.1095 raeburn 3012: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3013: if ($type eq 'text/html') {
1.1024 raeburn 3014: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3015: unless ($parse_result eq 'ok') {
3016: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3017: }
1.637 raeburn 3018: }
1.1095 raeburn 3019: if (ref($mimetype)) {
3020: $$mimetype = $type;
3021: }
1.637 raeburn 3022: }
1.477 raeburn 3023: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3024: $home);
1.481 raeburn 3025: if ($fetchresult eq 'ok') {
3026: return '/uploaded/'.$fpath.'/'.$fname;
3027: } else {
3028: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3029: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3030: return '/adm/notfound.html';
3031: }
1.477 raeburn 3032: }
3033: }
1.485 raeburn 3034: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3035: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3036: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3037: }
3038: return $fetchresult;
3039: }
3040:
1.637 raeburn 3041: sub build_filepath {
3042: my ($fpath) = @_;
3043: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3044: unless ($fpath eq '') {
3045: my @parts=split('/',$fpath);
3046: foreach my $part (@parts) {
3047: $filepath.= '/'.$part;
3048: if ((-e $filepath)!=1) {
3049: mkdir($filepath,0777);
3050: }
3051: }
3052: }
3053: return $filepath;
3054: }
3055:
3056: sub store_edited_file {
1.638 albertel 3057: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3058: my $file = $primary_url;
3059: $file =~ s#^/uploaded/$docudom/$docuname/##;
3060: my $fpath = '';
3061: my $fname = $file;
3062: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3063: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3064: my $filepath = &build_filepath($fpath);
3065: open(my $fh,'>'.$filepath.'/'.$fname);
3066: print $fh $content;
3067: close($fh);
1.638 albertel 3068: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3069: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3070: $home);
1.637 raeburn 3071: if ($$fetchresult eq 'ok') {
3072: return '/uploaded/'.$fpath.'/'.$fname;
3073: } else {
1.638 albertel 3074: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3075: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3076: return '/adm/notfound.html';
3077: }
3078: }
3079:
1.531 albertel 3080: sub clean_filename {
1.831 albertel 3081: my ($fname,$args)=@_;
1.315 www 3082: # Replace Windows backslashes by forward slashes
1.257 www 3083: $fname=~s/\\/\//g;
1.831 albertel 3084: if (!$args->{'keep_path'}) {
3085: # Get rid of everything but the actual filename
3086: $fname=~s/^.*\/([^\/]+)$/$1/;
3087: }
1.315 www 3088: # Replace spaces by underscores
3089: $fname=~s/\s+/\_/g;
3090: # Replace all other weird characters by nothing
1.831 albertel 3091: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3092: # Replace all .\d. sequences with _\d. so they no longer look like version
3093: # numbers
3094: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3095: return $fname;
3096: }
1.1051 raeburn 3097: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3098: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3099: # image with the same aspect ratio as the original, but with dimensions which do
3100: # not exceed $resizewidth and $resizeheight.
3101:
1.984 neumanie 3102: sub resizeImage {
1.1051 raeburn 3103: my ($img_path,$resizewidth,$resizeheight) = @_;
3104: my $ima = Image::Magick->new;
3105: my $resized;
3106: if (-e $img_path) {
3107: $ima->Read($img_path);
3108: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3109: my $width = $ima->Get('width');
3110: my $height = $ima->Get('height');
3111: if ($width > $resizewidth) {
3112: my $factor = $width/$resizewidth;
3113: my $newheight = $height/$factor;
3114: $ima->Scale(width=>$resizewidth,height=>$newheight);
3115: $resized = 1;
3116: }
3117: }
3118: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3119: my $width = $ima->Get('width');
3120: my $height = $ima->Get('height');
3121: if ($height > $resizeheight) {
3122: my $factor = $height/$resizeheight;
3123: my $newwidth = $width/$factor;
3124: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3125: $resized = 1;
3126: }
3127: }
3128: if ($resized) {
3129: $ima->Write($img_path);
3130: }
3131: }
3132: return;
1.977 amueller 3133: }
3134:
1.608 albertel 3135: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3136: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3137: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3138: # $context - possible values: coursedoc, existingfile, overwrite,
3139: # canceloverwrite, or ''.
3140: # if 'coursedoc': upload to the current course
3141: # if 'existingfile': write file to tmp/overwrites directory
3142: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3143: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3144: # $subdir - directory in userfile to store the file into
1.858 raeburn 3145: # $parser - instruction to parse file for objects ($parser = parse)
3146: # $allfiles - reference to hash for embedded objects
3147: # $codebase - reference to hash for codebase of java objects
3148: # $desuname - username for permanent storage of uploaded file
3149: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3150: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3151: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3152: # $resizewidth - width (pixels) to which to resize uploaded image
3153: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3154: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3155: # from File::MMagic.
1.858 raeburn 3156: #
1.686 albertel 3157: # output: url of file in userspace, or error: <message>
3158: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3159:
1.531 albertel 3160: sub userfileupload {
1.1090 raeburn 3161: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3162: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3163: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3164: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3165: $fname=&clean_filename($fname);
1.1090 raeburn 3166: # See if there is anything left
1.257 www 3167: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3168: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3169: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3170: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3171: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3172: my $now = time;
1.1090 raeburn 3173: my $filepath;
1.1095 raeburn 3174: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3175: $filepath = 'tmp/helprequests/'.$now;
3176: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3177: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3178: '_'.$env{'user.domain'}.'/pending';
3179: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3180: my ($docuname,$docudom);
3181: if ($destudom) {
3182: $docudom = $destudom;
3183: } else {
3184: $docudom = $env{'user.domain'};
3185: }
3186: if ($destuname) {
3187: $docuname = $destuname;
3188: } else {
3189: $docuname = $env{'user.name'};
3190: }
3191: if (exists($env{'form.group'})) {
3192: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3193: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3194: }
3195: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3196: if ($context eq 'canceloverwrite') {
3197: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3198: if (-e $tempfile) {
3199: my @info = stat($tempfile);
3200: if ($info[9] eq $env{'form.timestamp'}) {
3201: unlink($tempfile);
3202: }
3203: }
3204: return;
1.523 raeburn 3205: }
3206: }
1.1090 raeburn 3207: # Create the directory if not present
1.741 raeburn 3208: my @parts=split(/\//,$filepath);
3209: my $fullpath = $perlvar{'lonDaemons'};
3210: for (my $i=0;$i<@parts;$i++) {
3211: $fullpath .= '/'.$parts[$i];
3212: if ((-e $fullpath)!=1) {
3213: mkdir($fullpath,0777);
3214: }
3215: }
3216: open(my $fh,'>'.$fullpath.'/'.$fname);
3217: print $fh $env{'form.'.$formname};
3218: close($fh);
1.1090 raeburn 3219: if ($context eq 'existingfile') {
3220: my @info = stat($fullpath.'/'.$fname);
3221: return ($fullpath.'/'.$fname,$info[9]);
3222: } else {
3223: return $fullpath.'/'.$fname;
3224: }
1.523 raeburn 3225: }
1.995 raeburn 3226: if ($subdir eq 'scantron') {
3227: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3228: } else {
1.995 raeburn 3229: $fname="$subdir/$fname";
3230: }
1.1090 raeburn 3231: if ($context eq 'coursedoc') {
1.638 albertel 3232: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3233: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3234: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3235: return &finishuserfileupload($docuname,$docudom,
3236: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3237: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3238: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3239: } else {
1.1172.2.21 raeburn 3240: if ($env{'form.folder'}) {
3241: $fname=$env{'form.folder'}.'/'.$fname;
3242: }
1.638 albertel 3243: return &process_coursefile('uploaddoc',$docuname,$docudom,
3244: $fname,$formname,$parser,
1.1095 raeburn 3245: $allfiles,$codebase,$mimetype);
1.481 raeburn 3246: }
1.719 banghart 3247: } elsif (defined($destuname)) {
3248: my $docuname=$destuname;
3249: my $docudom=$destudom;
1.860 raeburn 3250: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3251: $parser,$allfiles,$codebase,
1.1051 raeburn 3252: $thumbwidth,$thumbheight,
1.1095 raeburn 3253: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3254: } else {
1.638 albertel 3255: my $docuname=$env{'user.name'};
3256: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3257: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3258: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3259: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3260: }
1.860 raeburn 3261: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3262: $parser,$allfiles,$codebase,
1.1051 raeburn 3263: $thumbwidth,$thumbheight,
1.1095 raeburn 3264: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3265: }
1.271 www 3266: }
3267:
3268: sub finishuserfileupload {
1.860 raeburn 3269: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3270: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3271: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3272: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3273:
1.860 raeburn 3274: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3275: $file=$fname;
3276: if ($fname=~m|/|) {
3277: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3278: $path.=$fnamepath.'/';
3279: }
1.259 www 3280: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3281: my $count;
3282: for ($count=4;$count<=$#parts;$count++) {
3283: $filepath.="/$parts[$count]";
3284: if ((-e $filepath)!=1) {
3285: mkdir($filepath,0777);
3286: }
3287: }
1.984 neumanie 3288:
1.258 www 3289: # Save the file
3290: {
1.701 albertel 3291: if (!open(FH,'>'.$filepath.'/'.$file)) {
3292: &logthis('Failed to create '.$filepath.'/'.$file);
3293: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3294: return '/adm/notfound.html';
3295: }
1.1090 raeburn 3296: if ($context eq 'overwrite') {
1.1117 foxr 3297: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3298: my $target = $filepath.'/'.$file;
3299: if (-e $source) {
3300: my @info = stat($source);
3301: if ($info[9] eq $env{'form.timestamp'}) {
3302: unless (&File::Copy::move($source,$target)) {
3303: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3304: return "Moving from $source failed";
3305: }
3306: } else {
3307: return "Temporary file: $source had unexpected date/time for last modification";
3308: }
3309: } else {
3310: return "Temporary file: $source missing";
3311: }
3312: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3313: &logthis('Failed to write to '.$filepath.'/'.$file);
3314: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3315: return '/adm/notfound.html';
3316: }
1.570 albertel 3317: close(FH);
1.1051 raeburn 3318: if ($resizewidth && $resizeheight) {
3319: my $mm = new File::MMagic;
3320: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3321: if ($mime_type =~ m{^image/}) {
3322: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3323: }
1.977 amueller 3324: }
1.258 www 3325: }
1.1152 raeburn 3326: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3327: if (ref($mimetype)) {
3328: if ($$mimetype eq '') {
3329: my $mm = new File::MMagic;
3330: my $type = $mm->checktype_filename($filepath.'/'.$file);
3331: $$mimetype = $type;
3332: }
3333: }
3334: }
1.637 raeburn 3335: if ($parser eq 'parse') {
1.1152 raeburn 3336: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3337: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3338: $allfiles,$codebase);
3339: unless ($parse_result eq 'ok') {
3340: &logthis('Failed to parse '.$filepath.$file.
3341: ' for embedded media: '.$parse_result);
3342: }
1.637 raeburn 3343: }
3344: }
1.860 raeburn 3345: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3346: my $input = $filepath.'/'.$file;
3347: my $output = $filepath.'/'.'tn-'.$file;
3348: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3349: system("convert -sample $thumbsize $input $output");
3350: if (-e $filepath.'/'.'tn-'.$file) {
3351: $fetchthumb = 1;
3352: }
3353: }
1.858 raeburn 3354:
1.259 www 3355: # Notify homeserver to grep it
3356: #
1.984 neumanie 3357: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3358: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3359: if ($fetchresult eq 'ok') {
1.860 raeburn 3360: if ($fetchthumb) {
3361: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3362: if ($thumbresult ne 'ok') {
3363: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3364: $docuhome.': '.$thumbresult);
3365: }
3366: }
1.259 www 3367: #
1.258 www 3368: # Return the URL to it
1.494 albertel 3369: return '/uploaded/'.$path.$file;
1.263 www 3370: } else {
1.494 albertel 3371: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3372: ': '.$fetchresult);
1.263 www 3373: return '/adm/notfound.html';
1.858 raeburn 3374: }
1.493 albertel 3375: }
3376:
1.637 raeburn 3377: sub extract_embedded_items {
1.961 raeburn 3378: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3379: my @state = ();
1.1164 raeburn 3380: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3381: my %javafiles = (
3382: codebase => '',
3383: code => '',
3384: archive => ''
3385: );
3386: my %mediafiles = (
3387: src => '',
3388: movie => '',
3389: );
1.648 raeburn 3390: my $p;
3391: if ($content) {
3392: $p = HTML::LCParser->new($content);
3393: } else {
1.961 raeburn 3394: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3395: }
1.641 albertel 3396: while (my $t=$p->get_token()) {
1.640 albertel 3397: if ($t->[0] eq 'S') {
3398: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3399: push(@state, $tagname);
1.648 raeburn 3400: if (lc($tagname) eq 'allow') {
3401: &add_filetype($allfiles,$attr->{'src'},'src');
3402: }
1.640 albertel 3403: if (lc($tagname) eq 'img') {
3404: &add_filetype($allfiles,$attr->{'src'},'src');
3405: }
1.886 albertel 3406: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3407: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3408: &add_filetype($allfiles,$attr->{'href'},'href');
3409: }
1.886 albertel 3410: }
1.645 raeburn 3411: if (lc($tagname) eq 'script') {
1.1164 raeburn 3412: my $src;
1.645 raeburn 3413: if ($attr->{'archive'} =~ /\.jar$/i) {
3414: &add_filetype($allfiles,$attr->{'archive'},'archive');
3415: } else {
1.1164 raeburn 3416: if ($attr->{'src'} ne '') {
3417: $src = $attr->{'src'};
3418: &add_filetype($allfiles,$src,'src');
3419: }
3420: }
3421: my $text = $p->get_trimmed_text();
3422: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3423: my @swfargs = split(/,/,$1);
3424: foreach my $item (@swfargs) {
3425: $item =~ s/["']//g;
3426: $item =~ s/^\s+//;
3427: $item =~ s/\s+$//;
3428: }
3429: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3430: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3431: push(@{$related{$swfargs[0]}},$swfargs[2]);
3432: } else {
3433: $related{$swfargs[0]} = [$swfargs[2]];
3434: }
3435: }
1.645 raeburn 3436: }
3437: }
3438: if (lc($tagname) eq 'link') {
3439: if (lc($attr->{'rel'}) eq 'stylesheet') {
3440: &add_filetype($allfiles,$attr->{'href'},'href');
3441: }
3442: }
1.640 albertel 3443: if (lc($tagname) eq 'object' ||
3444: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3445: foreach my $item (keys(%javafiles)) {
3446: $javafiles{$item} = '';
3447: }
1.1164 raeburn 3448: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3449: $lastids{lc($tagname)} = $attr->{'id'};
3450: }
1.640 albertel 3451: }
3452: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3453: my $name = lc($attr->{'name'});
3454: foreach my $item (keys(%javafiles)) {
3455: if ($name eq $item) {
3456: $javafiles{$item} = $attr->{'value'};
3457: last;
3458: }
3459: }
1.1164 raeburn 3460: my $pathfrom;
1.640 albertel 3461: foreach my $item (keys(%mediafiles)) {
3462: if ($name eq $item) {
1.1164 raeburn 3463: $pathfrom = $attr->{'value'};
3464: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3465: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3466: last;
3467: }
3468: }
1.1164 raeburn 3469: if ($name eq 'flashvars') {
3470: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3471: }
3472: if ($pathfrom ne '') {
3473: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3474: $pathfrom);
3475: }
1.640 albertel 3476: }
3477: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3478: foreach my $item (keys(%javafiles)) {
3479: if ($attr->{$item}) {
3480: $javafiles{$item} = $attr->{$item};
3481: last;
3482: }
3483: }
3484: foreach my $item (keys(%mediafiles)) {
3485: if ($attr->{$item}) {
3486: &add_filetype($allfiles,$attr->{$item},$item);
3487: last;
3488: }
3489: }
1.1164 raeburn 3490: if (lc($tagname) eq 'embed') {
3491: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3492: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3493: $attr->{'src'});
3494: }
3495: }
1.640 albertel 3496: }
1.1172.2.35 raeburn 3497: if (lc($tagname) eq 'iframe') {
3498: my $src = $attr->{'src'} ;
3499: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3500: &add_filetype($allfiles,$src,'src');
3501: } elsif ($src =~ m{^/}) {
3502: if ($env{'request.course.id'}) {
3503: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3504: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3505: my $url = &hreflocation('',$fullpath);
3506: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3507: my $relpath = $1;
3508: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3509: &add_filetype($allfiles,$1,'src');
3510: }
3511: }
3512: }
3513: }
3514: }
1.1164 raeburn 3515: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3516: pop(@state);
1.1164 raeburn 3517: }
1.640 albertel 3518: } elsif ($t->[0] eq 'E') {
3519: my ($tagname) = ($t->[1]);
3520: if ($javafiles{'codebase'} ne '') {
3521: $javafiles{'codebase'} .= '/';
3522: }
3523: if (lc($tagname) eq 'applet' ||
3524: lc($tagname) eq 'object' ||
3525: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3526: ) {
3527: foreach my $item (keys(%javafiles)) {
3528: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3529: my $file=$javafiles{'codebase'}.$javafiles{$item};
3530: &add_filetype($allfiles,$file,$item);
3531: }
3532: }
3533: }
3534: pop @state;
3535: }
3536: }
1.1164 raeburn 3537: foreach my $id (sort(keys(%flashvars))) {
3538: if ($shockwave{$id} ne '') {
3539: my @pairs = split(/\&/,$flashvars{$id});
3540: foreach my $pair (@pairs) {
3541: my ($key,$value) = split(/\=/,$pair);
3542: if ($key eq 'thumb') {
3543: &add_filetype($allfiles,$value,$key);
3544: } elsif ($key eq 'content') {
3545: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3546: my ($ext) = ($value =~ /\.([^.]+)$/);
3547: if ($ext ne '') {
3548: &add_filetype($allfiles,$path.$value,$ext);
3549: }
3550: }
3551: }
3552: }
3553: }
1.637 raeburn 3554: return 'ok';
3555: }
3556:
1.639 albertel 3557: sub add_filetype {
3558: my ($allfiles,$file,$type)=@_;
3559: if (exists($allfiles->{$file})) {
3560: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3561: push(@{$allfiles->{$file}}, &escape($type));
3562: }
3563: } else {
3564: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3565: }
3566: }
3567:
1.1164 raeburn 3568: sub embedded_dependency {
3569: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3570: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3571: if (($identifier ne '') &&
3572: (ref($related->{$identifier}) eq 'ARRAY') &&
3573: ($pathfrom ne '')) {
3574: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3575: foreach my $dep (@{$related->{$identifier}}) {
3576: &add_filetype($allfiles,$path.$dep,'object');
3577: }
3578: }
3579: }
3580: return;
3581: }
3582:
1.493 albertel 3583: sub removeuploadedurl {
1.984 neumanie 3584: my ($url)=@_;
3585: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3586: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3587: }
3588:
3589: sub removeuserfile {
3590: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3591: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3592: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3593: if ($result eq 'ok') {
1.798 raeburn 3594: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3595: my $metafile = $fname.'.meta';
3596: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3597: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3598: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3599: my $sqlresult =
1.823 albertel 3600: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3601: 'portfolio_metadata',$group,
3602: 'delete');
1.798 raeburn 3603: }
3604: }
3605: return $result;
1.257 www 3606: }
1.15 www 3607:
1.530 albertel 3608: sub mkdiruserfile {
3609: my ($docuname,$docudom,$dir)=@_;
3610: my $home=&homeserver($docuname,$docudom);
3611: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3612: }
3613:
1.531 albertel 3614: sub renameuserfile {
3615: my ($docuname,$docudom,$old,$new)=@_;
3616: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3617: my $result = &reply("renameuserfile:$docudom:$docuname:".
3618: &escape("$old").':'.&escape("$new"),$home);
3619: if ($result eq 'ok') {
3620: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3621: my $oldmeta = $old.'.meta';
3622: my $newmeta = $new.'.meta';
3623: my $metaresult =
3624: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3625: my $url = "/uploaded/$docudom/$docuname/$old";
3626: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3627: my $sqlresult =
1.823 albertel 3628: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3629: 'portfolio_metadata',$group,
3630: 'delete');
1.798 raeburn 3631: }
3632: }
3633: return $result;
1.531 albertel 3634: }
3635:
1.14 www 3636: # ------------------------------------------------------------------------- Log
3637:
3638: sub log {
3639: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3640: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3641: }
3642:
3643: # ------------------------------------------------------------------ Course Log
1.352 www 3644: #
3645: # This routine flushes several buffers of non-mission-critical nature
3646: #
1.157 www 3647:
3648: sub flushcourselogs {
1.352 www 3649: &logthis('Flushing log buffers');
3650: #
3651: # course logs
3652: # This is a log of all transactions in a course, which can be used
3653: # for data mining purposes
3654: #
3655: # It also collects the courseid database, which lists last transaction
3656: # times and course titles for all courseids
3657: #
3658: my %courseidbuffer=();
1.921 raeburn 3659: foreach my $crsid (keys(%courselogs)) {
1.352 www 3660: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3661: &escape($courselogs{$crsid}),
3662: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3663: delete $courselogs{$crsid};
3664: } else {
3665: &logthis('Failed to flush log buffer for '.$crsid);
3666: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3667: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3668: " exceeded maximum size, deleting.</font>");
3669: delete $courselogs{$crsid};
3670: }
1.352 www 3671: }
1.920 raeburn 3672: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3673: 'description' => $coursedescrbuf{$crsid},
3674: 'inst_code' => $courseinstcodebuf{$crsid},
3675: 'type' => $coursetypebuf{$crsid},
3676: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3677: };
1.191 harris41 3678: }
1.352 www 3679: #
3680: # Write course id database (reverse lookup) to homeserver of courses
3681: # Is used in pickcourse
3682: #
1.840 albertel 3683: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3684: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3685: $courseidbuffer{$crs_home},
3686: $crs_home,'timeonly');
1.352 www 3687: }
3688: #
3689: # File accesses
3690: # Writes to the dynamic metadata of resources to get hit counts, etc.
3691: #
1.449 matthew 3692: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3693: if ($entry =~ /___count$/) {
3694: my ($dom,$name);
1.807 albertel 3695: ($dom,$name,undef)=
1.811 albertel 3696: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3697: if (! defined($dom) || $dom eq '' ||
3698: ! defined($name) || $name eq '') {
1.620 albertel 3699: my $cid = $env{'request.course.id'};
3700: $dom = $env{'request.'.$cid.'.domain'};
3701: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3702: }
1.450 matthew 3703: my $value = $accesshash{$entry};
3704: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3705: my %temphash=($url => $value);
1.449 matthew 3706: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3707: if ($result eq 'ok') {
3708: delete $accesshash{$entry};
3709: }
3710: } else {
1.811 albertel 3711: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3712: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3713: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3714: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3715: delete $accesshash{$entry};
3716: }
1.185 www 3717: }
1.191 harris41 3718: }
1.352 www 3719: #
3720: # Roles
3721: # Reverse lookup of user roles for course faculty/staff and co-authorship
3722: #
1.800 albertel 3723: foreach my $entry (keys(%userrolehash)) {
1.351 www 3724: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3725: split(/\:/,$entry);
3726: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3727: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3728: $rudom,$runame) eq 'ok') {
3729: delete $userrolehash{$entry};
3730: }
3731: }
1.662 raeburn 3732: #
3733: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3734: #
3735: my %domrolebuffer = ();
1.1000 raeburn 3736: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3737: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3738: if ($domrolebuffer{$rudom}) {
3739: $domrolebuffer{$rudom}.='&'.&escape($entry).
3740: '='.&escape($domainrolehash{$entry});
3741: } else {
3742: $domrolebuffer{$rudom}.=&escape($entry).
3743: '='.&escape($domainrolehash{$entry});
3744: }
3745: delete $domainrolehash{$entry};
3746: }
3747: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3748: my %servers = &get_servers($dom,'library');
3749: foreach my $tryserver (keys(%servers)) {
3750: unless (&reply('domroleput:'.$dom.':'.
3751: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3752: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3753: }
1.662 raeburn 3754: }
3755: }
1.186 www 3756: $dumpcount++;
1.157 www 3757: }
3758:
3759: sub courselog {
3760: my $what=shift;
1.158 www 3761: $what=time.':'.$what;
1.620 albertel 3762: unless ($env{'request.course.id'}) { return ''; }
3763: $coursedombuf{$env{'request.course.id'}}=
3764: $env{'course.'.$env{'request.course.id'}.'.domain'};
3765: $coursenumbuf{$env{'request.course.id'}}=
3766: $env{'course.'.$env{'request.course.id'}.'.num'};
3767: $coursehombuf{$env{'request.course.id'}}=
3768: $env{'course.'.$env{'request.course.id'}.'.home'};
3769: $coursedescrbuf{$env{'request.course.id'}}=
3770: $env{'course.'.$env{'request.course.id'}.'.description'};
3771: $courseinstcodebuf{$env{'request.course.id'}}=
3772: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3773: $courseownerbuf{$env{'request.course.id'}}=
3774: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3775: $coursetypebuf{$env{'request.course.id'}}=
3776: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3777: if (defined $courselogs{$env{'request.course.id'}}) {
3778: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3779: } else {
1.620 albertel 3780: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3781: }
1.620 albertel 3782: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3783: &flushcourselogs();
3784: }
1.158 www 3785: }
3786:
3787: sub courseacclog {
3788: my $fnsymb=shift;
1.620 albertel 3789: unless ($env{'request.course.id'}) { return ''; }
3790: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3791: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3792: $what.=':POST';
1.583 matthew 3793: # FIXME: Probably ought to escape things....
1.800 albertel 3794: foreach my $key (keys(%env)) {
3795: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3796: my $formitem = $1;
3797: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3798: $what.=':'.$formitem.'='.$env{$key};
3799: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3800: $what.=':'.$formitem.'='.$env{$key};
3801: }
1.158 www 3802: }
1.191 harris41 3803: }
1.583 matthew 3804: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3805: # FIXME: We should not be depending on a form parameter that someone
3806: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3807: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3808: $what.= ':POST';
3809: # FIXME: Probably ought to escape things....
3810: foreach my $element ('courseexp','crsfulltext','crsrelated',
3811: 'crsdiscuss') {
1.620 albertel 3812: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3813: }
3814: }
1.158 www 3815: }
3816: &courselog($what);
1.149 www 3817: }
3818:
1.185 www 3819: sub countacc {
3820: my $url=&declutter(shift);
1.458 matthew 3821: return if (! defined($url) || $url eq '');
1.620 albertel 3822: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3823: #
3824: # Mark that this url was used in this course
3825: #
1.620 albertel 3826: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3827: #
3828: # Increase the access count for this resource in this child process
3829: #
1.281 www 3830: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3831: $accesshash{$key}++;
1.185 www 3832: }
1.349 www 3833:
1.361 www 3834: sub linklog {
3835: my ($from,$to)=@_;
3836: $from=&declutter($from);
3837: $to=&declutter($to);
3838: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3839: $accesshash{$to.'___'.$from.'___goto'}=1;
3840: }
1.1160 www 3841:
3842: sub statslog {
3843: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3844: if ($users<2) { return; }
3845: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3846: 'course' => $env{'request.course.id'},
3847: 'sections' => '"all"',
3848: 'num_students' => $users,
3849: 'part' => $part,
3850: 'symb' => $symb,
3851: 'mean_tries' => $av_attempts,
3852: 'deg_of_diff' => $degdiff});
3853: foreach my $key (keys(%dynstore)) {
3854: $accesshash{$key}=$dynstore{$key};
3855: }
3856: }
1.361 www 3857:
1.349 www 3858: sub userrolelog {
3859: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3860: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3861: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3862: $userrolehash
3863: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3864: =$tend.':'.$tstart;
1.662 raeburn 3865: }
1.1169 droeschl 3866: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3867: $userrolehash
3868: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3869: =$tend.':'.$tstart;
3870: }
1.1169 droeschl 3871: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3872: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3873: $domainrolehash
3874: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3875: = $tend.':'.$tstart;
3876: }
1.351 www 3877: }
3878:
1.957 raeburn 3879: sub courserolelog {
3880: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3881: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3882: my $cdom = $1;
3883: my $cnum = $2;
3884: my $sec = $3;
3885: my $namespace = 'rolelog';
3886: my %storehash = (
3887: role => $trole,
3888: start => $tstart,
3889: end => $tend,
3890: selfenroll => $selfenroll,
3891: context => $context,
3892: );
3893: if ($trole eq 'gr') {
3894: $namespace = 'groupslog';
3895: $storehash{'group'} = $sec;
3896: } else {
3897: $storehash{'section'} = $sec;
3898: }
3899: &write_log('course',$namespace,\%storehash,$delflag,$username,
3900: $domain,$cnum,$cdom);
3901: if (($trole ne 'st') || ($sec ne '')) {
3902: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3903: }
3904: }
3905: return;
3906: }
3907:
1.1172.2.9 raeburn 3908: sub domainrolelog {
3909: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3910: if ($area =~ m{^/($match_domain)/$}) {
3911: my $cdom = $1;
3912: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3913: my $namespace = 'rolelog';
3914: my %storehash = (
3915: role => $trole,
3916: start => $tstart,
3917: end => $tend,
3918: context => $context,
3919: );
3920: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3921: $domain,$domconfiguser,$cdom);
3922: }
3923: return;
3924:
3925: }
3926:
3927: sub coauthorrolelog {
3928: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3929: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3930: my $audom = $1;
3931: my $auname = $2;
3932: my $namespace = 'rolelog';
3933: my %storehash = (
3934: role => $trole,
3935: start => $tstart,
3936: end => $tend,
3937: context => $context,
3938: );
3939: &write_log('author',$namespace,\%storehash,$delflag,$username,
3940: $domain,$auname,$audom);
3941: }
3942: return;
3943: }
3944:
1.351 www 3945: sub get_course_adv_roles {
1.948 raeburn 3946: my ($cid,$codes) = @_;
1.620 albertel 3947: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3948: my %coursehash=&coursedescription($cid);
1.988 raeburn 3949: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3950: my %nothide=();
1.800 albertel 3951: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3952: if ($user !~ /:/) {
3953: $nothide{join(':',split(/[\@]/,$user))}=1;
3954: } else {
3955: $nothide{$user}=1;
3956: }
1.470 www 3957: }
1.1172.2.23 raeburn 3958: my @possdoms = ($coursehash{'domain'});
3959: if ($coursehash{'checkforpriv'}) {
3960: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3961: }
1.351 www 3962: my %returnhash=();
3963: my %dumphash=
3964: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3965: my $now=time;
1.997 raeburn 3966: my %privileged;
1.1000 raeburn 3967: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3968: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3969: if (($tstart) && ($tstart<0)) { next; }
3970: if (($tend) && ($tend<$now)) { next; }
3971: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3972: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3973: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 3974: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3975: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3976: if ($role eq 'cr') { next; }
1.948 raeburn 3977: if ($codes) {
3978: if ($section) { $role .= ':'.$section; }
3979: if ($returnhash{$role}) {
3980: $returnhash{$role}.=','.$username.':'.$domain;
3981: } else {
3982: $returnhash{$role}=$username.':'.$domain;
3983: }
1.351 www 3984: } else {
1.988 raeburn 3985: my $key=&plaintext($role,$crstype);
1.973 bisitz 3986: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3987: if ($returnhash{$key}) {
3988: $returnhash{$key}.=','.$username.':'.$domain;
3989: } else {
3990: $returnhash{$key}=$username.':'.$domain;
3991: }
1.351 www 3992: }
1.948 raeburn 3993: }
1.400 www 3994: return %returnhash;
3995: }
3996:
3997: sub get_my_roles {
1.937 raeburn 3998: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3999: unless (defined($uname)) { $uname=$env{'user.name'}; }
4000: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4001: my (%dumphash,%nothide);
1.1086 raeburn 4002: if ($context eq 'userroles') {
1.1166 raeburn 4003: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4004: } else {
1.1172.2.23 raeburn 4005: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4006: if ($hidepriv) {
4007: my %coursehash=&coursedescription($udom.'_'.$uname);
4008: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4009: if ($user !~ /:/) {
4010: $nothide{join(':',split(/[\@]/,$user))} = 1;
4011: } else {
4012: $nothide{$user} = 1;
4013: }
4014: }
4015: }
1.858 raeburn 4016: }
1.400 www 4017: my %returnhash=();
4018: my $now=time;
1.999 raeburn 4019: my %privileged;
1.800 albertel 4020: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4021: my ($role,$tend,$tstart);
4022: if ($context eq 'userroles') {
1.1149 raeburn 4023: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4024: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4025: } else {
4026: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4027: }
1.400 www 4028: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4029: my $status = 'active';
1.939 raeburn 4030: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4031: $status = 'previous';
4032: }
4033: if (($tstart) && ($now<$tstart)) {
4034: $status = 'future';
4035: }
4036: if (ref($types) eq 'ARRAY') {
4037: if (!grep(/^\Q$status\E$/,@{$types})) {
4038: next;
4039: }
4040: } else {
4041: if ($status ne 'active') {
4042: next;
4043: }
4044: }
1.867 raeburn 4045: my ($rolecode,$username,$domain,$section,$area);
4046: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4047: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4048: (undef,$domain,$username,$section) = split(/\//,$area);
4049: } else {
4050: ($role,$username,$domain,$section) = split(/\:/,$entry);
4051: }
1.832 raeburn 4052: if (ref($roledoms) eq 'ARRAY') {
4053: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4054: next;
4055: }
4056: }
4057: if (ref($roles) eq 'ARRAY') {
4058: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4059: if ($role =~ /^cr\//) {
4060: if (!grep(/^cr$/,@{$roles})) {
4061: next;
4062: }
1.1104 raeburn 4063: } elsif ($role =~ /^gr\//) {
4064: if (!grep(/^gr$/,@{$roles})) {
4065: next;
4066: }
1.922 raeburn 4067: } else {
4068: next;
4069: }
1.832 raeburn 4070: }
1.867 raeburn 4071: }
1.937 raeburn 4072: if ($hidepriv) {
1.1172.2.23 raeburn 4073: my @privroles = ('dc','su');
1.999 raeburn 4074: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4075: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4076: } else {
1.1172.2.23 raeburn 4077: my $possdoms = [$domain];
4078: if (ref($roledoms) eq 'ARRAY') {
4079: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4080: }
1.1172.2.23 raeburn 4081: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4082: if (!$nothide{$username.':'.$domain}) {
4083: next;
4084: }
4085: }
1.937 raeburn 4086: }
4087: }
1.933 raeburn 4088: if ($withsec) {
4089: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4090: $tstart.':'.$tend;
4091: } else {
4092: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4093: }
1.832 raeburn 4094: }
1.373 www 4095: return %returnhash;
1.399 www 4096: }
4097:
4098: # ----------------------------------------------------- Frontpage Announcements
4099: #
4100: #
4101:
4102: sub postannounce {
4103: my ($server,$text)=@_;
1.844 albertel 4104: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4105: unless ($text=~/\w/) { $text=''; }
4106: return &reply('setannounce:'.&escape($text),$server);
4107: }
4108:
4109: sub getannounce {
1.448 albertel 4110:
4111: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4112: my $announcement='';
1.800 albertel 4113: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4114: close($fh);
1.399 www 4115: if ($announcement=~/\w/) {
4116: return
4117: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4118: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4119: } else {
4120: return '';
4121: }
4122: } else {
4123: return '';
4124: }
1.351 www 4125: }
1.353 www 4126:
4127: # ---------------------------------------------------------- Course ID routines
4128: # Deal with domain's nohist_courseid.db files
4129: #
4130:
4131: sub courseidput {
1.921 raeburn 4132: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4133: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4134: my $outcome;
4135: if ($caller eq 'timeonly') {
4136: my $cids = '';
4137: foreach my $item (keys(%$storehash)) {
4138: $cids.=&escape($item).'&';
4139: }
4140: $cids=~s/\&$//;
4141: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4142: $coursehome);
4143: } else {
4144: my $items = '';
4145: foreach my $item (keys(%$storehash)) {
4146: $items.= &escape($item).'='.
4147: &freeze_escape($$storehash{$item}).'&';
4148: }
4149: $items=~s/\&$//;
4150: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4151: $coursehome);
1.918 raeburn 4152: }
4153: if ($outcome eq 'unknown_cmd') {
4154: my $what;
4155: foreach my $cid (keys(%$storehash)) {
4156: $what .= &escape($cid).'=';
1.921 raeburn 4157: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4158: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4159: }
4160: $what =~ s/\:$/&/;
4161: }
4162: $what =~ s/\&$//;
4163: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4164: } else {
4165: return $outcome;
4166: }
1.353 www 4167: }
4168:
4169: sub courseiddump {
1.921 raeburn 4170: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4171: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4172: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4173: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4174: my $as_hash = 1;
4175: my %returnhash;
4176: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4177: my %libserv = &all_library();
4178: foreach my $tryserver (keys(%libserv)) {
4179: if ( ( $hostidflag == 1
4180: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4181: || (!defined($hostidflag)) ) {
4182:
1.918 raeburn 4183: if (($domfilter eq '') ||
4184: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4185: my $rep;
4186: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4187: $rep = &LONCAPA::Lond::dump_course_id_handler(
4188: join(":", (&host_domain($tryserver), $sincefilter,
4189: &escape($descfilter), &escape($instcodefilter),
4190: &escape($ownerfilter), &escape($coursefilter),
4191: &escape($typefilter), &escape($regexp_ok),
4192: $as_hash, &escape($selfenrollonly),
4193: &escape($catfilter), $showhidden, $caller,
4194: &escape($cloner), &escape($cc_clone), $cloneonly,
4195: &escape($createdbefore), &escape($createdafter),
4196: &escape($creationcontext), $domcloner)));
4197: } else {
4198: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4199: $sincefilter.':'.&escape($descfilter).':'.
4200: &escape($instcodefilter).':'.&escape($ownerfilter).
4201: ':'.&escape($coursefilter).':'.&escape($typefilter).
4202: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4203: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4204: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4205: &escape($cc_clone).':'.$cloneonly.':'.
4206: &escape($createdbefore).':'.&escape($createdafter).':'.
4207: &escape($creationcontext).':'.$domcloner,
4208: $tryserver);
4209: }
4210:
1.918 raeburn 4211: my @pairs=split(/\&/,$rep);
4212: foreach my $item (@pairs) {
4213: my ($key,$value)=split(/\=/,$item,2);
4214: $key = &unescape($key);
4215: next if ($key =~ /^error: 2 /);
4216: my $result = &thaw_unescape($value);
4217: if (ref($result) eq 'HASH') {
4218: $returnhash{$key}=$result;
4219: } else {
1.921 raeburn 4220: my @responses = split(/:/,$value);
4221: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4222: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4223: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4224: }
1.1008 raeburn 4225: }
1.353 www 4226: }
4227: }
4228: }
4229: }
4230: return %returnhash;
4231: }
4232:
1.1055 raeburn 4233: sub courselastaccess {
4234: my ($cdom,$cnum,$hostidref) = @_;
4235: my %returnhash;
4236: if ($cdom && $cnum) {
4237: my $chome = &homeserver($cnum,$cdom);
4238: if ($chome ne 'no_host') {
4239: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4240: &extract_lastaccess(\%returnhash,$rep);
4241: }
4242: } else {
4243: if (!$cdom) { $cdom=''; }
4244: my %libserv = &all_library();
4245: foreach my $tryserver (keys(%libserv)) {
4246: if (ref($hostidref) eq 'ARRAY') {
4247: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4248: }
4249: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4250: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4251: &extract_lastaccess(\%returnhash,$rep);
4252: }
4253: }
4254: }
4255: return %returnhash;
4256: }
4257:
4258: sub extract_lastaccess {
4259: my ($returnhash,$rep) = @_;
4260: if (ref($returnhash) eq 'HASH') {
4261: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4262: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4263: $rep eq '') {
4264: my @pairs=split(/\&/,$rep);
4265: foreach my $item (@pairs) {
4266: my ($key,$value)=split(/\=/,$item,2);
4267: $key = &unescape($key);
4268: next if ($key =~ /^error: 2 /);
4269: $returnhash->{$key} = &thaw_unescape($value);
4270: }
4271: }
4272: }
4273: return;
4274: }
4275:
1.658 raeburn 4276: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4277:
4278: sub dcmailput {
1.685 raeburn 4279: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4280: my $status = &Apache::lonnet::critical(
1.740 www 4281: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4282: &escape($message),$server);
1.662 raeburn 4283: return $status;
4284: }
4285:
1.658 raeburn 4286: sub dcmaildump {
4287: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4288: my %returnhash=();
1.846 albertel 4289:
4290: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4291: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4292: &escape($enddate).':';
4293: my @esc_senders=map { &escape($_)} @$senders;
4294: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4295: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4296: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4297: if (($key) && ($value)) {
4298: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4299: }
4300: }
4301: }
4302: return %returnhash;
4303: }
1.662 raeburn 4304: # ---------------------------------------------------------- Domain roles
4305:
4306: sub get_domain_roles {
4307: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4308: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4309: $startdate = '.';
4310: }
1.1018 raeburn 4311: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4312: $enddate = '.';
4313: }
1.922 raeburn 4314: my $rolelist;
4315: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4316: $rolelist = join('&',@{$roles});
1.922 raeburn 4317: }
1.662 raeburn 4318: my %personnel = ();
1.841 albertel 4319:
4320: my %servers = &get_servers($dom,'library');
4321: foreach my $tryserver (keys(%servers)) {
4322: %{$personnel{$tryserver}}=();
4323: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4324: &escape($startdate).':'.
4325: &escape($enddate).':'.
4326: &escape($rolelist), $tryserver))) {
4327: my ($key,$value) = split(/\=/,$line,2);
4328: if (($key) && ($value)) {
4329: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4330: }
4331: }
1.662 raeburn 4332: }
4333: return %personnel;
4334: }
1.658 raeburn 4335:
1.1057 www 4336: # ----------------------------------------------------------- Interval timing
1.149 www 4337:
1.1153 www 4338: {
4339: # Caches needed for speedup of navmaps
4340: # We don't want to cache this for very long at all (5 seconds at most)
4341: #
4342: # The user for whom we cache
4343: my $cachedkey='';
4344: # The cached times for this user
4345: my %cachedtimes=();
4346: # When this was last done
4347: my $cachedtime=();
4348:
4349: sub load_all_first_access {
1.1154 raeburn 4350: my ($uname,$udom)=@_;
1.1156 www 4351: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4352: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4353: return;
4354: }
4355: $cachedtime=time;
4356: $cachedkey=$uname.':'.$udom;
4357: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4358: }
4359:
1.504 albertel 4360: sub get_first_access {
1.1162 raeburn 4361: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4362: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4363: if ($argsymb) { $symb=$argsymb; }
4364: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4365: if ($argmap) { $map = $argmap; }
1.926 albertel 4366: if ($type eq 'course') {
4367: $res='course';
4368: } elsif ($type eq 'map') {
1.588 albertel 4369: $res=&symbread($map);
4370: } else {
4371: $res=$symb;
4372: }
1.1153 www 4373: &load_all_first_access($uname,$udom);
4374: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4375: }
4376:
4377: sub set_first_access {
1.1162 raeburn 4378: my ($type,$interval)=@_;
1.790 albertel 4379: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4380: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4381: if ($type eq 'course') {
4382: $res='course';
4383: } elsif ($type eq 'map') {
1.588 albertel 4384: $res=&symbread($map);
4385: } else {
4386: $res=$symb;
4387: }
1.1153 www 4388: $cachedkey='';
1.1162 raeburn 4389: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4390: if (!$firstaccess) {
1.1162 raeburn 4391: my $start = time;
4392: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4393: $udom,$uname);
4394: if ($putres eq 'ok') {
4395: &put('timerinterval',{"$courseid\0$res"=>$interval},
4396: $udom,$uname);
4397: &appenv(
4398: {
4399: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4400: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4401: }
4402: );
4403: }
4404: return $putres;
1.505 albertel 4405: }
4406: return 'already_set';
1.504 albertel 4407: }
1.1153 www 4408: }
1.1172.2.32 raeburn 4409:
4410: sub checkout {
4411: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4412: my $now=time;
4413: my $lonhost=$perlvar{'lonHostID'};
4414: my $infostr=&escape(
4415: 'CHECKOUTTOKEN&'.
4416: $tuname.'&'.
4417: $tudom.'&'.
4418: $tcrsid.'&'.
4419: $symb.'&'.
4420: $now.'&'.$ENV{'REMOTE_ADDR'});
4421: my $token=&reply('tmpput:'.$infostr,$lonhost);
4422: if ($token=~/^error\:/) {
4423: &logthis("<font color=\"blue\">WARNING: ".
4424: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4425: "</font>");
4426: return '';
4427: }
4428:
4429: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4430: $token=~tr/a-z/A-Z/;
4431:
4432: my %infohash=('resource.0.outtoken' => $token,
4433: 'resource.0.checkouttime' => $now,
4434: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4435:
4436: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4437: return '';
4438: } else {
4439: &logthis("<font color=\"blue\">WARNING: ".
4440: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4441: "</font>");
4442: }
4443:
4444: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4445: &escape('Checkout '.$infostr.' - '.
4446: $token)) ne 'ok') {
4447: return '';
4448: } else {
4449: &logthis("<font color=\"blue\">WARNING: ".
4450: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4451: "</font>");
4452: }
4453: return $token;
4454: }
4455:
4456: # ------------------------------------------------------------ Check in an item
4457:
4458: sub checkin {
4459: my $token=shift;
4460: my $now=time;
4461: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4462: $lonhost=~tr/A-Z/a-z/;
4463: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4464: $dtoken=~s/\W/\_/g;
4465: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4466: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4467:
4468: unless (($tuname) && ($tudom)) {
4469: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4470: return '';
4471: }
4472:
4473: unless (&allowed('mgr',$tcrsid)) {
4474: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4475: $env{'user.name'}.' - '.$env{'user.domain'});
4476: return '';
4477: }
4478:
4479: my %infohash=('resource.0.intoken' => $token,
4480: 'resource.0.checkintime' => $now,
4481: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4482:
4483: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4484: return '';
4485: }
4486:
4487: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4488: &escape('Checkin - '.$token)) ne 'ok') {
4489: return '';
4490: }
4491:
4492: return ($symb,$tuname,$tudom,$tcrsid);
4493: }
4494:
1.110 www 4495: # --------------------------------------------- Set Expire Date for Spreadsheet
4496:
4497: sub expirespread {
4498: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4499: my $cid=$env{'request.course.id'};
1.110 www 4500: if ($cid) {
4501: my $now=time;
4502: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4503: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4504: $env{'course.'.$cid.'.num'}.
1.110 www 4505: ':nohist_expirationdates:'.
4506: &escape($key).'='.$now,
1.620 albertel 4507: $env{'course.'.$cid.'.home'})
1.110 www 4508: }
4509: return 'ok';
1.14 www 4510: }
4511:
1.109 www 4512: # ----------------------------------------------------- Devalidate Spreadsheets
4513:
4514: sub devalidate {
1.325 www 4515: my ($symb,$uname,$udom)=@_;
1.620 albertel 4516: my $cid=$env{'request.course.id'};
1.109 www 4517: if ($cid) {
1.391 matthew 4518: # delete the stored spreadsheets for
4519: # - the student level sheet of this user in course's homespace
4520: # - the assessment level sheet for this resource
4521: # for this user in user's homespace
1.553 albertel 4522: # - current conditional state info
1.325 www 4523: my $key=$uname.':'.$udom.':';
1.109 www 4524: my $status=
1.299 matthew 4525: &del('nohist_calculatedsheets',
1.391 matthew 4526: [$key.'studentcalc:'],
1.620 albertel 4527: $env{'course.'.$cid.'.domain'},
4528: $env{'course.'.$cid.'.num'})
1.133 albertel 4529: .' '.
4530: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4531: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4532: unless ($status eq 'ok ok') {
4533: &logthis('Could not devalidate spreadsheet '.
1.325 www 4534: $uname.' at '.$udom.' for '.
1.109 www 4535: $symb.': '.$status);
1.133 albertel 4536: }
1.553 albertel 4537: &delenv('user.state.'.$cid);
1.109 www 4538: }
4539: }
4540:
1.265 albertel 4541: sub get_scalar {
4542: my ($string,$end) = @_;
4543: my $value;
4544: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4545: $value = $1;
4546: } elsif ($$string =~ s/^([^&]*?)&//) {
4547: $value = $1;
4548: }
4549: return &unescape($value);
4550: }
4551:
4552: sub array2str {
4553: my (@array) = @_;
4554: my $result=&arrayref2str(\@array);
4555: $result=~s/^__ARRAY_REF__//;
4556: $result=~s/__END_ARRAY_REF__$//;
4557: return $result;
4558: }
4559:
1.204 albertel 4560: sub arrayref2str {
4561: my ($arrayref) = @_;
1.265 albertel 4562: my $result='__ARRAY_REF__';
1.204 albertel 4563: foreach my $elem (@$arrayref) {
1.265 albertel 4564: if(ref($elem) eq 'ARRAY') {
4565: $result.=&arrayref2str($elem).'&';
4566: } elsif(ref($elem) eq 'HASH') {
4567: $result.=&hashref2str($elem).'&';
4568: } elsif(ref($elem)) {
4569: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4570: } else {
4571: $result.=&escape($elem).'&';
4572: }
4573: }
4574: $result=~s/\&$//;
1.265 albertel 4575: $result .= '__END_ARRAY_REF__';
1.204 albertel 4576: return $result;
4577: }
4578:
1.168 albertel 4579: sub hash2str {
1.204 albertel 4580: my (%hash) = @_;
4581: my $result=&hashref2str(\%hash);
1.265 albertel 4582: $result=~s/^__HASH_REF__//;
4583: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4584: return $result;
4585: }
4586:
4587: sub hashref2str {
4588: my ($hashref)=@_;
1.265 albertel 4589: my $result='__HASH_REF__';
1.800 albertel 4590: foreach my $key (sort(keys(%$hashref))) {
4591: if (ref($key) eq 'ARRAY') {
4592: $result.=&arrayref2str($key).'=';
4593: } elsif (ref($key) eq 'HASH') {
4594: $result.=&hashref2str($key).'=';
4595: } elsif (ref($key)) {
1.265 albertel 4596: $result.='=';
1.800 albertel 4597: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4598: } else {
1.1132 raeburn 4599: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4600: }
4601:
1.800 albertel 4602: if(ref($hashref->{$key}) eq 'ARRAY') {
4603: $result.=&arrayref2str($hashref->{$key}).'&';
4604: } elsif(ref($hashref->{$key}) eq 'HASH') {
4605: $result.=&hashref2str($hashref->{$key}).'&';
4606: } elsif(ref($hashref->{$key})) {
1.265 albertel 4607: $result.='&';
1.800 albertel 4608: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4609: } else {
1.800 albertel 4610: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4611: }
4612: }
1.168 albertel 4613: $result=~s/\&$//;
1.265 albertel 4614: $result .= '__END_HASH_REF__';
1.168 albertel 4615: return $result;
4616: }
4617:
4618: sub str2hash {
1.265 albertel 4619: my ($string)=@_;
4620: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4621: return %$hash;
4622: }
4623:
4624: sub str2hashref {
1.168 albertel 4625: my ($string) = @_;
1.265 albertel 4626:
4627: my %hash;
4628:
4629: if($string !~ /^__HASH_REF__/) {
4630: if (! ($string eq '' || !defined($string))) {
4631: $hash{'error'}='Not hash reference';
4632: }
4633: return (\%hash, $string);
4634: }
4635:
4636: $string =~ s/^__HASH_REF__//;
4637:
4638: while($string !~ /^__END_HASH_REF__/) {
4639: #key
4640: my $key='';
4641: if($string =~ /^__HASH_REF__/) {
4642: ($key, $string)=&str2hashref($string);
4643: if(defined($key->{'error'})) {
4644: $hash{'error'}='Bad data';
4645: return (\%hash, $string);
4646: }
4647: } elsif($string =~ /^__ARRAY_REF__/) {
4648: ($key, $string)=&str2arrayref($string);
4649: if($key->[0] eq 'Array reference error') {
4650: $hash{'error'}='Bad data';
4651: return (\%hash, $string);
4652: }
4653: } else {
4654: $string =~ s/^(.*?)=//;
1.267 albertel 4655: $key=&unescape($1);
1.265 albertel 4656: }
4657: $string =~ s/^=//;
4658:
4659: #value
4660: my $value='';
4661: if($string =~ /^__HASH_REF__/) {
4662: ($value, $string)=&str2hashref($string);
4663: if(defined($value->{'error'})) {
4664: $hash{'error'}='Bad data';
4665: return (\%hash, $string);
4666: }
4667: } elsif($string =~ /^__ARRAY_REF__/) {
4668: ($value, $string)=&str2arrayref($string);
4669: if($value->[0] eq 'Array reference error') {
4670: $hash{'error'}='Bad data';
4671: return (\%hash, $string);
4672: }
4673: } else {
4674: $value=&get_scalar(\$string,'__END_HASH_REF__');
4675: }
4676: $string =~ s/^&//;
4677:
4678: $hash{$key}=$value;
1.204 albertel 4679: }
1.265 albertel 4680:
4681: $string =~ s/^__END_HASH_REF__//;
4682:
4683: return (\%hash, $string);
1.204 albertel 4684: }
4685:
4686: sub str2array {
1.265 albertel 4687: my ($string)=@_;
4688: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4689: return @$array;
4690: }
4691:
4692: sub str2arrayref {
1.204 albertel 4693: my ($string) = @_;
1.265 albertel 4694: my @array;
4695:
4696: if($string !~ /^__ARRAY_REF__/) {
4697: if (! ($string eq '' || !defined($string))) {
4698: $array[0]='Array reference error';
4699: }
4700: return (\@array, $string);
4701: }
4702:
4703: $string =~ s/^__ARRAY_REF__//;
4704:
4705: while($string !~ /^__END_ARRAY_REF__/) {
4706: my $value='';
4707: if($string =~ /^__HASH_REF__/) {
4708: ($value, $string)=&str2hashref($string);
4709: if(defined($value->{'error'})) {
4710: $array[0] ='Array reference error';
4711: return (\@array, $string);
4712: }
4713: } elsif($string =~ /^__ARRAY_REF__/) {
4714: ($value, $string)=&str2arrayref($string);
4715: if($value->[0] eq 'Array reference error') {
4716: $array[0] ='Array reference error';
4717: return (\@array, $string);
4718: }
4719: } else {
4720: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4721: }
4722: $string =~ s/^&//;
4723:
4724: push(@array, $value);
1.191 harris41 4725: }
1.265 albertel 4726:
4727: $string =~ s/^__END_ARRAY_REF__//;
4728:
4729: return (\@array, $string);
1.168 albertel 4730: }
4731:
1.167 albertel 4732: # -------------------------------------------------------------------Temp Store
4733:
1.168 albertel 4734: sub tmpreset {
4735: my ($symb,$namespace,$domain,$stuname) = @_;
4736: if (!$symb) {
4737: $symb=&symbread();
1.620 albertel 4738: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4739: }
4740: $symb=escape($symb);
4741:
1.620 albertel 4742: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4743: $namespace=~s/\//\_/g;
4744: $namespace=~s/\W//g;
4745:
1.620 albertel 4746: if (!$domain) { $domain=$env{'user.domain'}; }
4747: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4748: if ($domain eq 'public' && $stuname eq 'public') {
4749: $stuname=$ENV{'REMOTE_ADDR'};
4750: }
1.1117 foxr 4751: my $path=LONCAPA::tempdir();
1.168 albertel 4752: my %hash;
4753: if (tie(%hash,'GDBM_File',
4754: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4755: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4756: foreach my $key (keys(%hash)) {
1.180 albertel 4757: if ($key=~ /:$symb/) {
1.168 albertel 4758: delete($hash{$key});
4759: }
4760: }
4761: }
4762: }
4763:
1.167 albertel 4764: sub tmpstore {
1.168 albertel 4765: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4766:
4767: if (!$symb) {
4768: $symb=&symbread();
1.620 albertel 4769: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4770: }
4771: $symb=escape($symb);
4772:
4773: if (!$namespace) {
4774: # I don't think we would ever want to store this for a course.
4775: # it seems this will only be used if we don't have a course.
1.620 albertel 4776: #$namespace=$env{'request.course.id'};
1.168 albertel 4777: #if (!$namespace) {
1.620 albertel 4778: $namespace=$env{'request.state'};
1.168 albertel 4779: #}
4780: }
4781: $namespace=~s/\//\_/g;
4782: $namespace=~s/\W//g;
1.620 albertel 4783: if (!$domain) { $domain=$env{'user.domain'}; }
4784: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4785: if ($domain eq 'public' && $stuname eq 'public') {
4786: $stuname=$ENV{'REMOTE_ADDR'};
4787: }
1.168 albertel 4788: my $now=time;
4789: my %hash;
1.1117 foxr 4790: my $path=LONCAPA::tempdir();
1.168 albertel 4791: if (tie(%hash,'GDBM_File',
4792: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4793: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4794: $hash{"version:$symb"}++;
4795: my $version=$hash{"version:$symb"};
4796: my $allkeys='';
4797: foreach my $key (keys(%$storehash)) {
4798: $allkeys.=$key.':';
1.591 albertel 4799: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4800: }
4801: $hash{"$version:$symb:timestamp"}=$now;
4802: $allkeys.='timestamp';
4803: $hash{"$version:keys:$symb"}=$allkeys;
4804: if (untie(%hash)) {
4805: return 'ok';
4806: } else {
4807: return "error:$!";
4808: }
4809: } else {
4810: return "error:$!";
4811: }
4812: }
1.167 albertel 4813:
1.168 albertel 4814: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4815:
1.168 albertel 4816: sub tmprestore {
4817: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4818:
1.168 albertel 4819: if (!$symb) {
4820: $symb=&symbread();
1.620 albertel 4821: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4822: }
4823: $symb=escape($symb);
4824:
1.620 albertel 4825: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4826:
1.620 albertel 4827: if (!$domain) { $domain=$env{'user.domain'}; }
4828: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4829: if ($domain eq 'public' && $stuname eq 'public') {
4830: $stuname=$ENV{'REMOTE_ADDR'};
4831: }
1.168 albertel 4832: my %returnhash;
4833: $namespace=~s/\//\_/g;
4834: $namespace=~s/\W//g;
4835: my %hash;
1.1117 foxr 4836: my $path=LONCAPA::tempdir();
1.168 albertel 4837: if (tie(%hash,'GDBM_File',
4838: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4839: &GDBM_READER(),0640)) {
1.168 albertel 4840: my $version=$hash{"version:$symb"};
4841: $returnhash{'version'}=$version;
4842: my $scope;
4843: for ($scope=1;$scope<=$version;$scope++) {
4844: my $vkeys=$hash{"$scope:keys:$symb"};
4845: my @keys=split(/:/,$vkeys);
4846: my $key;
4847: $returnhash{"$scope:keys"}=$vkeys;
4848: foreach $key (@keys) {
1.591 albertel 4849: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4850: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4851: }
4852: }
1.168 albertel 4853: if (!(untie(%hash))) {
4854: return "error:$!";
4855: }
4856: } else {
4857: return "error:$!";
4858: }
4859: return %returnhash;
1.167 albertel 4860: }
4861:
1.9 www 4862: # ----------------------------------------------------------------------- Store
4863:
4864: sub store {
1.124 www 4865: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4866: my $home='';
4867:
1.168 albertel 4868: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4869:
1.213 www 4870: $symb=&symbclean($symb);
1.122 albertel 4871: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4872:
1.620 albertel 4873: if (!$domain) { $domain=$env{'user.domain'}; }
4874: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4875:
4876: &devalidate($symb,$stuname,$domain);
1.109 www 4877:
4878: $symb=escape($symb);
1.187 www 4879: if (!$namespace) {
1.620 albertel 4880: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4881: return '';
4882: }
4883: }
1.620 albertel 4884: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4885:
4886: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4887: $$storehash{'host'}=$perlvar{'lonHostID'};
4888:
1.12 www 4889: my $namevalue='';
1.800 albertel 4890: foreach my $key (keys(%$storehash)) {
4891: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4892: }
1.12 www 4893: $namevalue=~s/\&$//;
1.187 www 4894: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4895: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4896: }
4897:
1.47 www 4898: # -------------------------------------------------------------- Critical Store
4899:
4900: sub cstore {
1.124 www 4901: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4902: my $home='';
4903:
1.168 albertel 4904: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4905:
1.213 www 4906: $symb=&symbclean($symb);
1.122 albertel 4907: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4908:
1.620 albertel 4909: if (!$domain) { $domain=$env{'user.domain'}; }
4910: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4911:
4912: &devalidate($symb,$stuname,$domain);
1.109 www 4913:
4914: $symb=escape($symb);
1.187 www 4915: if (!$namespace) {
1.620 albertel 4916: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4917: return '';
4918: }
4919: }
1.620 albertel 4920: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4921:
4922: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4923: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4924:
1.47 www 4925: my $namevalue='';
1.800 albertel 4926: foreach my $key (keys(%$storehash)) {
4927: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4928: }
1.47 www 4929: $namevalue=~s/\&$//;
1.187 www 4930: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4931: return critical
4932: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4933: }
4934:
1.9 www 4935: # --------------------------------------------------------------------- Restore
4936:
4937: sub restore {
1.124 www 4938: my ($symb,$namespace,$domain,$stuname) = @_;
4939: my $home='';
4940:
1.168 albertel 4941: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4942:
1.122 albertel 4943: if (!$symb) {
1.1172.2.26 raeburn 4944: return if ($namespace eq 'courserequests');
4945: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4946: } else {
1.1172.2.26 raeburn 4947: unless ($namespace eq 'courserequests') {
4948: $symb=&escape(&symbclean($symb));
4949: }
1.122 albertel 4950: }
1.188 www 4951: if (!$namespace) {
1.620 albertel 4952: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4953: return '';
4954: }
4955: }
1.620 albertel 4956: if (!$domain) { $domain=$env{'user.domain'}; }
4957: if (!$stuname) { $stuname=$env{'user.name'}; }
4958: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4959: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4960:
1.12 www 4961: my %returnhash=();
1.800 albertel 4962: foreach my $line (split(/\&/,$answer)) {
4963: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4964: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4965: }
1.75 www 4966: my $version;
4967: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4968: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4969: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4970: }
1.75 www 4971: }
1.13 www 4972: return %returnhash;
1.34 www 4973: }
4974:
4975: # ---------------------------------------------------------- Course Description
1.1118 foxr 4976: #
4977: #
1.34 www 4978:
4979: sub coursedescription {
1.731 albertel 4980: my ($courseid,$args)=@_;
1.34 www 4981: $courseid=~s/^\///;
1.49 www 4982: $courseid=~s/\_/\//g;
1.34 www 4983: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4984: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4985: my $normalid=$cdomain.'_'.$cnum;
4986: # need to always cache even if we get errors otherwise we keep
4987: # trying and trying and trying to get the course description.
4988: my %envhash=();
4989: my %returnhash=();
1.731 albertel 4990:
4991: my $expiretime=600;
4992: if ($env{'request.course.id'} eq $normalid) {
4993: $expiretime=120;
4994: }
4995:
4996: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4997: if (!$args->{'freshen_cache'}
4998: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4999: foreach my $key (keys(%env)) {
5000: next if ($key !~ /^\Q$prefix\E(.*)/);
5001: my ($setting) = $1;
5002: $returnhash{$setting} = $env{$key};
5003: }
5004: return %returnhash;
5005: }
5006:
1.1118 foxr 5007: # get the data again
5008:
1.731 albertel 5009: if (!$args->{'one_time'}) {
5010: $envhash{'course.'.$normalid.'.last_cache'}=time;
5011: }
1.811 albertel 5012:
1.34 www 5013: if ($chome ne 'no_host') {
1.302 albertel 5014: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5015: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5016: my $username = $env{'user.name'}; # Defult username
5017: if(defined $args->{'user'}) {
5018: $username = $args->{'user'};
5019: }
1.129 albertel 5020: $returnhash{'home'}= $chome;
5021: $returnhash{'domain'} = $cdomain;
5022: $returnhash{'num'} = $cnum;
1.741 raeburn 5023: if (!defined($returnhash{'type'})) {
5024: $returnhash{'type'} = 'Course';
5025: }
1.130 albertel 5026: while (my ($name,$value) = each %returnhash) {
1.53 www 5027: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5028: }
1.270 www 5029: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5030: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5031: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5032: $envhash{'course.'.$normalid.'.home'}=$chome;
5033: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5034: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5035: }
5036: }
1.731 albertel 5037: if (!$args->{'one_time'}) {
1.949 raeburn 5038: &appenv(\%envhash);
1.731 albertel 5039: }
1.302 albertel 5040: return %returnhash;
1.461 www 5041: }
5042:
1.1080 raeburn 5043: sub update_released_required {
5044: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5045: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5046: $cid = $env{'request.course.id'};
5047: $cdom = $env{'course.'.$cid.'.domain'};
5048: $cnum = $env{'course.'.$cid.'.num'};
5049: $chome = $env{'course.'.$cid.'.home'};
5050: }
5051: if ($needsrelease) {
5052: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5053: my $needsupdate;
5054: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5055: $needsupdate = 1;
5056: } else {
5057: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5058: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5059: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5060: $needsupdate = 1;
5061: }
5062: }
5063: if ($needsupdate) {
5064: my %needshash = (
5065: 'internal.releaserequired' => $needsrelease,
5066: );
5067: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5068: if ($putresult eq 'ok') {
5069: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5070: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5071: if (ref($crsinfo{$cid}) eq 'HASH') {
5072: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5073: &courseidput($cdom,\%crsinfo,$chome,'notime');
5074: }
5075: }
5076: }
5077: }
5078: return;
5079: }
5080:
1.461 www 5081: # -------------------------------------------------See if a user is privileged
5082:
5083: sub privileged {
1.1172.2.23 raeburn 5084: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5085: my $now = time;
1.1172.2.23 raeburn 5086: my $roles;
5087: if (ref($possroles) eq 'ARRAY') {
5088: $roles = $possroles;
5089: } else {
5090: $roles = ['dc','su'];
5091: }
5092: if (ref($possdomains) eq 'ARRAY') {
5093: my %privileged = &privileged_by_domain($possdomains,$roles);
5094: foreach my $dom (@{$possdomains}) {
5095: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5096: (ref($privileged{$dom}) eq 'HASH')) {
5097: foreach my $role (@{$roles}) {
5098: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5099: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5100: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5101: return 1 unless (($end && $end < $now) ||
5102: ($start && $start > $now));
5103: }
5104: }
5105: }
5106: }
5107: }
5108: } else {
5109: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5110: my $now = time;
1.1170 droeschl 5111:
1.1172.2.23 raeburn 5112: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5113: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5114: if (grep(/^\Q$trole\E$/,@{$roles})) {
5115: return 1 unless ($tend && $tend < $now)
5116: or ($tstart && $tstart > $now);
1.1170 droeschl 5117: }
1.1172.2.23 raeburn 5118: }
5119: }
1.461 www 5120: return 0;
1.9 www 5121: }
1.1 albertel 5122:
1.1172.2.23 raeburn 5123: sub privileged_by_domain {
5124: my ($domains,$roles) = @_;
5125: my %privileged = ();
5126: my $cachetime = 60*60*24;
5127: my $now = time;
5128: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5129: return %privileged;
5130: }
5131: foreach my $dom (@{$domains}) {
5132: next if (ref($privileged{$dom}) eq 'HASH');
5133: my $needroles;
5134: foreach my $role (@{$roles}) {
5135: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5136: if (defined($cached)) {
5137: if (ref($result) eq 'HASH') {
5138: $privileged{$dom}{$role} = $result;
5139: }
5140: } else {
5141: $needroles = 1;
5142: }
5143: }
5144: if ($needroles) {
5145: my %dompersonnel = &get_domain_roles($dom,$roles);
5146: $privileged{$dom} = {};
5147: foreach my $server (keys(%dompersonnel)) {
5148: if (ref($dompersonnel{$server}) eq 'HASH') {
5149: foreach my $item (keys(%{$dompersonnel{$server}})) {
5150: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5151: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5152: next if ($end && $end < $now);
5153: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5154: $dompersonnel{$server}{$item};
5155: }
5156: }
5157: }
5158: if (ref($privileged{$dom}) eq 'HASH') {
5159: foreach my $role (@{$roles}) {
5160: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5161: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5162: } else {
5163: my %hash = ();
5164: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5165: }
5166: }
5167: }
5168: }
5169: }
5170: return %privileged;
5171: }
5172:
1.103 harris41 5173: # -------------------------------------------------------- Get user privileges
1.11 www 5174:
5175: sub rolesinit {
1.1169 droeschl 5176: my ($domain, $username) = @_;
5177: my %userroles = ('user.login.time' => time);
5178: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5179:
5180: # firstaccess and timerinterval are related to timed maps/resources.
5181: # also, blocking can be triggered by an activating timer
5182: # it's saved in the user's %env.
5183: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5184: my %timerinterval = &dump('timerinterval', $domain, $username);
5185: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5186: %timerintchk, %timerintenv);
5187:
1.1162 raeburn 5188: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5189: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5190: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5191: }
1.1169 droeschl 5192:
1.1162 raeburn 5193: foreach my $key (keys(%timerinterval)) {
5194: my ($cid,$rest) = split(/\0/,$key);
5195: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5196: }
1.1169 droeschl 5197:
1.11 www 5198: my %allroles=();
1.1162 raeburn 5199: my %allgroups=();
1.11 www 5200:
1.1169 droeschl 5201: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5202: my $role = $rolesdump{$area};
5203: $area =~ s/\_\w\w$//;
5204:
5205: my ($trole, $tend, $tstart, $group_privs);
5206:
5207: if ($role =~ /^cr/) {
5208: # Custom role, defined by a user
5209: # e.g., user.role.cr/msu/smith/mynewrole
5210: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5211: $trole = $1;
5212: ($tend, $tstart) = split('_', $2);
5213: } else {
5214: $trole = $role;
5215: }
5216: } elsif ($role =~ m|^gr/|) {
5217: # Role of member in a group, defined within a course/community
5218: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5219: ($trole, $tend, $tstart) = split(/_/, $role);
5220: next if $tstart eq '-1';
5221: ($trole, $group_privs) = split(/\//, $trole);
5222: $group_privs = &unescape($group_privs);
5223: } else {
5224: # Just a normal role, defined in roles.tab
5225: ($trole, $tend, $tstart) = split(/_/,$role);
5226: }
5227:
5228: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5229: $username);
5230: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5231:
5232: # role expired or not available yet?
5233: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5234: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5235:
5236: next if $area eq '' or $trole eq '';
5237:
5238: my $spec = "$trole.$area";
5239: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5240:
5241: if ($trole =~ /^cr\//) {
5242: # Custom role, defined by a user
5243: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5244: } elsif ($trole eq 'gr') {
5245: # Role of a member in a group, defined within a course/community
5246: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5247: next;
5248: } else {
5249: # Normal role, defined in roles.tab
5250: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5251: }
5252:
5253: my $cid = $tdomain.'_'.$trest;
5254: unless ($firstaccchk{$cid}) {
5255: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5256: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5257: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5258: $coursetimerstarts{$cid}{$item};
5259: }
5260: }
5261: $firstaccchk{$cid} = 1;
5262: }
5263: unless ($timerintchk{$cid}) {
5264: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5265: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5266: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5267: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5268: }
1.12 www 5269: }
1.1169 droeschl 5270: $timerintchk{$cid} = 1;
1.191 harris41 5271: }
1.11 www 5272: }
1.1169 droeschl 5273:
5274: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5275: \%allroles, \%allgroups);
5276: $env{'user.adv'} = $userroles{'user.adv'};
5277:
1.1162 raeburn 5278: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5279: }
5280:
1.567 raeburn 5281: sub set_arearole {
1.1172.2.19 raeburn 5282: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5283: unless ($nolog) {
1.567 raeburn 5284: # log the associated role with the area
1.1172.2.19 raeburn 5285: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5286: }
1.743 albertel 5287: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5288: }
5289:
5290: sub custom_roleprivs {
5291: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5292: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5293: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5294: if (&hostname($homsvr) ne '') {
1.567 raeburn 5295: my ($rdummy,$roledef)=
5296: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5297: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5298: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5299: if (defined($syspriv)) {
1.1043 raeburn 5300: if ($trest =~ /^$match_community$/) {
5301: $syspriv =~ s/bre\&S//;
5302: }
1.567 raeburn 5303: $$allroles{'cm./'}.=':'.$syspriv;
5304: $$allroles{$spec.'./'}.=':'.$syspriv;
5305: }
5306: if ($tdomain ne '') {
5307: if (defined($dompriv)) {
5308: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5309: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5310: }
5311: if (($trest ne '') && (defined($coursepriv))) {
5312: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5313: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5314: }
5315: }
5316: }
5317: }
5318: }
5319:
1.678 raeburn 5320: sub group_roleprivs {
5321: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5322: my $access = 1;
5323: my $now = time;
5324: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5325: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5326: if ($access) {
1.811 albertel 5327: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5328: $$allgroups{$course}{$group} .=':'.$group_privs;
5329: }
5330: }
1.567 raeburn 5331:
5332: sub standard_roleprivs {
5333: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5334: if (defined($pr{$trole.':s'})) {
5335: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5336: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5337: }
5338: if ($tdomain ne '') {
5339: if (defined($pr{$trole.':d'})) {
5340: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5341: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5342: }
5343: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5344: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5345: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5346: }
5347: }
5348: }
5349:
5350: sub set_userprivs {
1.1064 raeburn 5351: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5352: my $author=0;
5353: my $adv=0;
1.678 raeburn 5354: my %grouproles = ();
5355: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5356: my @groupkeys;
1.1000 raeburn 5357: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5358: push(@groupkeys,$role);
5359: }
5360: if (ref($groups_roles) eq 'HASH') {
5361: foreach my $key (keys(%{$groups_roles})) {
5362: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5363: push(@groupkeys,$key);
5364: }
5365: }
5366: }
5367: if (@groupkeys > 0) {
5368: foreach my $role (@groupkeys) {
5369: my ($trole,$area,$sec,$extendedarea);
5370: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5371: $trole = $1;
5372: $area = $2;
5373: $sec = $3;
5374: $extendedarea = $area.$sec;
5375: if (exists($$allgroups{$area})) {
5376: foreach my $group (keys(%{$$allgroups{$area}})) {
5377: my $spec = $trole.'.'.$extendedarea;
5378: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5379: $$allgroups{$area}{$group};
1.1064 raeburn 5380: }
1.678 raeburn 5381: }
5382: }
5383: }
5384: }
5385: }
1.800 albertel 5386: foreach my $group (keys(%grouproles)) {
5387: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5388: }
1.800 albertel 5389: foreach my $role (keys(%{$allroles})) {
5390: my %thesepriv;
1.941 raeburn 5391: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5392: foreach my $item (split(/:/,$$allroles{$role})) {
5393: if ($item ne '') {
5394: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5395: if ($restrictions eq '') {
5396: $thesepriv{$privilege}='F';
5397: } elsif ($thesepriv{$privilege} ne 'F') {
5398: $thesepriv{$privilege}.=$restrictions;
5399: }
5400: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5401: }
5402: }
5403: my $thesestr='';
1.1104 raeburn 5404: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5405: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5406: }
5407: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5408: }
5409: return ($author,$adv);
5410: }
5411:
1.994 raeburn 5412: sub role_status {
1.1104 raeburn 5413: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5414: my @pwhere = ();
5415: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5416: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5417: unless (!defined($$role) || $$role eq '') {
5418: $$where=join('.',@pwhere);
5419: $$trolecode=$$role.'.'.$$where;
5420: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5421: $$tstatus='is';
1.1104 raeburn 5422: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5423: $$tstatus='future';
1.1034 raeburn 5424: if ($$tstart<$now) {
5425: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5426: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5427: my (%allroles,%allgroups,$group_privs,
5428: %groups_roles,@rolecodes);
1.1002 raeburn 5429: my %userroles = (
5430: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5431: );
1.1064 raeburn 5432: @rolecodes = ('cm');
1.1002 raeburn 5433: my $spec=$$role.'.'.$$where;
5434: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5435: if ($$role =~ /^cr\//) {
5436: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5437: push(@rolecodes,'cr');
1.1002 raeburn 5438: } elsif ($$role eq 'gr') {
1.1064 raeburn 5439: push(@rolecodes,$$role);
1.1002 raeburn 5440: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5441: $env{'user.name'});
1.1064 raeburn 5442: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5443: (undef,my $group_privs) = split(/\//,$trole);
5444: $group_privs = &unescape($group_privs);
5445: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5446: 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 5447: &get_groups_roles($tdomain,$trest,
5448: \%course_roles,\@rolecodes,
5449: \%groups_roles);
1.1002 raeburn 5450: } else {
1.1064 raeburn 5451: push(@rolecodes,$$role);
1.1002 raeburn 5452: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5453: }
1.1064 raeburn 5454: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5455: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5456: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5457: }
5458: }
1.1034 raeburn 5459: $$tstatus = 'is';
1.1002 raeburn 5460: }
1.994 raeburn 5461: }
5462: if ($$tend) {
1.1104 raeburn 5463: if ($$tend<$update) {
1.994 raeburn 5464: $$tstatus='expired';
5465: } elsif ($$tend<$now) {
5466: $$tstatus='will_not';
5467: }
5468: }
5469: }
5470: }
5471: }
5472:
1.1104 raeburn 5473: sub get_groups_roles {
5474: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5475: return unless((ref($cdom_courseroles) eq 'HASH') &&
5476: (ref($rolecodes) eq 'ARRAY') &&
5477: (ref($groups_roles) eq 'HASH'));
5478: if (keys(%{$cdom_courseroles}) > 0) {
5479: my ($cnum) = ($rest =~ /^($match_courseid)/);
5480: if ($cdom ne '' && $cnum ne '') {
5481: foreach my $key (keys(%{$cdom_courseroles})) {
5482: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5483: my $crsrole = $1;
5484: my $crssec = $2;
5485: if ($crsrole =~ /^cr/) {
5486: unless (grep(/^cr$/,@{$rolecodes})) {
5487: push(@{$rolecodes},'cr');
5488: }
5489: } else {
5490: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5491: push(@{$rolecodes},$crsrole);
5492: }
5493: }
5494: my $rolekey = "$crsrole./$cdom/$cnum";
5495: if ($crssec ne '') {
5496: $rolekey .= "/$crssec";
5497: }
5498: $rolekey .= './';
5499: $groups_roles->{$rolekey} = $rolecodes;
5500: }
5501: }
5502: }
5503: }
5504: return;
5505: }
5506:
5507: sub delete_env_groupprivs {
5508: my ($where,$courseroles,$possroles) = @_;
5509: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5510: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5511: unless (ref($courseroles->{$udom}) eq 'HASH') {
5512: %{$courseroles->{$udom}} =
5513: &get_my_roles('','','userroles',['active'],
5514: $possroles,[$udom],1);
5515: }
5516: if (ref($courseroles->{$udom}) eq 'HASH') {
5517: foreach my $item (keys(%{$courseroles->{$udom}})) {
5518: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5519: my $area = '/'.$cdom.'/'.$cnum;
5520: my $privkey = "user.priv.$crsrole.$area";
5521: if ($crssec ne '') {
5522: $privkey .= '/'.$crssec;
5523: }
5524: $privkey .= ".$area/$group";
5525: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5526: }
5527: }
5528: return;
5529: }
5530:
1.994 raeburn 5531: sub check_adhoc_privs {
1.1104 raeburn 5532: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5533: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5534: my $setprivs;
1.994 raeburn 5535: if ($env{$cckey}) {
5536: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5537: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5538: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5539: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5540: $setprivs = 1;
1.994 raeburn 5541: }
5542: } else {
1.1088 raeburn 5543: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5544: $setprivs = 1;
1.994 raeburn 5545: }
1.1172.2.9 raeburn 5546: return $setprivs;
1.994 raeburn 5547: }
5548:
5549: sub set_adhoc_privileges {
5550: # role can be cc or ca
1.1088 raeburn 5551: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5552: my $area = '/'.$dcdom.'/'.$pickedcourse;
5553: my $spec = $role.'.'.$area;
5554: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5555: $env{'user.name'},1);
1.994 raeburn 5556: my %ccrole = ();
5557: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5558: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5559: &appenv(\%userroles,[$role,'cm']);
5560: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5561: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5562: &appenv( {'request.role' => $spec,
5563: 'request.role.domain' => $dcdom,
5564: 'request.course.sec' => ''
5565: }
5566: );
5567: my $tadv=0;
5568: if (&allowed('adv') eq 'F') { $tadv=1; }
5569: &appenv({'request.role.adv' => $tadv});
5570: }
1.994 raeburn 5571: }
5572:
1.12 www 5573: # --------------------------------------------------------------- get interface
5574:
5575: sub get {
1.131 albertel 5576: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5577: my $items='';
1.800 albertel 5578: foreach my $item (@$storearr) {
5579: $items.=&escape($item).'&';
1.191 harris41 5580: }
1.12 www 5581: $items=~s/\&$//;
1.620 albertel 5582: if (!$udomain) { $udomain=$env{'user.domain'}; }
5583: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5584: my $uhome=&homeserver($uname,$udomain);
5585:
1.133 albertel 5586: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5587: my @pairs=split(/\&/,$rep);
1.273 albertel 5588: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5589: return @pairs;
5590: }
1.15 www 5591: my %returnhash=();
1.42 www 5592: my $i=0;
1.800 albertel 5593: foreach my $item (@$storearr) {
5594: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5595: $i++;
1.191 harris41 5596: }
1.15 www 5597: return %returnhash;
1.27 www 5598: }
5599:
5600: # --------------------------------------------------------------- del interface
5601:
5602: sub del {
1.133 albertel 5603: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5604: my $items='';
1.800 albertel 5605: foreach my $item (@$storearr) {
5606: $items.=&escape($item).'&';
1.191 harris41 5607: }
1.984 neumanie 5608:
1.27 www 5609: $items=~s/\&$//;
1.620 albertel 5610: if (!$udomain) { $udomain=$env{'user.domain'}; }
5611: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5612: my $uhome=&homeserver($uname,$udomain);
5613: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5614: }
5615:
5616: # -------------------------------------------------------------- dump interface
5617:
1.1172.2.22 raeburn 5618: sub unserialize {
5619: my ($rep, $escapedkeys) = @_;
5620:
5621: return {} if $rep =~ /^error/;
5622:
5623: my %returnhash=();
5624: foreach my $item (split(/\&/,$rep)) {
5625: my ($key, $value) = split(/=/, $item, 2);
5626: $key = unescape($key) unless $escapedkeys;
5627: next if $key =~ /^error: 2 /;
5628: $returnhash{$key} = &thaw_unescape($value);
5629: }
5630: return \%returnhash;
5631: }
5632:
5633: # see Lond::dump_with_regexp
5634: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5635: sub dump {
1.1172.2.22 raeburn 5636: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5637: if (!$udomain) { $udomain=$env{'user.domain'}; }
5638: if (!$uname) { $uname=$env{'user.name'}; }
5639: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5640:
1.1172.2.22 raeburn 5641: my $reply;
5642: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5643: # user is hosted on this machine
5644: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5645: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5646: return %{&unserialize($reply, $escapedkeys)};
5647: }
1.755 albertel 5648: if ($regexp) {
5649: $regexp=&escape($regexp);
5650: } else {
5651: $regexp='.';
5652: }
1.1166 raeburn 5653: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5654: my @pairs=split(/\&/,$rep);
5655: my %returnhash=();
1.1098 foxr 5656: if (!($rep =~ /^error/ )) {
5657: foreach my $item (@pairs) {
5658: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5659: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5660: next if ($key =~ /^error: 2 /);
5661: $returnhash{$key}=&thaw_unescape($value);
5662: }
1.755 albertel 5663: }
5664: return %returnhash;
1.407 www 5665: }
5666:
1.1098 foxr 5667:
1.717 albertel 5668: # --------------------------------------------------------- dumpstore interface
5669:
5670: sub dumpstore {
5671: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5672: # same as dump but keys must be escaped. They may contain colon separated
5673: # lists of values that may themself contain colons (e.g. symbs).
5674: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5675: }
5676:
1.407 www 5677: # -------------------------------------------------------------- keys interface
5678:
5679: sub getkeys {
5680: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5681: if (!$udomain) { $udomain=$env{'user.domain'}; }
5682: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5683: my $uhome=&homeserver($uname,$udomain);
5684: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5685: my @keyarray=();
1.800 albertel 5686: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5687: next if ($key =~ /^error: 2 /);
1.800 albertel 5688: push(@keyarray,&unescape($key));
1.407 www 5689: }
5690: return @keyarray;
1.318 matthew 5691: }
5692:
1.319 matthew 5693: # --------------------------------------------------------------- currentdump
5694: sub currentdump {
1.328 matthew 5695: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5696: $courseid = $env{'request.course.id'} if (! defined($courseid));
5697: $sdom = $env{'user.domain'} if (! defined($sdom));
5698: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5699: my $uhome = &homeserver($sname,$sdom);
5700: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5701: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5702: #
1.318 matthew 5703: my %returnhash=();
1.319 matthew 5704: #
5705: if ($rep eq "unknown_cmd") {
5706: # an old lond will not know currentdump
5707: # Do a dump and make it look like a currentdump
1.822 albertel 5708: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5709: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5710: my %hash = @tmp;
5711: @tmp=();
1.424 matthew 5712: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5713: } else {
5714: my @pairs=split(/\&/,$rep);
1.800 albertel 5715: foreach my $pair (@pairs) {
5716: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5717: my ($symb,$param) = split(/:/,$key);
5718: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5719: &thaw_unescape($value);
1.319 matthew 5720: }
1.191 harris41 5721: }
1.12 www 5722: return %returnhash;
1.424 matthew 5723: }
5724:
5725: sub convert_dump_to_currentdump{
5726: my %hash = %{shift()};
5727: my %returnhash;
5728: # Code ripped from lond, essentially. The only difference
5729: # here is the unescaping done by lonnet::dump(). Conceivably
5730: # we might run in to problems with parameter names =~ /^v\./
5731: while (my ($key,$value) = each(%hash)) {
5732: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5733: $symb = &unescape($symb);
5734: $param = &unescape($param);
1.424 matthew 5735: next if ($v eq 'version' || $symb eq 'keys');
5736: next if (exists($returnhash{$symb}) &&
5737: exists($returnhash{$symb}->{$param}) &&
5738: $returnhash{$symb}->{'v.'.$param} > $v);
5739: $returnhash{$symb}->{$param}=$value;
5740: $returnhash{$symb}->{'v.'.$param}=$v;
5741: }
5742: #
5743: # Remove all of the keys in the hashes which keep track of
5744: # the version of the parameter.
5745: while (my ($symb,$param_hash) = each(%returnhash)) {
5746: # use a foreach because we are going to delete from the hash.
5747: foreach my $key (keys(%$param_hash)) {
5748: delete($param_hash->{$key}) if ($key =~ /^v\./);
5749: }
5750: }
5751: return \%returnhash;
1.12 www 5752: }
5753:
1.627 albertel 5754: # ------------------------------------------------------ critical inc interface
5755:
5756: sub cinc {
5757: return &inc(@_,'critical');
5758: }
5759:
1.449 matthew 5760: # --------------------------------------------------------------- inc interface
5761:
5762: sub inc {
1.627 albertel 5763: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5764: if (!$udomain) { $udomain=$env{'user.domain'}; }
5765: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5766: my $uhome=&homeserver($uname,$udomain);
5767: my $items='';
5768: if (! ref($store)) {
5769: # got a single value, so use that instead
5770: $items = &escape($store).'=&';
5771: } elsif (ref($store) eq 'SCALAR') {
5772: $items = &escape($$store).'=&';
5773: } elsif (ref($store) eq 'ARRAY') {
5774: $items = join('=&',map {&escape($_);} @{$store});
5775: } elsif (ref($store) eq 'HASH') {
5776: while (my($key,$value) = each(%{$store})) {
5777: $items.= &escape($key).'='.&escape($value).'&';
5778: }
5779: }
5780: $items=~s/\&$//;
1.627 albertel 5781: if ($critical) {
5782: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5783: } else {
5784: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5785: }
1.449 matthew 5786: }
5787:
1.12 www 5788: # --------------------------------------------------------------- put interface
5789:
5790: sub put {
1.134 albertel 5791: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5792: if (!$udomain) { $udomain=$env{'user.domain'}; }
5793: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5794: my $uhome=&homeserver($uname,$udomain);
1.12 www 5795: my $items='';
1.800 albertel 5796: foreach my $item (keys(%$storehash)) {
5797: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5798: }
1.12 www 5799: $items=~s/\&$//;
1.134 albertel 5800: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5801: }
5802:
1.631 albertel 5803: # ------------------------------------------------------------ newput interface
5804:
5805: sub newput {
5806: my ($namespace,$storehash,$udomain,$uname)=@_;
5807: if (!$udomain) { $udomain=$env{'user.domain'}; }
5808: if (!$uname) { $uname=$env{'user.name'}; }
5809: my $uhome=&homeserver($uname,$udomain);
5810: my $items='';
5811: foreach my $key (keys(%$storehash)) {
5812: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5813: }
5814: $items=~s/\&$//;
5815: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5816: }
5817:
5818: # --------------------------------------------------------- putstore interface
5819:
1.524 raeburn 5820: sub putstore {
1.715 albertel 5821: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5822: if (!$udomain) { $udomain=$env{'user.domain'}; }
5823: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5824: my $uhome=&homeserver($uname,$udomain);
5825: my $items='';
1.715 albertel 5826: foreach my $key (keys(%$storehash)) {
5827: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5828: }
1.715 albertel 5829: $items=~s/\&$//;
1.716 albertel 5830: my $esc_symb=&escape($symb);
5831: my $esc_v=&escape($version);
1.715 albertel 5832: my $reply =
1.716 albertel 5833: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5834: $uhome);
5835: if ($reply eq 'unknown_cmd') {
1.716 albertel 5836: # gfall back to way things use to be done
1.715 albertel 5837: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5838: $uname);
1.524 raeburn 5839: }
1.715 albertel 5840: return $reply;
5841: }
5842:
5843: sub old_putstore {
1.716 albertel 5844: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5845: if (!$udomain) { $udomain=$env{'user.domain'}; }
5846: if (!$uname) { $uname=$env{'user.name'}; }
5847: my $uhome=&homeserver($uname,$udomain);
5848: my %newstorehash;
1.800 albertel 5849: foreach my $item (keys(%$storehash)) {
5850: my $key = $version.':'.&escape($symb).':'.$item;
5851: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5852: }
5853: my $items='';
5854: my %allitems = ();
1.800 albertel 5855: foreach my $item (keys(%newstorehash)) {
5856: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5857: my $key = $1.':keys:'.$2;
5858: $allitems{$key} .= $3.':';
5859: }
1.800 albertel 5860: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5861: }
1.800 albertel 5862: foreach my $item (keys(%allitems)) {
5863: $allitems{$item} =~ s/\:$//;
5864: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5865: }
5866: $items=~s/\&$//;
5867: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5868: }
5869:
1.47 www 5870: # ------------------------------------------------------ critical put interface
5871:
5872: sub cput {
1.134 albertel 5873: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5874: if (!$udomain) { $udomain=$env{'user.domain'}; }
5875: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5876: my $uhome=&homeserver($uname,$udomain);
1.47 www 5877: my $items='';
1.800 albertel 5878: foreach my $item (keys(%$storehash)) {
5879: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5880: }
1.47 www 5881: $items=~s/\&$//;
1.134 albertel 5882: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5883: }
5884:
5885: # -------------------------------------------------------------- eget interface
5886:
5887: sub eget {
1.133 albertel 5888: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5889: my $items='';
1.800 albertel 5890: foreach my $item (@$storearr) {
5891: $items.=&escape($item).'&';
1.191 harris41 5892: }
1.12 www 5893: $items=~s/\&$//;
1.620 albertel 5894: if (!$udomain) { $udomain=$env{'user.domain'}; }
5895: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5896: my $uhome=&homeserver($uname,$udomain);
5897: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5898: my @pairs=split(/\&/,$rep);
5899: my %returnhash=();
1.42 www 5900: my $i=0;
1.800 albertel 5901: foreach my $item (@$storearr) {
5902: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5903: $i++;
1.191 harris41 5904: }
1.12 www 5905: return %returnhash;
5906: }
5907:
1.667 albertel 5908: # ------------------------------------------------------------ tmpput interface
5909: sub tmpput {
1.802 raeburn 5910: my ($storehash,$server,$context)=@_;
1.667 albertel 5911: my $items='';
1.800 albertel 5912: foreach my $item (keys(%$storehash)) {
5913: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5914: }
5915: $items=~s/\&$//;
1.802 raeburn 5916: if (defined($context)) {
5917: $items .= ':'.&escape($context);
5918: }
1.667 albertel 5919: return &reply("tmpput:$items",$server);
5920: }
5921:
5922: # ------------------------------------------------------------ tmpget interface
5923: sub tmpget {
1.688 albertel 5924: my ($token,$server)=@_;
5925: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5926: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5927: my %returnhash;
5928: foreach my $item (split(/\&/,$rep)) {
5929: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5930: next if ($key =~ /^error: 2 /);
1.667 albertel 5931: $returnhash{&unescape($key)}=&thaw_unescape($value);
5932: }
5933: return %returnhash;
5934: }
5935:
1.1113 raeburn 5936: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5937: sub tmpdel {
5938: my ($token,$server)=@_;
5939: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5940: return &reply("tmpdel:$token",$server);
5941: }
5942:
1.1172.2.13 raeburn 5943: # ------------------------------------------------------------ get_timebased_id
5944:
5945: sub get_timebased_id {
5946: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5947: $maxtries) = @_;
5948: my ($newid,$error,$dellock);
5949: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5950: return ('','ok','invalid call to get suffix');
5951: }
5952:
5953: # set defaults for any optional args for which values were not supplied
5954: if ($who eq '') {
5955: $who = $env{'user.name'}.':'.$env{'user.domain'};
5956: }
5957: if (!$locktries) {
5958: $locktries = 3;
5959: }
5960: if (!$maxtries) {
5961: $maxtries = 10;
5962: }
5963:
5964: if (($cdom eq '') || ($cnum eq '')) {
5965: if ($env{'request.course.id'}) {
5966: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5967: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5968: }
5969: if (($cdom eq '') || ($cnum eq '')) {
5970: return ('','ok','call to get suffix not in course context');
5971: }
5972: }
5973:
5974: # construct locking item
5975: my $lockhash = {
5976: $prefix."\0".'locked_'.$keyid => $who,
5977: };
5978: my $tries = 0;
5979:
5980: # attempt to get lock on nohist_$namespace file
5981: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5982: while (($gotlock ne 'ok') && $tries <$locktries) {
5983: $tries ++;
5984: sleep 1;
5985: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5986: }
5987:
5988: # attempt to get unique identifier, based on current timestamp
5989: if ($gotlock eq 'ok') {
5990: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5991: my $id = time;
5992: $newid = $id;
5993: my $idtries = 0;
5994: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5995: if ($idtype eq 'concat') {
5996: $newid = $id.$idtries;
5997: } else {
5998: $newid ++;
5999: }
6000: $idtries ++;
6001: }
6002: if (!exists($inuse{$prefix."\0".$newid})) {
6003: my %new_item = (
6004: $prefix."\0".$newid => $who,
6005: );
6006: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6007: $cdom,$cnum);
6008: if ($putresult ne 'ok') {
6009: undef($newid);
6010: $error = 'error saving new item: '.$putresult;
6011: }
6012: } else {
6013: $error = ('error: no unique suffix available for the new item ');
6014: }
6015: # remove lock
6016: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6017: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6018: } else {
6019: $error = "error: could not obtain lockfile\n";
6020: $dellock = 'ok';
6021: }
6022: return ($newid,$dellock,$error);
6023: }
6024:
1.765 albertel 6025: # -------------------------------------------------- portfolio access checking
6026:
6027: sub portfolio_access {
1.766 albertel 6028: my ($requrl) = @_;
1.765 albertel 6029: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6030: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6031: if ($result) {
6032: my %setters;
6033: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6034: my ($startblock,$endblock) =
6035: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6036: if ($startblock && $endblock) {
6037: return 'B';
6038: }
6039: } else {
6040: my ($startblock,$endblock) =
6041: &Apache::loncommon::blockcheck(\%setters,'port');
6042: if ($startblock && $endblock) {
6043: return 'B';
6044: }
6045: }
6046: }
1.765 albertel 6047: if ($result eq 'ok') {
1.766 albertel 6048: return 'F';
1.765 albertel 6049: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6050: return 'A';
1.765 albertel 6051: }
1.766 albertel 6052: return '';
1.765 albertel 6053: }
6054:
6055: sub get_portfolio_access {
1.767 albertel 6056: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6057:
6058: if (!ref($access_hash)) {
6059: my $current_perms = &get_portfile_permissions($udom,$unum);
6060: my %access_controls = &get_access_controls($current_perms,$group,
6061: $file_name);
6062: $access_hash = $access_controls{$file_name};
6063: }
6064:
1.765 albertel 6065: my ($public,$guest,@domains,@users,@courses,@groups);
6066: my $now = time;
6067: if (ref($access_hash) eq 'HASH') {
6068: foreach my $key (keys(%{$access_hash})) {
6069: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6070: if ($start > $now) {
6071: next;
6072: }
6073: if ($end && $end<$now) {
6074: next;
6075: }
6076: if ($scope eq 'public') {
6077: $public = $key;
6078: last;
6079: } elsif ($scope eq 'guest') {
6080: $guest = $key;
6081: } elsif ($scope eq 'domains') {
6082: push(@domains,$key);
6083: } elsif ($scope eq 'users') {
6084: push(@users,$key);
6085: } elsif ($scope eq 'course') {
6086: push(@courses,$key);
6087: } elsif ($scope eq 'group') {
6088: push(@groups,$key);
6089: }
6090: }
6091: if ($public) {
6092: return 'ok';
6093: }
6094: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6095: if ($guest) {
6096: return $guest;
6097: }
6098: } else {
6099: if (@domains > 0) {
6100: foreach my $domkey (@domains) {
6101: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6102: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6103: return 'ok';
6104: }
6105: }
6106: }
6107: }
6108: if (@users > 0) {
6109: foreach my $userkey (@users) {
1.865 raeburn 6110: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6111: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6112: if (ref($item) eq 'HASH') {
6113: if (($item->{'uname'} eq $env{'user.name'}) &&
6114: ($item->{'udom'} eq $env{'user.domain'})) {
6115: return 'ok';
6116: }
6117: }
6118: }
6119: }
1.765 albertel 6120: }
6121: }
6122: my %roleshash;
6123: my @courses_and_groups = @courses;
6124: push(@courses_and_groups,@groups);
6125: if (@courses_and_groups > 0) {
6126: my (%allgroups,%allroles);
6127: my ($start,$end,$role,$sec,$group);
6128: foreach my $envkey (%env) {
1.1060 raeburn 6129: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6130: my $cid = $2.'_'.$3;
6131: if ($1 eq 'gr') {
6132: $group = $4;
6133: $allgroups{$cid}{$group} = $env{$envkey};
6134: } else {
6135: if ($4 eq '') {
6136: $sec = 'none';
6137: } else {
6138: $sec = $4;
6139: }
6140: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6141: }
1.811 albertel 6142: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6143: my $cid = $2.'_'.$3;
6144: if ($4 eq '') {
6145: $sec = 'none';
6146: } else {
6147: $sec = $4;
6148: }
6149: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6150: }
6151: }
6152: if (keys(%allroles) == 0) {
6153: return;
6154: }
6155: foreach my $key (@courses_and_groups) {
6156: my %content = %{$$access_hash{$key}};
6157: my $cnum = $content{'number'};
6158: my $cdom = $content{'domain'};
6159: my $cid = $cdom.'_'.$cnum;
6160: if (!exists($allroles{$cid})) {
6161: next;
6162: }
6163: foreach my $role_id (keys(%{$content{'roles'}})) {
6164: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6165: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6166: my @status = @{$content{'roles'}{$role_id}{'access'}};
6167: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6168: foreach my $role (keys(%{$allroles{$cid}})) {
6169: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6170: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6171: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6172: if (grep/^all$/,@sections) {
6173: return 'ok';
6174: } else {
6175: if (grep/^$sec$/,@sections) {
6176: return 'ok';
6177: }
6178: }
6179: }
6180: }
6181: if (keys(%{$allgroups{$cid}}) == 0) {
6182: if (grep/^none$/,@groups) {
6183: return 'ok';
6184: }
6185: } else {
6186: if (grep/^all$/,@groups) {
6187: return 'ok';
6188: }
6189: foreach my $group (keys(%{$allgroups{$cid}})) {
6190: if (grep/^$group$/,@groups) {
6191: return 'ok';
6192: }
6193: }
6194: }
6195: }
6196: }
6197: }
6198: }
6199: }
6200: if ($guest) {
6201: return $guest;
6202: }
6203: }
6204: }
6205: return;
6206: }
6207:
6208: sub course_group_datechecker {
6209: my ($dates,$now,$status) = @_;
6210: my ($start,$end) = split(/\./,$dates);
6211: if (!$start && !$end) {
6212: return 'ok';
6213: }
6214: if (grep/^active$/,@{$status}) {
6215: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6216: return 'ok';
6217: }
6218: }
6219: if (grep/^previous$/,@{$status}) {
6220: if ($end > $now ) {
6221: return 'ok';
6222: }
6223: }
6224: if (grep/^future$/,@{$status}) {
6225: if ($start > $now) {
6226: return 'ok';
6227: }
6228: }
6229: return;
6230: }
6231:
6232: sub parse_portfolio_url {
6233: my ($url) = @_;
6234:
6235: my ($type,$udom,$unum,$group,$file_name);
6236:
1.823 albertel 6237: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6238: $type = 1;
6239: $udom = $1;
6240: $unum = $2;
6241: $file_name = $3;
1.823 albertel 6242: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6243: $type = 2;
6244: $udom = $1;
6245: $unum = $2;
6246: $group = $3;
6247: $file_name = $3.'/'.$4;
6248: }
6249: if (wantarray) {
6250: return ($type,$udom,$unum,$file_name,$group);
6251: }
6252: return $type;
6253: }
6254:
6255: sub is_portfolio_url {
6256: my ($url) = @_;
6257: return scalar(&parse_portfolio_url($url));
6258: }
6259:
1.798 raeburn 6260: sub is_portfolio_file {
6261: my ($file) = @_;
1.820 raeburn 6262: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6263: return 1;
6264: }
6265: return;
6266: }
6267:
1.976 raeburn 6268: sub usertools_access {
1.1084 raeburn 6269: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6270: my ($access,%tools);
6271: if ($context eq '') {
6272: $context = 'tools';
6273: }
6274: if ($context eq 'requestcourses') {
6275: %tools = (
6276: official => 1,
6277: unofficial => 1,
1.1006 raeburn 6278: community => 1,
1.1172.2.37! raeburn 6279: textbook => 1,
1.985 raeburn 6280: );
1.1172.2.9 raeburn 6281: } elsif ($context eq 'requestauthor') {
6282: %tools = (
6283: requestauthor => 1,
6284: );
1.985 raeburn 6285: } else {
6286: %tools = (
6287: aboutme => 1,
6288: blog => 1,
1.1172.2.6 raeburn 6289: webdav => 1,
1.985 raeburn 6290: portfolio => 1,
6291: );
6292: }
1.976 raeburn 6293: return if (!defined($tools{$tool}));
6294:
1.1172.2.35 raeburn 6295: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6296: $udom = $env{'user.domain'};
6297: $uname = $env{'user.name'};
6298: }
6299:
1.978 raeburn 6300: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6301: if ($action ne 'reload') {
1.985 raeburn 6302: if ($context eq 'requestcourses') {
6303: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6304: } elsif ($context eq 'requestauthor') {
6305: return $env{'environment.canrequest.author'};
1.985 raeburn 6306: } else {
6307: return $env{'environment.availabletools.'.$tool};
6308: }
6309: }
1.976 raeburn 6310: }
6311:
1.1172.2.9 raeburn 6312: my ($toolstatus,$inststatus,$envkey);
6313: if ($context eq 'requestauthor') {
6314: $envkey = $context;
6315: } else {
6316: $envkey = $context.'.'.$tool;
6317: }
1.976 raeburn 6318:
1.985 raeburn 6319: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6320: ($action ne 'reload')) {
1.1172.2.9 raeburn 6321: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6322: $inststatus = $env{'environment.inststatus'};
6323: } else {
1.1084 raeburn 6324: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6325: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6326: $inststatus = $userenvref->{'inststatus'};
6327: } else {
1.1172.2.9 raeburn 6328: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6329: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6330: $inststatus = $userenv{'inststatus'};
6331: }
1.976 raeburn 6332: }
6333:
6334: if ($toolstatus ne '') {
6335: if ($toolstatus) {
6336: $access = 1;
6337: } else {
6338: $access = 0;
6339: }
6340: return $access;
6341: }
6342:
1.1084 raeburn 6343: my ($is_adv,%domdef);
6344: if (ref($is_advref) eq 'HASH') {
6345: $is_adv = $is_advref->{'is_adv'};
6346: } else {
6347: $is_adv = &is_advanced_user($udom,$uname);
6348: }
6349: if (ref($domdefref) eq 'HASH') {
6350: %domdef = %{$domdefref};
6351: } else {
6352: %domdef = &get_domain_defaults($udom);
6353: }
1.976 raeburn 6354: if (ref($domdef{$tool}) eq 'HASH') {
6355: if ($is_adv) {
6356: if ($domdef{$tool}{'_LC_adv'} ne '') {
6357: if ($domdef{$tool}{'_LC_adv'}) {
6358: $access = 1;
6359: } else {
6360: $access = 0;
6361: }
6362: return $access;
6363: }
6364: }
6365: if ($inststatus ne '') {
6366: my ($hasaccess,$hasnoaccess);
6367: foreach my $affiliation (split(/:/,$inststatus)) {
6368: if ($domdef{$tool}{$affiliation} ne '') {
6369: if ($domdef{$tool}{$affiliation}) {
6370: $hasaccess = 1;
6371: } else {
6372: $hasnoaccess = 1;
6373: }
6374: }
6375: }
6376: if ($hasaccess || $hasnoaccess) {
6377: if ($hasaccess) {
6378: $access = 1;
6379: } elsif ($hasnoaccess) {
6380: $access = 0;
6381: }
6382: return $access;
6383: }
6384: } else {
6385: if ($domdef{$tool}{'default'} ne '') {
6386: if ($domdef{$tool}{'default'}) {
6387: $access = 1;
6388: } elsif ($domdef{$tool}{'default'} == 0) {
6389: $access = 0;
6390: }
6391: return $access;
6392: }
6393: }
6394: } else {
1.1172.2.6 raeburn 6395: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6396: $access = 1;
6397: } else {
6398: $access = 0;
6399: }
1.976 raeburn 6400: return $access;
6401: }
6402: }
6403:
1.1050 raeburn 6404: sub is_course_owner {
6405: my ($cdom,$cnum,$udom,$uname) = @_;
6406: if (($udom eq '') || ($uname eq '')) {
6407: $udom = $env{'user.domain'};
6408: $uname = $env{'user.name'};
6409: }
6410: unless (($udom eq '') || ($uname eq '')) {
6411: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6412: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6413: return 1;
6414: } else {
6415: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6416: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6417: return 1;
6418: }
6419: }
6420: }
6421: }
6422: return;
6423: }
6424:
1.976 raeburn 6425: sub is_advanced_user {
6426: my ($udom,$uname) = @_;
1.1085 raeburn 6427: if ($udom ne '' && $uname ne '') {
6428: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6429: if (wantarray) {
6430: return ($env{'user.adv'},$env{'user.author'});
6431: } else {
6432: return $env{'user.adv'};
6433: }
1.1085 raeburn 6434: }
6435: }
1.976 raeburn 6436: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6437: my %allroles;
1.1128 raeburn 6438: my ($is_adv,$is_author);
1.976 raeburn 6439: foreach my $role (keys(%roleshash)) {
6440: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6441: my $area = '/'.$tdomain.'/'.$trest;
6442: if ($sec ne '') {
6443: $area .= '/'.$sec;
6444: }
6445: if (($area ne '') && ($trole ne '')) {
6446: my $spec=$trole.'.'.$area;
6447: if ($trole =~ /^cr\//) {
6448: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6449: } elsif ($trole ne 'gr') {
6450: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6451: }
1.1128 raeburn 6452: if ($trole eq 'au') {
6453: $is_author = 1;
6454: }
1.976 raeburn 6455: }
6456: }
6457: foreach my $role (keys(%allroles)) {
6458: last if ($is_adv);
6459: foreach my $item (split(/:/,$allroles{$role})) {
6460: if ($item ne '') {
6461: my ($privilege,$restrictions)=split(/&/,$item);
6462: if ($privilege eq 'adv') {
6463: $is_adv = 1;
6464: last;
6465: }
6466: }
6467: }
6468: }
1.1128 raeburn 6469: if (wantarray) {
6470: return ($is_adv,$is_author);
6471: }
1.976 raeburn 6472: return $is_adv;
6473: }
1.798 raeburn 6474:
1.1035 raeburn 6475: sub check_can_request {
1.1036 raeburn 6476: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6477: my $canreq = 0;
6478: my ($types,$typename) = &Apache::loncommon::course_types();
6479: my @options = ('approval','validate','autolimit');
6480: my $optregex = join('|',@options);
6481: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6482: foreach my $type (@{$types}) {
6483: if (&usertools_access($env{'user.name'},
6484: $env{'user.domain'},
6485: $type,undef,'requestcourses')) {
6486: $canreq ++;
1.1036 raeburn 6487: if (ref($request_domains) eq 'HASH') {
6488: push(@{$request_domains->{$type}},$env{'user.domain'});
6489: }
1.1035 raeburn 6490: if ($dom eq $env{'user.domain'}) {
6491: $can_request->{$type} = 1;
6492: }
6493: }
6494: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6495: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6496: if (@curr > 0) {
1.1036 raeburn 6497: foreach my $item (@curr) {
6498: if (ref($request_domains) eq 'HASH') {
6499: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6500: if ($otherdom ne '') {
6501: if (ref($request_domains->{$type}) eq 'ARRAY') {
6502: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6503: push(@{$request_domains->{$type}},$otherdom);
6504: }
6505: } else {
6506: push(@{$request_domains->{$type}},$otherdom);
6507: }
6508: }
6509: }
6510: }
6511: unless($dom eq $env{'user.domain'}) {
6512: $canreq ++;
1.1035 raeburn 6513: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6514: $can_request->{$type} = 1;
6515: }
6516: }
6517: }
6518: }
6519: }
6520: }
6521: return $canreq;
6522: }
6523:
1.341 www 6524: # ---------------------------------------------- Custom access rule evaluation
6525:
6526: sub customaccess {
6527: my ($priv,$uri)=@_;
1.807 albertel 6528: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6529: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6530: $udom = &LONCAPA::clean_domain($udom);
6531: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6532: my $access=0;
1.800 albertel 6533: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6534: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6535: if ($type eq 'user') {
6536: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6537: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6538: if ($tdom) {
6539: if ($tdom ne $env{'user.domain'}) { next; }
6540: }
1.896 albertel 6541: if ($tuname) {
6542: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6543: }
6544: $access=($effect eq 'allow');
6545: last;
6546: }
6547: } else {
6548: if ($role) {
6549: if ($role ne $urole) { next; }
6550: }
6551: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6552: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6553: if ($tdom) {
6554: if ($tdom ne $udom) { next; }
6555: }
6556: if ($tcrs) {
6557: if ($tcrs ne $ucrs) { next; }
6558: }
6559: if ($tsec) {
6560: if ($tsec ne $usec) { next; }
6561: }
6562: $access=($effect eq 'allow');
6563: last;
6564: }
6565: if ($realm eq '' && $role eq '') {
6566: $access=($effect eq 'allow');
6567: }
1.402 bowersj2 6568: }
1.341 www 6569: }
6570: return $access;
6571: }
6572:
1.103 harris41 6573: # ------------------------------------------------- Check for a user privilege
1.12 www 6574:
6575: sub allowed {
1.810 raeburn 6576: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6577: my $ver_orguri=$uri;
1.439 www 6578: $uri=&deversion($uri);
1.152 www 6579: my $orguri=$uri;
1.52 www 6580: $uri=&declutter($uri);
1.809 raeburn 6581:
1.810 raeburn 6582: if ($priv eq 'evb') {
6583: # Evade communication block restrictions for specified role in a course
6584: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6585: return $1;
6586: } else {
6587: return;
6588: }
6589: }
6590:
1.620 albertel 6591: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6592: # Free bre access to adm and meta resources
1.775 albertel 6593: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6594: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6595: && ($priv eq 'bre')) {
1.14 www 6596: return 'F';
1.159 www 6597: }
6598:
1.545 banghart 6599: # Free bre access to user's own portfolio contents
1.714 raeburn 6600: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6601: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6602: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6603: my %setters;
6604: my ($startblock,$endblock) =
6605: &Apache::loncommon::blockcheck(\%setters,'port');
6606: if ($startblock && $endblock) {
6607: return 'B';
6608: } else {
6609: return 'F';
6610: }
1.545 banghart 6611: }
6612:
1.762 raeburn 6613: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6614: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6615: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6616: if (exists($env{'request.course.id'})) {
6617: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6618: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6619: if (($domain eq $cdom) && ($name eq $cnum)) {
6620: my $courseprivid=$env{'request.course.id'};
6621: $courseprivid=~s/\_/\//;
6622: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6623: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6624: return $1;
1.762 raeburn 6625: } else {
6626: if ($env{'request.course.sec'}) {
6627: $courseprivid.='/'.$env{'request.course.sec'};
6628: }
6629: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6630: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6631: return $2;
6632: }
1.714 raeburn 6633: }
6634: }
6635: }
6636: }
6637:
1.159 www 6638: # Free bre to public access
6639:
6640: if ($priv eq 'bre') {
1.238 www 6641: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6642: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6643: return 'F';
6644: }
1.238 www 6645: if ($copyright eq 'priv') {
6646: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6647: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6648: return '';
6649: }
6650: }
6651: if ($copyright eq 'domain') {
6652: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6653: unless (($env{'user.domain'} eq $1) ||
6654: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6655: return '';
6656: }
1.262 matthew 6657: }
1.620 albertel 6658: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6659: # Library role, so allow browsing of resources in this domain.
6660: return 'F';
1.238 www 6661: }
1.341 www 6662: if ($copyright eq 'custom') {
6663: unless (&customaccess($priv,$uri)) { return ''; }
6664: }
1.14 www 6665: }
1.264 matthew 6666: # Domain coordinator is trying to create a course
1.620 albertel 6667: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6668: # uri is the requested domain in this case.
6669: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6670: # a role of dc for the domain in question.
1.620 albertel 6671: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6672: }
1.29 www 6673:
1.52 www 6674: my $thisallowed='';
6675: my $statecond=0;
6676: my $courseprivid='';
6677:
1.1039 raeburn 6678: my $ownaccess;
1.1043 raeburn 6679: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6680: if (($priv eq 'bro') && ($env{'user.author'})) {
6681: if ($uri eq '') {
6682: $ownaccess = 1;
6683: } else {
6684: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6685: my $udom = $env{'user.domain'};
6686: my $uname = $env{'user.name'};
6687: if ($uri =~ m{^\Q$udom\E/?$}) {
6688: $ownaccess = 1;
1.1040 raeburn 6689: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6690: unless ($uri =~ m{\.\./}) {
6691: $ownaccess = 1;
6692: }
6693: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6694: my $now = time;
6695: if ($uri =~ m{^([^/]+)/?$}) {
6696: my $adom = $1;
6697: foreach my $key (keys(%env)) {
1.1042 raeburn 6698: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6699: my ($start,$end) = split('.',$env{$key});
6700: if (($now >= $start) && (!$end || $end < $now)) {
6701: $ownaccess = 1;
6702: last;
6703: }
6704: }
6705: }
6706: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6707: my $adom = $1;
6708: my $aname = $2;
1.1042 raeburn 6709: foreach my $role ('ca','aa') {
6710: if ($env{"user.role.$role./$adom/$aname"}) {
6711: my ($start,$end) =
6712: split('.',$env{"user.role.$role./$adom/$aname"});
6713: if (($now >= $start) && (!$end || $end < $now)) {
6714: $ownaccess = 1;
6715: last;
6716: }
1.1039 raeburn 6717: }
6718: }
6719: }
6720: }
6721: }
6722: }
6723: }
6724:
1.52 www 6725: # Course
6726:
1.620 albertel 6727: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6728: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6729: $thisallowed.=$1;
6730: }
1.52 www 6731: }
1.29 www 6732:
1.52 www 6733: # Domain
6734:
1.620 albertel 6735: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6736: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6737: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6738: $thisallowed.=$1;
6739: }
1.12 www 6740: }
1.52 www 6741:
1.1141 raeburn 6742: # User who is not author or co-author might still be able to edit
6743: # resource of an author in the domain (e.g., if Domain Coordinator).
6744: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6745: (&allowed('mdc',$env{'request.course.id'}))) {
6746: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6747: $thisallowed.=$1;
6748: }
6749: }
6750:
1.52 www 6751: # Course: uri itself is a course
1.66 www 6752: my $courseuri=$uri;
6753: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6754: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6755:
1.620 albertel 6756: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6757: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6758: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6759: $thisallowed.=$1;
6760: }
1.12 www 6761: }
1.29 www 6762:
1.665 albertel 6763: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6764: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6765: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6766: $thisallowed='';
1.671 raeburn 6767: my ($match)=&is_on_map($uri);
6768: if ($match) {
6769: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6770: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6771: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6772: if (@blockers > 0) {
6773: $thisallowed = 'B';
6774: } else {
6775: $thisallowed.=$1;
6776: }
1.671 raeburn 6777: }
6778: } else {
1.705 albertel 6779: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6780: if ($refuri) {
6781: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6782: $thisallowed='F';
1.671 raeburn 6783: } else {
6784: $refuri=&declutter($refuri);
6785: my ($match) = &is_on_map($refuri);
6786: if ($match) {
1.1162 raeburn 6787: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6788: if (@blockers > 0) {
6789: $thisallowed = 'B';
6790: } else {
6791: $thisallowed='F';
6792: }
1.671 raeburn 6793: }
1.669 raeburn 6794: }
1.671 raeburn 6795: }
6796: }
1.314 www 6797: }
1.492 albertel 6798:
1.766 albertel 6799: if ($priv eq 'bre'
6800: && $thisallowed ne 'F'
6801: && $thisallowed ne '2'
6802: && &is_portfolio_url($uri)) {
6803: $thisallowed = &portfolio_access($uri);
6804: }
6805:
1.52 www 6806: # Full access at system, domain or course-wide level? Exit.
1.29 www 6807: if ($thisallowed=~/F/) {
6808: return 'F';
6809: }
6810:
1.52 www 6811: # If this is generating or modifying users, exit with special codes
1.29 www 6812:
1.643 www 6813: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6814: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6815: my ($audom,$auname)=split('/',$uri);
1.643 www 6816: # no author name given, so this just checks on the general right to make a co-author in this domain
6817: unless ($auname) { return $thisallowed; }
6818: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6819: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6820: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6821: ($audom ne $env{'request.role.domain'}))) { return ''; }
6822: }
1.52 www 6823: return $thisallowed;
6824: }
6825: #
1.103 harris41 6826: # Gathered so far: system, domain and course wide privileges
1.52 www 6827: #
6828: # Course: See if uri or referer is an individual resource that is part of
6829: # the course
6830:
1.620 albertel 6831: if ($env{'request.course.id'}) {
1.232 www 6832:
1.620 albertel 6833: $courseprivid=$env{'request.course.id'};
6834: if ($env{'request.course.sec'}) {
6835: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6836: }
6837: $courseprivid=~s/\_/\//;
6838: my $checkreferer=1;
1.232 www 6839: my ($match,$cond)=&is_on_map($uri);
6840: if ($match) {
6841: $statecond=$cond;
1.620 albertel 6842: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6843: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6844: my $value = $1;
6845: if ($priv eq 'bre') {
6846: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6847: if (@blockers > 0) {
6848: $thisallowed = 'B';
6849: } else {
6850: $thisallowed.=$value;
6851: }
6852: } else {
6853: $thisallowed.=$value;
6854: }
1.52 www 6855: $checkreferer=0;
6856: }
1.29 www 6857: }
1.83 www 6858:
1.148 www 6859: if ($checkreferer) {
1.620 albertel 6860: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6861: unless ($refuri) {
1.800 albertel 6862: foreach my $key (keys(%env)) {
6863: if ($key=~/^httpref\..*\*/) {
6864: my $pattern=$key;
1.156 www 6865: $pattern=~s/^httpref\.\/res\///;
1.148 www 6866: $pattern=~s/\*/\[\^\/\]\+/g;
6867: $pattern=~s/\//\\\//g;
1.152 www 6868: if ($orguri=~/$pattern/) {
1.800 albertel 6869: $refuri=$env{$key};
1.148 www 6870: }
6871: }
1.191 harris41 6872: }
1.148 www 6873: }
1.232 www 6874:
1.148 www 6875: if ($refuri) {
1.152 www 6876: $refuri=&declutter($refuri);
1.232 www 6877: my ($match,$cond)=&is_on_map($refuri);
6878: if ($match) {
6879: my $refstatecond=$cond;
1.620 albertel 6880: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6881: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6882: my $value = $1;
6883: if ($priv eq 'bre') {
6884: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6885: if (@blockers > 0) {
6886: $thisallowed = 'B';
6887: } else {
6888: $thisallowed.=$value;
6889: }
6890: } else {
6891: $thisallowed.=$value;
6892: }
1.53 www 6893: $uri=$refuri;
6894: $statecond=$refstatecond;
1.52 www 6895: }
6896: }
1.148 www 6897: }
1.29 www 6898: }
1.52 www 6899: }
1.29 www 6900:
1.52 www 6901: #
1.103 harris41 6902: # Gathered now: all privileges that could apply, and condition number
1.52 www 6903: #
6904: #
6905: # Full or no access?
6906: #
1.29 www 6907:
1.52 www 6908: if ($thisallowed=~/F/) {
6909: return 'F';
6910: }
1.29 www 6911:
1.52 www 6912: unless ($thisallowed) {
6913: return '';
6914: }
1.29 www 6915:
1.52 www 6916: # Restrictions exist, deal with them
6917: #
6918: # C:according to course preferences
6919: # R:according to resource settings
6920: # L:unless locked
6921: # X:according to user session state
6922: #
6923:
6924: # Possibly locked functionality, check all courses
1.54 www 6925: # Locks might take effect only after 10 minutes cache expiration for other
6926: # courses, and 2 minutes for current course
1.52 www 6927:
6928: my $envkey;
6929: if ($thisallowed=~/L/) {
1.1000 raeburn 6930: foreach $envkey (keys(%env)) {
1.54 www 6931: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6932: my $courseid=$2;
6933: my $roleid=$1.'.'.$2;
1.92 www 6934: $courseid=~s/^\///;
1.54 www 6935: my $expiretime=600;
1.620 albertel 6936: if ($env{'request.role'} eq $roleid) {
1.54 www 6937: $expiretime=120;
6938: }
6939: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6940: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6941: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6942: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6943: }
1.620 albertel 6944: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6945: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6946: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6947: &log($env{'user.domain'},$env{'user.name'},
6948: $env{'user.home'},
1.57 www 6949: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6950: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6951: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6952: return '';
6953: }
6954: }
1.620 albertel 6955: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6956: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6957: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6958: &log($env{'user.domain'},$env{'user.name'},
6959: $env{'user.home'},
1.57 www 6960: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6961: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6962: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6963: return '';
6964: }
6965: }
6966: }
1.29 www 6967: }
1.52 www 6968: }
6969:
6970: #
6971: # Rest of the restrictions depend on selected course
6972: #
6973:
1.620 albertel 6974: unless ($env{'request.course.id'}) {
1.766 albertel 6975: if ($thisallowed eq 'A') {
6976: return 'A';
1.814 raeburn 6977: } elsif ($thisallowed eq 'B') {
6978: return 'B';
1.766 albertel 6979: } else {
6980: return '1';
6981: }
1.52 www 6982: }
1.29 www 6983:
1.52 www 6984: #
6985: # Now user is definitely in a course
6986: #
1.53 www 6987:
6988:
6989: # Course preferences
6990:
6991: if ($thisallowed=~/C/) {
1.620 albertel 6992: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6993: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6994: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6995: =~/\Q$rolecode\E/) {
1.1103 raeburn 6996: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6997: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6998: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6999: $env{'request.course.id'});
7000: }
1.237 www 7001: return '';
7002: }
7003:
1.620 albertel 7004: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7005: =~/\Q$unamedom\E/) {
1.1103 raeburn 7006: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7007: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7008: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7009: $env{'request.course.id'});
7010: }
1.54 www 7011: return '';
7012: }
1.53 www 7013: }
7014:
7015: # Resource preferences
7016:
7017: if ($thisallowed=~/R/) {
1.620 albertel 7018: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7019: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7020: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7021: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7022: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7023: }
7024: return '';
1.54 www 7025: }
1.53 www 7026: }
1.30 www 7027:
1.246 www 7028: # Restricted by state or randomout?
1.30 www 7029:
1.52 www 7030: if ($thisallowed=~/X/) {
1.620 albertel 7031: if ($env{'acc.randomout'}) {
1.579 albertel 7032: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7033: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7034: return '';
7035: }
1.247 www 7036: }
7037: if (&condval($statecond)) {
1.52 www 7038: return '2';
7039: } else {
7040: return '';
7041: }
7042: }
1.30 www 7043:
1.766 albertel 7044: if ($thisallowed eq 'A') {
7045: return 'A';
1.814 raeburn 7046: } elsif ($thisallowed eq 'B') {
7047: return 'B';
1.766 albertel 7048: }
1.52 www 7049: return 'F';
1.232 www 7050: }
1.1162 raeburn 7051:
1.1172.2.13 raeburn 7052: # ------------------------------------------- Check construction space access
7053:
7054: sub constructaccess {
7055: my ($url,$setpriv)=@_;
7056:
7057: # We do not allow editing of previous versions of files
7058: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7059:
7060: # Get username and domain from URL
7061: my ($ownername,$ownerdomain,$ownerhome);
7062:
7063: ($ownerdomain,$ownername) =
7064: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7065:
7066: # The URL does not really point to any authorspace, forget it
7067: unless (($ownername) && ($ownerdomain)) { return ''; }
7068:
7069: # Now we need to see if the user has access to the authorspace of
7070: # $ownername at $ownerdomain
7071:
7072: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7073: # Real author for this?
7074: $ownerhome = $env{'user.home'};
7075: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7076: return ($ownername,$ownerdomain,$ownerhome);
7077: }
7078: } else {
7079: # Co-author for this?
7080: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7081: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7082: $ownerhome = &homeserver($ownername,$ownerdomain);
7083: return ($ownername,$ownerdomain,$ownerhome);
7084: }
7085: }
7086:
7087: # We don't have any access right now. If we are not possibly going to do anything about this,
7088: # we might as well leave
7089: unless ($setpriv) { return ''; }
7090:
7091: # Backdoor access?
7092: my $allowed=&allowed('eco',$ownerdomain);
7093: # Nope
7094: unless ($allowed) { return ''; }
7095: # Looks like we may have access, but could be locked by the owner of the construction space
7096: if ($allowed eq 'U') {
7097: my %blocked=&get('environment',['domcoord.author'],
7098: $ownerdomain,$ownername);
7099: # Is blocked by owner
7100: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7101: }
7102: if (($allowed eq 'F') || ($allowed eq 'U')) {
7103: # Grant temporary access
7104: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7105: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7106: if (!$update) { $update = $then; }
7107: my $refresh=$env{'user.refresh.time'};
7108: if (!$refresh) { $refresh = $update; }
7109: my $now = time;
7110: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7111: $now,'ca','constructaccess');
7112: $ownerhome = &homeserver($ownername,$ownerdomain);
7113: return($ownername,$ownerdomain,$ownerhome);
7114: }
7115: # No business here
7116: return '';
7117: }
7118:
1.1162 raeburn 7119: sub get_comm_blocks {
7120: my ($cdom,$cnum) = @_;
7121: if ($cdom eq '' || $cnum eq '') {
7122: return unless ($env{'request.course.id'});
7123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7125: }
7126: my %commblocks;
7127: my $hashid=$cdom.'_'.$cnum;
7128: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7129: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7130: %commblocks = %{$blocksref};
7131: } else {
7132: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7133: my $cachetime = 600;
7134: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7135: }
7136: return %commblocks;
7137: }
7138:
7139: sub has_comm_blocking {
7140: my ($priv,$symb,$uri,$blocks) = @_;
7141: return unless ($env{'request.course.id'});
7142: return unless ($priv eq 'bre');
7143: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7144: my %commblocks;
7145: if (ref($blocks) eq 'HASH') {
7146: %commblocks = %{$blocks};
7147: } else {
7148: %commblocks = &get_comm_blocks();
7149: }
7150: return unless (keys(%commblocks) > 0);
7151: if (!$symb) { $symb=&symbread($uri,1); }
7152: my ($map,$resid,undef)=&decode_symb($symb);
7153: my %tocheck = (
7154: maps => $map,
7155: resources => $symb,
7156: );
7157: my @blockers;
7158: my $now = time;
1.1163 raeburn 7159: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7160: foreach my $block (keys(%commblocks)) {
7161: if ($block =~ /^(\d+)____(\d+)$/) {
7162: my ($start,$end) = ($1,$2);
7163: if ($start <= $now && $end >= $now) {
7164: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7165: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7166: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7167: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7168: unless (grep(/^\Q$block\E$/,@blockers)) {
7169: push(@blockers,$block);
7170: }
7171: }
7172: }
7173: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7174: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7175: unless (grep(/^\Q$block\E$/,@blockers)) {
7176: push(@blockers,$block);
7177: }
7178: }
7179: }
7180: }
7181: }
7182: }
7183: } elsif ($block =~ /^firstaccess____(.+)$/) {
7184: my $item = $1;
1.1163 raeburn 7185: my @to_test;
1.1162 raeburn 7186: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7187: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7188: my $check_interval;
7189: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7190: my @interval;
7191: my $type = 'map';
7192: if ($item eq 'course') {
7193: $type = 'course';
7194: @interval=&EXT("resource.0.interval");
7195: } else {
7196: if ($item =~ /___\d+___/) {
7197: $type = 'resource';
7198: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7199: if (ref($navmap)) {
7200: my $res = $navmap->getBySymb($item);
7201: push(@to_test,$res);
7202: }
1.1162 raeburn 7203: } else {
7204: my $mapsymb = &symbread($item,1);
7205: if ($mapsymb) {
7206: if (ref($navmap)) {
7207: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7208: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7209: foreach my $res (@to_test) {
1.1162 raeburn 7210: my $symb = $res->symb();
7211: next if ($symb eq $mapsymb);
7212: if ($symb ne '') {
7213: @interval=&EXT("resource.0.interval",$symb);
7214: last;
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: if ($interval[0] =~ /\d+/) {
7222: my $first_access;
7223: if ($type eq 'resource') {
7224: $first_access=&get_first_access($interval[1],$item);
7225: } elsif ($type eq 'map') {
7226: $first_access=&get_first_access($interval[1],undef,$item);
7227: } else {
7228: $first_access=&get_first_access($interval[1]);
7229: }
7230: if ($first_access) {
7231: my $timesup = $first_access+$interval[0];
7232: if ($timesup > $now) {
1.1163 raeburn 7233: foreach my $res (@to_test) {
7234: if ($res->is_problem()) {
7235: if ($res->completable()) {
7236: unless (grep(/^\Q$block\E$/,@blockers)) {
7237: push(@blockers,$block);
7238: }
7239: last;
7240: }
7241: }
1.1162 raeburn 7242: }
7243: }
7244: }
7245: }
7246: }
7247: }
7248: }
7249: }
7250: }
7251: return @blockers;
7252: }
7253:
7254: sub check_docs_block {
7255: my ($docsblock,$tocheck) =@_;
7256: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7257: return;
7258: }
7259: if (ref($docsblock->{'maps'}) eq 'HASH') {
7260: if ($tocheck->{'maps'}) {
7261: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7262: return 1;
7263: }
7264: }
7265: }
7266: if (ref($docsblock->{'resources'}) eq 'HASH') {
7267: if ($tocheck->{'resources'}) {
7268: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7269: return 1;
7270: }
7271: }
7272: }
7273: return;
7274: }
7275:
1.1133 foxr 7276: #
7277: # Removes the versino from a URI and
7278: # splits it in to its filename and path to the filename.
7279: # Seems like File::Basename could have done this more clearly.
7280: # Parameters:
7281: # $uri - input URI
7282: # Returns:
7283: # Two element list consisting of
7284: # $pathname - the URI up to and excluding the trailing /
7285: # $filename - The part of the URI following the last /
7286: # NOTE:
7287: # Another realization of this is simply:
7288: # use File::Basename;
7289: # ...
7290: # $uri = shift;
7291: # $filename = basename($uri);
7292: # $path = dirname($uri);
7293: # return ($filename, $path);
7294: #
7295: # The implementation below is probably faster however.
7296: #
1.710 albertel 7297: sub split_uri_for_cond {
7298: my $uri=&deversion(&declutter(shift));
7299: my @uriparts=split(/\//,$uri);
7300: my $filename=pop(@uriparts);
7301: my $pathname=join('/',@uriparts);
7302: return ($pathname,$filename);
7303: }
1.232 www 7304: # --------------------------------------------------- Is a resource on the map?
7305:
7306: sub is_on_map {
1.710 albertel 7307: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7308: #Trying to find the conditional for the file
1.620 albertel 7309: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7310: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7311: if ($match) {
1.289 bowersj2 7312: return (1,$1);
7313: } else {
1.434 www 7314: return (0,0);
1.289 bowersj2 7315: }
1.12 www 7316: }
7317:
1.427 www 7318: # --------------------------------------------------------- Get symb from alias
7319:
7320: sub get_symb_from_alias {
7321: my $symb=shift;
7322: my ($map,$resid,$url)=&decode_symb($symb);
7323: # Already is a symb
7324: if ($url) { return $symb; }
7325: # Must be an alias
7326: my $aliassymb='';
7327: my %bighash;
1.620 albertel 7328: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7329: &GDBM_READER(),0640)) {
7330: my $rid=$bighash{'mapalias_'.$symb};
7331: if ($rid) {
7332: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7333: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7334: $resid,$bighash{'src_'.$rid});
1.427 www 7335: }
7336: untie %bighash;
7337: }
7338: return $aliassymb;
7339: }
7340:
1.12 www 7341: # ----------------------------------------------------------------- Define Role
7342:
7343: sub definerole {
7344: if (allowed('mcr','/')) {
7345: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7346: foreach my $role (split(':',$sysrole)) {
7347: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7348: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7349: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7350: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7351: return "refused:s:$crole&$cqual";
7352: }
7353: }
1.191 harris41 7354: }
1.800 albertel 7355: foreach my $role (split(':',$domrole)) {
7356: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7357: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7358: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7359: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7360: return "refused:d:$crole&$cqual";
7361: }
7362: }
1.191 harris41 7363: }
1.800 albertel 7364: foreach my $role (split(':',$courole)) {
7365: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7366: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7367: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7368: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7369: return "refused:c:$crole&$cqual";
7370: }
7371: }
1.191 harris41 7372: }
1.620 albertel 7373: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7374: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7375: "rolesdef_$rolename=".
7376: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7377: return reply($command,$env{'user.home'});
1.12 www 7378: } else {
7379: return 'refused';
7380: }
1.105 harris41 7381: }
7382:
7383: # ---------------- Make a metadata query against the network of library servers
7384:
7385: sub metadata_query {
1.1172.2.33 raeburn 7386: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7387: my %rhash;
1.845 albertel 7388: my %libserv = &all_library();
1.244 matthew 7389: my @server_list = (defined($server_array) ? @$server_array
7390: : keys(%libserv) );
7391: for my $server (@server_list) {
1.1172.2.33 raeburn 7392: my $domains = '';
7393: if (ref($domains_hash) eq 'HASH') {
7394: $domains = $domains_hash->{$server};
7395: }
1.118 harris41 7396: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7397: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7398: $rhash{$server}=$reply;
7399: }
7400: else {
7401: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7402: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7403: $server);
7404: $rhash{$server}=$reply;
7405: }
1.112 harris41 7406: }
1.118 harris41 7407: return \%rhash;
1.240 www 7408: }
7409:
7410: # ----------------------------------------- Send log queries and wait for reply
7411:
7412: sub log_query {
7413: my ($uname,$udom,$query,%filters)=@_;
7414: my $uhome=&homeserver($uname,$udom);
7415: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7416: my $uhost=&hostname($uhome);
1.800 albertel 7417: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7418: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7419: $uhome);
1.479 albertel 7420: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7421: return get_query_reply($queryid);
7422: }
7423:
1.818 raeburn 7424: # -------------------------- Update MySQL table for portfolio file
7425:
7426: sub update_portfolio_table {
1.821 raeburn 7427: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7428: if ($group ne '') {
7429: $file_name =~s /^\Q$group\E//;
7430: }
1.818 raeburn 7431: my $homeserver = &homeserver($uname,$udom);
7432: my $queryid=
1.821 raeburn 7433: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7434: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7435: my $reply = &get_query_reply($queryid);
7436: return $reply;
7437: }
7438:
1.899 raeburn 7439: # -------------------------- Update MySQL allusers table
7440:
7441: sub update_allusers_table {
7442: my ($uname,$udom,$names) = @_;
7443: my $homeserver = &homeserver($uname,$udom);
7444: my $queryid=
7445: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7446: 'lastname='.&escape($names->{'lastname'}).'%%'.
7447: 'firstname='.&escape($names->{'firstname'}).'%%'.
7448: 'middlename='.&escape($names->{'middlename'}).'%%'.
7449: 'generation='.&escape($names->{'generation'}).'%%'.
7450: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7451: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7452: return;
1.899 raeburn 7453: }
7454:
1.508 raeburn 7455: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7456:
7457: sub fetch_enrollment_query {
1.511 raeburn 7458: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7459: my $homeserver;
1.547 raeburn 7460: my $maxtries = 1;
1.508 raeburn 7461: if ($context eq 'automated') {
7462: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7463: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7464: } else {
7465: $homeserver = &homeserver($cnum,$dom);
7466: }
1.838 albertel 7467: my $host=&hostname($homeserver);
1.506 raeburn 7468: my $cmd = '';
1.1000 raeburn 7469: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7470: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7471: }
7472: $cmd =~ s/%%$//;
7473: $cmd = &escape($cmd);
7474: my $query = 'fetchenrollment';
1.620 albertel 7475: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7476: unless ($queryid=~/^\Q$host\E\_/) {
7477: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7478: return 'error: '.$queryid;
7479: }
1.506 raeburn 7480: my $reply = &get_query_reply($queryid);
1.547 raeburn 7481: my $tries = 1;
7482: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7483: $reply = &get_query_reply($queryid);
7484: $tries ++;
7485: }
1.526 raeburn 7486: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7487: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7488: } else {
1.901 albertel 7489: my @responses = split(/:/,$reply);
1.515 raeburn 7490: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7491: foreach my $line (@responses) {
7492: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7493: $$replyref{$key} = $value;
7494: }
7495: } else {
1.1117 foxr 7496: my $pathname = LONCAPA::tempdir();
1.800 albertel 7497: foreach my $line (@responses) {
7498: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7499: $$replyref{$key} = $value;
7500: if ($value > 0) {
1.800 albertel 7501: foreach my $item (@{$$affiliatesref{$key}}) {
7502: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7503: my $destname = $pathname.'/'.$filename;
7504: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7505: if ($xml_classlist =~ /^error/) {
7506: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7507: } else {
1.506 raeburn 7508: if ( open(FILE,">$destname") ) {
7509: print FILE &unescape($xml_classlist);
7510: close(FILE);
1.526 raeburn 7511: } else {
7512: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7513: }
7514: }
7515: }
7516: }
7517: }
7518: }
7519: return 'ok';
7520: }
7521: return 'error';
7522: }
7523:
1.242 www 7524: sub get_query_reply {
7525: my $queryid=shift;
1.1117 foxr 7526: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7527: my $reply='';
7528: for (1..100) {
7529: sleep 2;
7530: if (-e $replyfile.'.end') {
1.448 albertel 7531: if (open(my $fh,$replyfile)) {
1.904 albertel 7532: $reply = join('',<$fh>);
7533: close($fh);
1.240 www 7534: } else { return 'error: reply_file_error'; }
1.242 www 7535: return &unescape($reply);
7536: }
1.240 www 7537: }
1.242 www 7538: return 'timeout:'.$queryid;
1.240 www 7539: }
7540:
7541: sub courselog_query {
1.241 www 7542: #
7543: # possible filters:
7544: # url: url or symb
7545: # username
7546: # domain
7547: # action: view, submit, grade
7548: # start: timestamp
7549: # end: timestamp
7550: #
1.240 www 7551: my (%filters)=@_;
1.620 albertel 7552: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7553: if ($filters{'url'}) {
7554: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7555: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7556: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7557: }
1.620 albertel 7558: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7559: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7560: return &log_query($cname,$cdom,'courselog',%filters);
7561: }
7562:
7563: sub userlog_query {
1.858 raeburn 7564: #
7565: # possible filters:
7566: # action: log check role
7567: # start: timestamp
7568: # end: timestamp
7569: #
1.240 www 7570: my ($uname,$udom,%filters)=@_;
7571: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7572: }
7573:
1.506 raeburn 7574: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7575:
7576: sub auto_run {
1.508 raeburn 7577: my ($cnum,$cdom) = @_;
1.876 raeburn 7578: my $response = 0;
7579: my $settings;
7580: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7581: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7582: $settings = $domconfig{'autoenroll'};
7583: if ($settings->{'run'} eq '1') {
7584: $response = 1;
7585: }
7586: } else {
1.934 raeburn 7587: my $homeserver;
7588: if (&is_course($cdom,$cnum)) {
7589: $homeserver = &homeserver($cnum,$cdom);
7590: } else {
7591: $homeserver = &domain($cdom,'primary');
7592: }
7593: if ($homeserver ne 'no_host') {
7594: $response = &reply('autorun:'.$cdom,$homeserver);
7595: }
1.876 raeburn 7596: }
1.506 raeburn 7597: return $response;
7598: }
1.776 albertel 7599:
1.506 raeburn 7600: sub auto_get_sections {
1.508 raeburn 7601: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7602: my $homeserver;
7603: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7604: $homeserver = &homeserver($cnum,$cdom);
7605: }
7606: if (!defined($homeserver)) {
7607: if ($cdom =~ /^$match_domain$/) {
7608: $homeserver = &domain($cdom,'primary');
7609: }
7610: }
7611: my @secs;
7612: if (defined($homeserver)) {
7613: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7614: unless ($response eq 'refused') {
7615: @secs = split(/:/,$response);
7616: }
1.506 raeburn 7617: }
7618: return @secs;
7619: }
1.776 albertel 7620:
1.506 raeburn 7621: sub auto_new_course {
1.1099 raeburn 7622: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7623: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7624: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7625: return $response;
7626: }
1.776 albertel 7627:
1.506 raeburn 7628: sub auto_validate_courseID {
1.508 raeburn 7629: my ($cnum,$cdom,$inst_course_id) = @_;
7630: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7631: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7632: return $response;
7633: }
1.776 albertel 7634:
1.1007 raeburn 7635: sub auto_validate_instcode {
1.1020 raeburn 7636: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7637: my ($homeserver,$response);
7638: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7639: $homeserver = &homeserver($cnum,$cdom);
7640: }
7641: if (!defined($homeserver)) {
7642: if ($cdom =~ /^$match_domain$/) {
7643: $homeserver = &domain($cdom,'primary');
7644: }
7645: }
1.1065 raeburn 7646: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7647: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7648: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7649: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7650: }
7651:
1.506 raeburn 7652: sub auto_create_password {
1.873 raeburn 7653: my ($cnum,$cdom,$authparam,$udom) = @_;
7654: my ($homeserver,$response);
1.506 raeburn 7655: my $create_passwd = 0;
7656: my $authchk = '';
1.873 raeburn 7657: if ($udom =~ /^$match_domain$/) {
7658: $homeserver = &domain($udom,'primary');
7659: }
7660: if ($homeserver eq '') {
7661: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7662: $homeserver = &homeserver($cnum,$cdom);
7663: }
7664: }
7665: if ($homeserver eq '') {
7666: $authchk = 'nodomain';
1.506 raeburn 7667: } else {
1.873 raeburn 7668: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7669: if ($response eq 'refused') {
7670: $authchk = 'refused';
7671: } else {
1.901 albertel 7672: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7673: }
1.506 raeburn 7674: }
7675: return ($authparam,$create_passwd,$authchk);
7676: }
7677:
1.706 raeburn 7678: sub auto_photo_permission {
7679: my ($cnum,$cdom,$students) = @_;
7680: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7681: my ($outcome,$perm_reqd,$conditions) =
7682: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7683: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7684: return (undef,undef);
7685: }
1.706 raeburn 7686: return ($outcome,$perm_reqd,$conditions);
7687: }
7688:
7689: sub auto_checkphotos {
7690: my ($uname,$udom,$pid) = @_;
7691: my $homeserver = &homeserver($uname,$udom);
7692: my ($result,$resulttype);
7693: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7694: &escape($uname).':'.&escape($pid),
7695: $homeserver));
1.709 albertel 7696: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7697: return (undef,undef);
7698: }
1.706 raeburn 7699: if ($outcome) {
7700: ($result,$resulttype) = split(/:/,$outcome);
7701: }
7702: return ($result,$resulttype);
7703: }
7704:
7705: sub auto_photochoice {
7706: my ($cnum,$cdom) = @_;
7707: my $homeserver = &homeserver($cnum,$cdom);
7708: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7709: &escape($cdom),
7710: $homeserver)));
1.709 albertel 7711: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7712: return (undef,undef);
7713: }
1.706 raeburn 7714: return ($update,$comment);
7715: }
7716:
7717: sub auto_photoupdate {
7718: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7719: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7720: my $host=&hostname($homeserver);
1.706 raeburn 7721: my $cmd = '';
7722: my $maxtries = 1;
1.800 albertel 7723: foreach my $affiliate (keys(%{$affiliatesref})) {
7724: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7725: }
7726: $cmd =~ s/%%$//;
7727: $cmd = &escape($cmd);
7728: my $query = 'institutionalphotos';
7729: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7730: unless ($queryid=~/^\Q$host\E\_/) {
7731: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7732: return 'error: '.$queryid;
7733: }
7734: my $reply = &get_query_reply($queryid);
7735: my $tries = 1;
7736: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7737: $reply = &get_query_reply($queryid);
7738: $tries ++;
7739: }
7740: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7741: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7742: } else {
7743: my @responses = split(/:/,$reply);
7744: my $outcome = shift(@responses);
7745: foreach my $item (@responses) {
7746: my ($key,$value) = split(/=/,$item);
7747: $$photo{$key} = $value;
7748: }
7749: return $outcome;
7750: }
7751: return 'error';
7752: }
7753:
1.521 raeburn 7754: sub auto_instcode_format {
1.793 albertel 7755: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7756: $cat_order) = @_;
1.521 raeburn 7757: my $courses = '';
1.772 raeburn 7758: my @homeservers;
1.521 raeburn 7759: if ($caller eq 'global') {
1.841 albertel 7760: my %servers = &get_servers($codedom,'library');
7761: foreach my $tryserver (keys(%servers)) {
7762: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7763: push(@homeservers,$tryserver);
7764: }
1.584 raeburn 7765: }
1.1022 raeburn 7766: } elsif ($caller eq 'requests') {
7767: if ($codedom =~ /^$match_domain$/) {
7768: my $chome = &domain($codedom,'primary');
7769: unless ($chome eq 'no_host') {
7770: push(@homeservers,$chome);
7771: }
7772: }
1.521 raeburn 7773: } else {
1.772 raeburn 7774: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7775: }
1.793 albertel 7776: foreach my $code (keys(%{$instcodes})) {
7777: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7778: }
7779: chop($courses);
1.772 raeburn 7780: my $ok_response = 0;
7781: my $response;
7782: while (@homeservers > 0 && $ok_response == 0) {
7783: my $server = shift(@homeservers);
7784: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7785: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7786: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7787: split(/:/,$response);
1.772 raeburn 7788: %{$codes} = (%{$codes},&str2hash($codes_str));
7789: push(@{$codetitles},&str2array($codetitles_str));
7790: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7791: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7792: $ok_response = 1;
7793: }
7794: }
7795: if ($ok_response) {
1.521 raeburn 7796: return 'ok';
1.772 raeburn 7797: } else {
7798: return $response;
1.521 raeburn 7799: }
7800: }
7801:
1.792 raeburn 7802: sub auto_instcode_defaults {
7803: my ($domain,$returnhash,$code_order) = @_;
7804: my @homeservers;
1.841 albertel 7805:
7806: my %servers = &get_servers($domain,'library');
7807: foreach my $tryserver (keys(%servers)) {
7808: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7809: push(@homeservers,$tryserver);
7810: }
1.792 raeburn 7811: }
1.841 albertel 7812:
1.792 raeburn 7813: my $response;
1.841 albertel 7814: foreach my $server (@homeservers) {
1.792 raeburn 7815: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7816: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7817:
7818: foreach my $pair (split(/\&/,$response)) {
7819: my ($name,$value)=split(/\=/,$pair);
7820: if ($name eq 'code_order') {
7821: @{$code_order} = split(/\&/,&unescape($value));
7822: } else {
7823: $returnhash->{&unescape($name)}=&unescape($value);
7824: }
7825: }
7826: return 'ok';
1.792 raeburn 7827: }
1.841 albertel 7828:
7829: return $response;
1.1003 raeburn 7830: }
7831:
7832: sub auto_possible_instcodes {
1.1007 raeburn 7833: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7834: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7835: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7836: return;
7837: }
1.1003 raeburn 7838: my (@homeservers,$uhome);
7839: if (defined(&domain($domain,'primary'))) {
7840: $uhome=&domain($domain,'primary');
7841: push(@homeservers,&domain($domain,'primary'));
7842: } else {
7843: my %servers = &get_servers($domain,'library');
7844: foreach my $tryserver (keys(%servers)) {
7845: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7846: push(@homeservers,$tryserver);
7847: }
7848: }
7849: }
7850: my $response;
7851: foreach my $server (@homeservers) {
7852: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7853: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7854: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7855: split(':',$response);
7856: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7857: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7858: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7859: my ($name,$value)=split('=',$item);
7860: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7861: }
7862: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7863: my ($name,$value)=split('=',$item);
7864: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7865: }
7866: return 'ok';
7867: }
7868: return $response;
7869: }
1.792 raeburn 7870:
1.1010 raeburn 7871: sub auto_courserequest_checks {
7872: my ($dom) = @_;
1.1020 raeburn 7873: my ($homeserver,%validations);
7874: if ($dom =~ /^$match_domain$/) {
7875: $homeserver = &domain($dom,'primary');
7876: }
7877: unless ($homeserver eq 'no_host') {
7878: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7879: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7880: my @items = split(/&/,$response);
7881: foreach my $item (@items) {
7882: my ($key,$value) = split('=',$item);
7883: $validations{&unescape($key)} = &thaw_unescape($value);
7884: }
7885: }
7886: }
1.1010 raeburn 7887: return %validations;
7888: }
7889:
1.1020 raeburn 7890: sub auto_courserequest_validation {
7891: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7892: my ($homeserver,$response);
7893: if ($dom =~ /^$match_domain$/) {
7894: $homeserver = &domain($dom,'primary');
7895: }
7896: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7897:
1.1020 raeburn 7898: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7899: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7900: ':'.&escape($instcode).':'.&escape($instseclist),
7901: $homeserver));
7902: }
7903: return $response;
7904: }
7905:
1.777 albertel 7906: sub auto_validate_class_sec {
1.918 raeburn 7907: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7908: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7909: my $ownerlist;
7910: if (ref($owners) eq 'ARRAY') {
7911: $ownerlist = join(',',@{$owners});
7912: } else {
7913: $ownerlist = $owners;
7914: }
1.773 raeburn 7915: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7916: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7917: return $response;
7918: }
7919:
1.679 raeburn 7920: # ------------------------------------------------------- Course Group routines
7921:
7922: sub get_coursegroups {
1.809 raeburn 7923: my ($cdom,$cnum,$group,$namespace) = @_;
7924: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7925: }
7926:
1.679 raeburn 7927: sub modify_coursegroup {
7928: my ($cdom,$cnum,$groupsettings) = @_;
7929: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7930: }
7931:
1.809 raeburn 7932: sub toggle_coursegroup_status {
7933: my ($cdom,$cnum,$group,$action) = @_;
7934: my ($from_namespace,$to_namespace);
7935: if ($action eq 'delete') {
7936: $from_namespace = 'coursegroups';
7937: $to_namespace = 'deleted_groups';
7938: } else {
7939: $from_namespace = 'deleted_groups';
7940: $to_namespace = 'coursegroups';
7941: }
7942: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7943: if (my $tmp = &error(%curr_group)) {
7944: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7945: return ('read error',$tmp);
7946: } else {
7947: my %savedsettings = %curr_group;
1.809 raeburn 7948: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7949: my $deloutcome;
7950: if ($result eq 'ok') {
1.809 raeburn 7951: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7952: } else {
7953: return ('write error',$result);
7954: }
7955: if ($deloutcome eq 'ok') {
7956: return 'ok';
7957: } else {
7958: return ('delete error',$deloutcome);
7959: }
7960: }
7961: }
7962:
1.679 raeburn 7963: sub modify_group_roles {
1.957 raeburn 7964: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7965: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7966: my $role = 'gr/'.&escape($userprivs);
7967: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7968: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7969: if ($result eq 'ok') {
7970: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7971: }
1.679 raeburn 7972: return $result;
7973: }
7974:
7975: sub modify_coursegroup_membership {
7976: my ($cdom,$cnum,$membership) = @_;
7977: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7978: return $result;
7979: }
7980:
1.682 raeburn 7981: sub get_active_groups {
7982: my ($udom,$uname,$cdom,$cnum) = @_;
7983: my $now = time;
7984: my %groups = ();
7985: foreach my $key (keys(%env)) {
1.811 albertel 7986: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7987: my ($start,$end) = split(/\./,$env{$key});
7988: if (($end!=0) && ($end<$now)) { next; }
7989: if (($start!=0) && ($start>$now)) { next; }
7990: if ($1 eq $cdom && $2 eq $cnum) {
7991: $groups{$3} = $env{$key} ;
7992: }
7993: }
7994: }
7995: return %groups;
7996: }
7997:
1.683 raeburn 7998: sub get_group_membership {
7999: my ($cdom,$cnum,$group) = @_;
8000: return(&dump('groupmembership',$cdom,$cnum,$group));
8001: }
8002:
8003: sub get_users_groups {
8004: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8005: my @usersgroups;
1.683 raeburn 8006: my $cachetime=1800;
8007:
8008: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8009: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8010: if (defined($cached)) {
1.734 albertel 8011: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8012: } else {
8013: $grouplist = '';
1.816 raeburn 8014: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8015: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8016: my $access_end = $env{'course.'.$courseid.
8017: '.default_enrollment_end_date'};
8018: my $now = time;
8019: foreach my $key (keys(%roleshash)) {
8020: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8021: my $group = $1;
8022: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8023: my $start = $2;
8024: my $end = $1;
8025: if ($start == -1) { next; } # deleted from group
8026: if (($start!=0) && ($start>$now)) { next; }
8027: if (($end!=0) && ($end<$now)) {
8028: if ($access_end && $access_end < $now) {
8029: if ($access_end - $end < 86400) {
8030: push(@usersgroups,$group);
1.733 raeburn 8031: }
8032: }
1.817 raeburn 8033: next;
1.733 raeburn 8034: }
1.817 raeburn 8035: push(@usersgroups,$group);
1.683 raeburn 8036: }
8037: }
8038: }
1.817 raeburn 8039: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8040: $grouplist = join(':',@usersgroups);
8041: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8042: }
1.733 raeburn 8043: return @usersgroups;
1.683 raeburn 8044: }
8045:
8046: sub devalidate_getgroups_cache {
8047: my ($udom,$uname,$cdom,$cnum)=@_;
8048: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8049:
1.683 raeburn 8050: my $hashid="$udom:$uname:$courseid";
8051: &devalidate_cache_new('getgroups',$hashid);
8052: }
8053:
1.12 www 8054: # ------------------------------------------------------------------ Plain Text
8055:
8056: sub plaintext {
1.988 raeburn 8057: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8058: if ($short =~ m{^cr/}) {
1.758 albertel 8059: return (split('/',$short))[-1];
8060: }
1.742 raeburn 8061: if (!defined($cid)) {
8062: $cid = $env{'request.course.id'};
8063: }
8064: my %rolenames = (
1.1008 raeburn 8065: Course => 'std',
8066: Community => 'alt1',
1.742 raeburn 8067: );
1.1037 raeburn 8068: if ($cid ne '') {
8069: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8070: unless ($forcedefault) {
8071: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8072: &Apache::lonlocal::mt_escape(\$roletext);
8073: return &Apache::lonlocal::mt($roletext);
8074: }
8075: }
8076: }
8077: if ((defined($type)) && (defined($rolenames{$type})) &&
8078: (defined($rolenames{$type})) &&
8079: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8080: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8081: } elsif ($cid ne '') {
8082: my $crstype = $env{'course.'.$cid.'.type'};
8083: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8084: (defined($prp{$short}{$rolenames{$crstype}}))) {
8085: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8086: }
1.742 raeburn 8087: }
1.1037 raeburn 8088: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8089: }
8090:
8091: # ----------------------------------------------------------------- Assign Role
8092:
8093: sub assignrole {
1.957 raeburn 8094: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8095: $context)=@_;
1.21 www 8096: my $mrole;
8097: if ($role =~ /^cr\//) {
1.393 www 8098: my $cwosec=$url;
1.811 albertel 8099: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8100: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8101: my $refused = 1;
8102: if ($context eq 'requestcourses') {
8103: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8104: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8105: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8106: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8107: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8108: if ($crsenv{'internal.courseowner'} eq
8109: $env{'user.name'}.':'.$env{'user.domain'}) {
8110: $refused = '';
8111: }
8112: }
8113: }
8114: }
8115: }
8116: if ($refused) {
8117: &logthis('Refused custom assignrole: '.
8118: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8119: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8120: return 'refused';
8121: }
1.104 www 8122: }
1.21 www 8123: $mrole='cr';
1.678 raeburn 8124: } elsif ($role =~ /^gr\//) {
8125: my $cwogrp=$url;
1.811 albertel 8126: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8127: unless (&allowed('mdg',$cwogrp)) {
8128: &logthis('Refused group assignrole: '.
8129: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8130: $env{'user.name'}.' at '.$env{'user.domain'});
8131: return 'refused';
8132: }
8133: $mrole='gr';
1.21 www 8134: } else {
1.82 www 8135: my $cwosec=$url;
1.811 albertel 8136: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8137: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8138: my $refused;
8139: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8140: if (!(&allowed('c'.$role,$url))) {
8141: $refused = 1;
8142: }
8143: } else {
8144: $refused = 1;
8145: }
1.947 raeburn 8146: if ($refused) {
1.1045 raeburn 8147: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8148: if (!$selfenroll && $context eq 'course') {
8149: my %crsenv;
8150: if ($role eq 'cc' || $role eq 'co') {
8151: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8152: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8153: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8154: if ($crsenv{'internal.courseowner'} eq
8155: $env{'user.name'}.':'.$env{'user.domain'}) {
8156: $refused = '';
8157: }
8158: }
8159: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8160: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8161: if ($crsenv{'internal.courseowner'} eq
8162: $env{'user.name'}.':'.$env{'user.domain'}) {
8163: $refused = '';
8164: }
8165: }
8166: }
8167: }
8168: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8169: $refused = '';
1.1017 raeburn 8170: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8171: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8172: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8173: my $wrongcc;
8174: if ($cnum =~ /^$match_community$/) {
8175: $wrongcc = 1 if ($role eq 'cc');
8176: } else {
8177: $wrongcc = 1 if ($role eq 'co');
8178: }
8179: unless ($wrongcc) {
8180: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8181: if ($crsenv{'internal.courseowner'} eq
8182: $env{'user.name'}.':'.$env{'user.domain'}) {
8183: $refused = '';
8184: }
1.1017 raeburn 8185: }
8186: }
1.1172.2.9 raeburn 8187: } elsif ($context eq 'requestauthor') {
8188: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8189: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8190: if ($env{'environment.requestauthor'} eq 'automatic') {
8191: $refused = '';
8192: } else {
8193: my %domdefaults = &get_domain_defaults($udom);
8194: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8195: my $checkbystatus;
8196: if ($env{'user.adv'}) {
8197: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8198: if ($disposition eq 'automatic') {
8199: $refused = '';
8200: } elsif ($disposition eq '') {
8201: $checkbystatus = 1;
8202: }
8203: } else {
8204: $checkbystatus = 1;
8205: }
8206: if ($checkbystatus) {
8207: if ($env{'environment.inststatus'}) {
8208: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8209: foreach my $type (@inststatuses) {
8210: if (($type ne '') &&
8211: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8212: $refused = '';
8213: }
8214: }
8215: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8216: $refused = '';
8217: }
8218: }
8219: }
8220: }
8221: }
1.1017 raeburn 8222: }
8223: if ($refused) {
1.947 raeburn 8224: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8225: ' '.$role.' '.$end.' '.$start.' by '.
8226: $env{'user.name'}.' at '.$env{'user.domain'});
8227: return 'refused';
8228: }
1.932 raeburn 8229: }
1.1131 raeburn 8230: } elsif ($role eq 'au') {
8231: if ($url ne '/'.$udom.'/') {
8232: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8233: ' to assign author role for '.$uname.':'.$udom.
8234: ' in domain: '.$url.' refused (wrong domain).');
8235: return 'refused';
8236: }
1.104 www 8237: }
1.21 www 8238: $mrole=$role;
8239: }
1.620 albertel 8240: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8241: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8242: if ($end) { $command.='_'.$end; }
1.21 www 8243: if ($start) {
8244: if ($end) {
1.81 www 8245: $command.='_'.$start;
1.21 www 8246: } else {
1.81 www 8247: $command.='_0_'.$start;
1.21 www 8248: }
8249: }
1.739 raeburn 8250: my $origstart = $start;
8251: my $origend = $end;
1.957 raeburn 8252: my $delflag;
1.357 www 8253: # actually delete
8254: if ($deleteflag) {
1.373 www 8255: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8256: # modify command to delete the role
1.620 albertel 8257: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8258: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8259: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8260: # set start and finish to negative values for userrolelog
8261: $start=-1;
8262: $end=-1;
1.957 raeburn 8263: $delflag = 1;
1.357 www 8264: }
8265: }
8266: # send command
1.349 www 8267: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8268: # log new user role if status is ok
1.349 www 8269: if ($answer eq 'ok') {
1.663 raeburn 8270: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8271: if (($role eq 'cc') || ($role eq 'in') ||
8272: ($role eq 'ep') || ($role eq 'ad') ||
8273: ($role eq 'ta') || ($role eq 'st') ||
8274: ($role=~/^cr/) || ($role eq 'gr') ||
8275: ($role eq 'co')) {
1.1172.2.13 raeburn 8276: # for course roles, perform group memberships changes triggered by role change.
8277: unless ($role =~ /^gr/) {
8278: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8279: $origstart,$selfenroll,$context);
8280: }
1.1172.2.9 raeburn 8281: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8282: $selfenroll,$context);
8283: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8284: ($role eq 'au') || ($role eq 'dc')) {
8285: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8286: $context);
8287: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8288: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8289: $context);
8290: }
1.1053 raeburn 8291: if ($role eq 'cc') {
8292: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8293: }
1.349 www 8294: }
8295: return $answer;
1.169 harris41 8296: }
8297:
1.1053 raeburn 8298: sub autoupdate_coowners {
8299: my ($url,$end,$start,$uname,$udom) = @_;
8300: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8301: if (($cdom ne '') && ($cnum ne '')) {
8302: my $now = time;
8303: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8304: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8305: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8306: my $instcode = $coursehash{'internal.coursecode'};
8307: if ($instcode ne '') {
1.1056 raeburn 8308: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8309: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8310: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8311: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8312: if ($result eq 'valid') {
8313: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8314: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8315: push(@newcoowners,$coowner);
8316: }
8317: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8318: push(@newcoowners,$uname.':'.$udom);
8319: }
8320: @newcoowners = sort(@newcoowners);
8321: } else {
8322: push(@newcoowners,$uname.':'.$udom);
8323: }
8324: } else {
8325: if ($coursehash{'internal.co-owners'}) {
8326: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8327: unless ($coowner eq $uname.':'.$udom) {
8328: push(@newcoowners,$coowner);
8329: }
8330: }
8331: unless (@newcoowners > 0) {
8332: $delcoowners = 1;
8333: $coowners = '';
8334: }
8335: }
8336: }
8337: if (@newcoowners || $delcoowners) {
8338: &store_coowners($cdom,$cnum,$coursehash{'home'},
8339: $delcoowners,@newcoowners);
8340: }
8341: }
8342: }
8343: }
8344: }
8345: }
8346: }
8347:
8348: sub store_coowners {
8349: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8350: my $cid = $cdom.'_'.$cnum;
8351: my ($coowners,$delresult,$putresult);
8352: if (@newcoowners) {
8353: $coowners = join(',',@newcoowners);
8354: my %coownershash = (
8355: 'internal.co-owners' => $coowners,
8356: );
8357: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8358: if ($putresult eq 'ok') {
8359: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8360: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8361: }
8362: }
8363: }
8364: if ($delcoowners) {
8365: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8366: if ($delresult eq 'ok') {
8367: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8368: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8369: }
8370: }
8371: }
8372: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8373: my %crsinfo =
8374: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8375: if (ref($crsinfo{$cid}) eq 'HASH') {
8376: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8377: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8378: }
8379: }
8380: }
8381:
1.169 harris41 8382: # -------------------------------------------------- Modify user authentication
1.197 www 8383: # Overrides without validation
8384:
1.169 harris41 8385: sub modifyuserauth {
8386: my ($udom,$uname,$umode,$upass)=@_;
8387: my $uhome=&homeserver($uname,$udom);
1.197 www 8388: unless (&allowed('mau',$udom)) { return 'refused'; }
8389: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8390: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8391: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8392: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8393: &escape($upass),$uhome);
1.620 albertel 8394: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8395: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8396: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8397: &log($udom,,$uname,$uhome,
1.620 albertel 8398: 'Authentication changed by '.$env{'user.domain'}.', '.
8399: $env{'user.name'}.', '.$umode.
1.197 www 8400: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8401: unless ($reply eq 'ok') {
1.197 www 8402: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8403: return 'error: '.$reply;
8404: }
1.170 harris41 8405: return 'ok';
1.80 www 8406: }
8407:
1.81 www 8408: # --------------------------------------------------------------- Modify a user
1.80 www 8409:
1.81 www 8410: sub modifyuser {
1.206 matthew 8411: my ($udom, $uname, $uid,
8412: $umode, $upass, $first,
8413: $middle, $last, $gene,
1.1058 raeburn 8414: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8415: $udom= &LONCAPA::clean_domain($udom);
8416: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8417: my $showcandelete = 'none';
8418: if (ref($candelete) eq 'ARRAY') {
8419: if (@{$candelete} > 0) {
8420: $showcandelete = join(', ',@{$candelete});
8421: }
8422: }
1.81 www 8423: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8424: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8425: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8426: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8427: ' desiredhome not specified').
1.620 albertel 8428: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8429: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8430: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8431: my $newuser;
8432: if ($uhome eq 'no_host') {
8433: $newuser = 1;
8434: }
1.80 www 8435: # ----------------------------------------------------------------- Create User
1.406 albertel 8436: if (($uhome eq 'no_host') &&
8437: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8438: my $unhome='';
1.844 albertel 8439: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8440: $unhome = $desiredhome;
1.620 albertel 8441: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8442: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8443: } else { # load balancing routine for determining $unhome
1.81 www 8444: my $loadm=10000000;
1.841 albertel 8445: my %servers = &get_servers($udom,'library');
8446: foreach my $tryserver (keys(%servers)) {
8447: my $answer=reply('load',$tryserver);
8448: if (($answer=~/\d+/) && ($answer<$loadm)) {
8449: $loadm=$answer;
8450: $unhome=$tryserver;
8451: }
1.80 www 8452: }
8453: }
8454: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8455: return 'error: unable to find a home server for '.$uname.
8456: ' in domain '.$udom;
1.80 www 8457: }
8458: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8459: &escape($upass),$unhome);
8460: unless ($reply eq 'ok') {
8461: return 'error: '.$reply;
8462: }
1.230 stredwic 8463: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8464: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8465: return 'error: unable verify users home machine.';
1.80 www 8466: }
1.209 matthew 8467: } # End of creation of new user
1.80 www 8468: # ---------------------------------------------------------------------- Add ID
8469: if ($uid) {
8470: $uid=~tr/A-Z/a-z/;
8471: my %uidhash=&idrget($udom,$uname);
1.196 www 8472: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8473: && (!$forceid)) {
1.80 www 8474: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8475: return 'error: user id "'.$uid.'" does not match '.
8476: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8477: }
8478: } else {
8479: &idput($udom,($uname => $uid));
8480: }
8481: }
8482: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8483: my @tmp=&get('environment',
1.899 raeburn 8484: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8485: 'permanentemail','inststatus'],
1.134 albertel 8486: $udom,$uname);
1.1075 raeburn 8487: my (%names,%oldnames);
1.313 matthew 8488: if ($tmp[0] =~ m/^error:.*/) {
8489: %names=();
8490: } else {
8491: %names = @tmp;
1.1075 raeburn 8492: %oldnames = %names;
1.313 matthew 8493: }
1.388 www 8494: #
1.1058 raeburn 8495: # If name, email and/or uid are blank (e.g., because an uploaded file
8496: # of users did not contain them), do not overwrite existing values
8497: # unless field is in $candelete array ref.
8498: #
8499:
8500: my @fields = ('firstname','middlename','lastname','generation',
8501: 'permanentemail','id');
8502: my %newvalues;
8503: if (ref($candelete) eq 'ARRAY') {
8504: foreach my $field (@fields) {
8505: if (grep(/^\Q$field\E$/,@{$candelete})) {
8506: if ($field eq 'firstname') {
8507: $names{$field} = $first;
8508: } elsif ($field eq 'middlename') {
8509: $names{$field} = $middle;
8510: } elsif ($field eq 'lastname') {
8511: $names{$field} = $last;
8512: } elsif ($field eq 'generation') {
8513: $names{$field} = $gene;
8514: } elsif ($field eq 'permanentemail') {
8515: $names{$field} = $email;
8516: } elsif ($field eq 'id') {
8517: $names{$field} = $uid;
8518: }
8519: }
8520: }
8521: }
1.388 www 8522: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8523: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8524: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8525: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8526: if ($email) {
8527: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8528: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8529: }
1.899 raeburn 8530: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8531: if (defined($inststatus)) {
8532: $names{'inststatus'} = '';
8533: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8534: if (ref($usertypes) eq 'HASH') {
8535: my @okstatuses;
8536: foreach my $item (split(/:/,$inststatus)) {
8537: if (defined($usertypes->{$item})) {
8538: push(@okstatuses,$item);
8539: }
8540: }
8541: if (@okstatuses) {
8542: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8543: }
8544: }
8545: }
1.1075 raeburn 8546: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8547: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8548: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8549: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8550: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8551: } else {
8552: $logmsg .= ' during self creation';
8553: }
1.1075 raeburn 8554: my $changed;
8555: if ($newuser) {
8556: $changed = 1;
8557: } else {
8558: foreach my $field (@fields) {
8559: if ($names{$field} ne $oldnames{$field}) {
8560: $changed = 1;
8561: last;
8562: }
8563: }
8564: }
8565: unless ($changed) {
8566: $logmsg = 'No changes in user information needed for: '.$logmsg;
8567: &logthis($logmsg);
8568: return 'ok';
8569: }
8570: my $reply = &put('environment', \%names, $udom,$uname);
8571: if ($reply ne 'ok') {
8572: return 'error: '.$reply;
8573: }
1.1087 raeburn 8574: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8575: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8576: }
1.1075 raeburn 8577: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8578: &devalidate_cache_new('namescache',$uname.':'.$udom);
8579: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8580: &logthis($logmsg);
1.134 albertel 8581: return 'ok';
1.80 www 8582: }
8583:
1.81 www 8584: # -------------------------------------------------------------- Modify student
1.80 www 8585:
1.81 www 8586: sub modifystudent {
8587: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8588: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8589: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8590: if (!$cid) {
1.620 albertel 8591: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8592: return 'not_in_class';
8593: }
1.80 www 8594: }
8595: # --------------------------------------------------------------- Make the user
1.81 www 8596: my $reply=&modifyuser
1.209 matthew 8597: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8598: $desiredhome,$email,$inststatus);
1.80 www 8599: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8600: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8601: # student's environment
1.297 matthew 8602: $uid = undef if (!$forceid);
1.455 albertel 8603: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8604: $gene,$usec,$end,$start,$type,$locktype,
8605: $cid,$selfenroll,$context,$credits);
1.297 matthew 8606: return $reply;
8607: }
8608:
8609: sub modify_student_enrollment {
1.1172.2.23 raeburn 8610: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8611: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8612: my ($cdom,$cnum,$chome);
8613: if (!$cid) {
1.620 albertel 8614: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8615: return 'not_in_class';
8616: }
1.620 albertel 8617: $cdom=$env{'course.'.$cid.'.domain'};
8618: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8619: } else {
8620: ($cdom,$cnum)=split(/_/,$cid);
8621: }
1.620 albertel 8622: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8623: if (!$chome) {
1.457 raeburn 8624: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8625: }
1.455 albertel 8626: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8627: # Make sure the user exists
1.81 www 8628: my $uhome=&homeserver($uname,$udom);
8629: if (($uhome eq '') || ($uhome eq 'no_host')) {
8630: return 'error: no such user';
8631: }
1.297 matthew 8632: # Get student data if we were not given enough information
8633: if (!defined($first) || $first eq '' ||
8634: !defined($last) || $last eq '' ||
8635: !defined($uid) || $uid eq '' ||
8636: !defined($middle) || $middle eq '' ||
8637: !defined($gene) || $gene eq '') {
1.294 matthew 8638: # They did not supply us with enough data to enroll the student, so
8639: # we need to pick up more information.
1.297 matthew 8640: my %tmp = &get('environment',
1.294 matthew 8641: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8642: ,$udom,$uname);
8643:
1.800 albertel 8644: #foreach my $key (keys(%tmp)) {
8645: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8646: #}
1.294 matthew 8647: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8648: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8649: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8650: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8651: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8652: }
1.556 albertel 8653: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8654: my $user = "$uname:$udom";
8655: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8656: my $reply=cput('classlist',
1.1148 raeburn 8657: {$user =>
1.1172.2.19 raeburn 8658: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8659: $cdom,$cnum);
1.1148 raeburn 8660: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8661: &devalidate_getsection_cache($udom,$uname,$cid);
8662: } else {
1.81 www 8663: return 'error: '.$reply;
8664: }
1.297 matthew 8665: # Add student role to user
1.83 www 8666: my $uurl='/'.$cid;
1.81 www 8667: $uurl=~s/\_/\//g;
8668: if ($usec) {
8669: $uurl.='/'.$usec;
8670: }
1.1148 raeburn 8671: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8672: $selfenroll,$context);
8673: if ($result ne 'ok') {
8674: if ($old_entry{$user} ne '') {
8675: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8676: } else {
8677: $reply = &del('classlist',[$user],$cdom,$cnum);
8678: }
8679: }
8680: return $result;
1.21 www 8681: }
8682:
1.556 albertel 8683: sub format_name {
8684: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8685: my $name;
8686: if ($first ne 'lastname') {
8687: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8688: } else {
8689: if ($lastname=~/\S/) {
8690: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8691: $name=~s/\s+,/,/;
8692: } else {
8693: $name.= $firstname.' '.$middlename.' '.$generation;
8694: }
8695: }
8696: $name=~s/^\s+//;
8697: $name=~s/\s+$//;
8698: $name=~s/\s+/ /g;
8699: return $name;
8700: }
8701:
1.84 www 8702: # ------------------------------------------------- Write to course preferences
8703:
8704: sub writecoursepref {
8705: my ($courseid,%prefs)=@_;
8706: $courseid=~s/^\///;
8707: $courseid=~s/\_/\//g;
8708: my ($cdomain,$cnum)=split(/\//,$courseid);
8709: my $chome=homeserver($cnum,$cdomain);
8710: if (($chome eq '') || ($chome eq 'no_host')) {
8711: return 'error: no such course';
8712: }
8713: my $cstring='';
1.800 albertel 8714: foreach my $pref (keys(%prefs)) {
8715: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8716: }
1.84 www 8717: $cstring=~s/\&$//;
8718: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8719: }
8720:
8721: # ---------------------------------------------------------- Make/modify course
8722:
8723: sub createcourse {
1.741 raeburn 8724: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8725: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8726: $url=&declutter($url);
8727: my $cid='';
1.1028 raeburn 8728: if ($context eq 'requestcourses') {
8729: my $can_create = 0;
8730: my ($ownername,$ownerdom) = split(':',$course_owner);
8731: if ($udom eq $ownerdom) {
8732: if (&usertools_access($ownername,$ownerdom,$category,undef,
8733: $context)) {
8734: $can_create = 1;
8735: }
8736: } else {
8737: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8738: $category);
8739: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8740: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8741: if (@curr > 0) {
8742: my @options = qw(approval validate autolimit);
8743: my $optregex = join('|',@options);
8744: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8745: $can_create = 1;
8746: }
8747: }
8748: }
8749: }
8750: if ($can_create) {
8751: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8752: unless (&allowed('ccc',$udom)) {
8753: return 'refused';
8754: }
1.1017 raeburn 8755: }
8756: } else {
8757: return 'refused';
8758: }
1.1028 raeburn 8759: } elsif (!&allowed('ccc',$udom)) {
8760: return 'refused';
1.84 www 8761: }
1.1011 raeburn 8762: # --------------------------------------------------------------- Get Unique ID
8763: my $uname;
8764: if ($cnum =~ /^$match_courseid$/) {
8765: my $chome=&homeserver($cnum,$udom,'true');
8766: if (($chome eq '') || ($chome eq 'no_host')) {
8767: $uname = $cnum;
8768: } else {
1.1038 raeburn 8769: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8770: }
8771: } else {
1.1038 raeburn 8772: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8773: }
8774: return $uname if ($uname =~ /^error/);
8775: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8776: if (!defined($course_server)) {
8777: if (defined(&domain($udom,'primary'))) {
8778: $course_server = &domain($udom,'primary');
8779: } else {
8780: $course_server = $env{'user.home'};
8781: }
8782: }
8783: my %host_servers =
8784: &Apache::lonnet::get_servers($udom,'library');
8785: unless ($host_servers{$course_server}) {
8786: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8787: }
1.84 www 8788: # ------------------------------------------------------------- Make the course
8789: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8790: $course_server);
1.84 www 8791: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8792: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8793: if (($uhome eq '') || ($uhome eq 'no_host')) {
8794: return 'error: no such course';
8795: }
1.271 www 8796: # ----------------------------------------------------------------- Course made
1.516 raeburn 8797: # log existence
1.1029 raeburn 8798: my $now = time;
1.918 raeburn 8799: my $newcourse = {
8800: $udom.'_'.$uname => {
1.921 raeburn 8801: description => $description,
8802: inst_code => $inst_code,
8803: owner => $course_owner,
8804: type => $crstype,
1.1029 raeburn 8805: creator => $env{'user.name'}.':'.
8806: $env{'user.domain'},
8807: created => $now,
8808: context => $context,
1.918 raeburn 8809: },
8810: };
1.921 raeburn 8811: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8812: # set toplevel url
1.271 www 8813: my $topurl=$url;
8814: unless ($nonstandard) {
8815: # ------------------------------------------ For standard courses, make top url
8816: my $mapurl=&clutter($url);
1.278 www 8817: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8818: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8819: <map>
8820: <resource id="1" type="start"></resource>
8821: <resource id="2" src="$mapurl"></resource>
8822: <resource id="3" type="finish"></resource>
8823: <link index="1" from="1" to="2"></link>
8824: <link index="2" from="2" to="3"></link>
8825: </map>
8826: ENDINITMAP
8827: $topurl=&declutter(
1.638 albertel 8828: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8829: );
8830: }
8831: # ----------------------------------------------------------- Write preferences
1.84 www 8832: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8833: ('description' => $description,
8834: 'url' => $topurl,
8835: 'internal.creator' => $env{'user.name'}.':'.
8836: $env{'user.domain'},
8837: 'internal.created' => $now,
8838: 'internal.creationcontext' => $context)
8839: );
1.84 www 8840: return '/'.$udom.'/'.$uname;
8841: }
8842:
1.1011 raeburn 8843: # ------------------------------------------------------------------- Create ID
8844: sub generate_coursenum {
1.1038 raeburn 8845: my ($udom,$crstype) = @_;
1.1011 raeburn 8846: my $domdesc = &domain($udom);
8847: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8848: my $first;
8849: if ($crstype eq 'Community') {
8850: $first = '0';
8851: } else {
8852: $first = int(1+rand(9));
8853: }
8854: my $uname=$first.
1.1011 raeburn 8855: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8856: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8857: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8858: # ----------------------------------------------- Make sure that does not exist
8859: my $uhome=&homeserver($uname,$udom,'true');
8860: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8861: if ($crstype eq 'Community') {
8862: $first = '0';
8863: } else {
8864: $first = int(1+rand(9));
8865: }
8866: $uname=$first.
1.1011 raeburn 8867: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8868: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8869: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8870: $uhome=&homeserver($uname,$udom,'true');
8871: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8872: return 'error: unable to generate unique course-ID';
8873: }
8874: }
8875: return $uname;
8876: }
8877:
1.813 albertel 8878: sub is_course {
1.1167 droeschl 8879: my ($cdom, $cnum) = scalar(@_) == 1 ?
8880: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8881:
8882: return unless $cdom and $cnum;
8883:
8884: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8885: '.');
8886:
1.1172.2.23 raeburn 8887: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8888: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8889: }
8890:
1.1015 raeburn 8891: sub store_userdata {
8892: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8893: my $result;
1.1016 raeburn 8894: if ($datakey ne '') {
1.1013 raeburn 8895: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8896: if ($udom eq '' || $uname eq '') {
8897: $udom = $env{'user.domain'};
8898: $uname = $env{'user.name'};
8899: }
8900: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8901: if (($uhome eq '') || ($uhome eq 'no_host')) {
8902: $result = 'error: no_host';
8903: } else {
8904: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8905: $storehash->{'host'} = $perlvar{'lonHostID'};
8906:
8907: my $namevalue='';
8908: foreach my $key (keys(%{$storehash})) {
8909: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8910: }
8911: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8912: unless ($namespace eq 'courserequests') {
8913: $datakey = &escape($datakey);
8914: }
1.1105 raeburn 8915: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8916: $namevalue,$uhome);
1.1013 raeburn 8917: }
8918: } else {
8919: $result = 'error: data to store was not a hash reference';
8920: }
8921: } else {
8922: $result= 'error: invalid requestkey';
8923: }
8924: return $result;
8925: }
8926:
1.21 www 8927: # ---------------------------------------------------------- Assign Custom Role
8928:
8929: sub assigncustomrole {
1.957 raeburn 8930: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8931: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8932: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8933: }
8934:
8935: # ----------------------------------------------------------------- Revoke Role
8936:
8937: sub revokerole {
1.957 raeburn 8938: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8939: my $now=time;
1.965 raeburn 8940: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8941: }
8942:
8943: # ---------------------------------------------------------- Revoke Custom Role
8944:
8945: sub revokecustomrole {
1.957 raeburn 8946: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8947: my $now=time;
1.357 www 8948: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8949: $deleteflag,$selfenroll,$context);
1.17 www 8950: }
8951:
1.533 banghart 8952: # ------------------------------------------------------------ Disk usage
1.535 albertel 8953: sub diskusage {
1.955 raeburn 8954: my ($udom,$uname,$directorypath,$getpropath)=@_;
8955: $directorypath =~ s/\/$//;
8956: my $listing=&reply('du2:'.&escape($directorypath).':'
8957: .&escape($getpropath).':'.&escape($uname).':'
8958: .&escape($udom),homeserver($uname,$udom));
8959: if ($listing eq 'unknown_cmd') {
8960: if ($getpropath) {
8961: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8962: }
8963: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8964: }
1.514 albertel 8965: return $listing;
1.512 banghart 8966: }
8967:
1.566 banghart 8968: sub is_locked {
1.1096 raeburn 8969: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8970: my @check;
8971: my $is_locked;
1.1093 raeburn 8972: push (@check,$file_name);
1.613 albertel 8973: my %locked = &get('file_permissions',\@check,
1.620 albertel 8974: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8975: my ($tmp)=keys(%locked);
8976: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8977:
1.566 banghart 8978: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8979: $is_locked = 'false';
8980: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8981: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8982: $is_locked = 'true';
1.1096 raeburn 8983: if (ref($which) eq 'ARRAY') {
8984: push(@{$which},$entry);
8985: } else {
8986: last;
8987: }
1.745 raeburn 8988: }
8989: }
1.566 banghart 8990: } else {
8991: $is_locked = 'false';
8992: }
1.1093 raeburn 8993: return $is_locked;
1.566 banghart 8994: }
8995:
1.759 albertel 8996: sub declutter_portfile {
8997: my ($file) = @_;
1.833 albertel 8998: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8999: return $file;
9000: }
9001:
1.559 banghart 9002: # ------------------------------------------------------------- Mark as Read Only
9003:
9004: sub mark_as_readonly {
9005: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9006: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9007: my ($tmp)=keys(%current_permissions);
9008: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9009: foreach my $file (@{$files}) {
1.759 albertel 9010: $file = &declutter_portfile($file);
1.561 banghart 9011: push(@{$current_permissions{$file}},$what);
1.559 banghart 9012: }
1.613 albertel 9013: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9014: return;
9015: }
9016:
1.572 banghart 9017: # ------------------------------------------------------------Save Selected Files
9018:
9019: sub save_selected_files {
9020: my ($user, $path, @files) = @_;
9021: my $filename = $user."savedfiles";
1.573 banghart 9022: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9023: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9024: foreach my $file (@files) {
1.620 albertel 9025: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9026: }
9027: foreach my $file (@other_files) {
1.574 banghart 9028: print (OUT $file."\n");
1.572 banghart 9029: }
1.574 banghart 9030: close (OUT);
1.572 banghart 9031: return 'ok';
9032: }
9033:
1.574 banghart 9034: sub clear_selected_files {
9035: my ($user) = @_;
9036: my $filename = $user."savedfiles";
1.1117 foxr 9037: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9038: print (OUT undef);
9039: close (OUT);
9040: return ("ok");
9041: }
9042:
1.572 banghart 9043: sub files_in_path {
9044: my ($user, $path) = @_;
9045: my $filename = $user."savedfiles";
9046: my %return_files;
1.1117 foxr 9047: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9048: while (my $line_in = <IN>) {
1.574 banghart 9049: chomp ($line_in);
9050: my @paths_and_file = split (m!/!, $line_in);
9051: my $file_part = pop (@paths_and_file);
9052: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9053: $path_part.='/';
9054: my $path_and_file = $path_part.$file_part;
9055: if ($path_part eq $path) {
9056: $return_files{$file_part}= 'selected';
9057: }
9058: }
1.574 banghart 9059: close (IN);
9060: return (\%return_files);
1.572 banghart 9061: }
9062:
9063: # called in portfolio select mode, to show files selected NOT in current directory
9064: sub files_not_in_path {
9065: my ($user, $path) = @_;
9066: my $filename = $user."savedfiles";
9067: my @return_files;
9068: my $path_part;
1.1117 foxr 9069: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9070: while (my $line = <IN>) {
1.572 banghart 9071: #ok, I know it's clunky, but I want it to work
1.800 albertel 9072: my @paths_and_file = split(m|/|, $line);
9073: my $file_part = pop(@paths_and_file);
9074: chomp($file_part);
9075: my $path_part = join('/', @paths_and_file);
1.572 banghart 9076: $path_part .= '/';
9077: my $path_and_file = $path_part.$file_part;
9078: if ($path_part ne $path) {
1.800 albertel 9079: push(@return_files, ($path_and_file));
1.572 banghart 9080: }
9081: }
1.800 albertel 9082: close(OUT);
1.574 banghart 9083: return (@return_files);
1.572 banghart 9084: }
9085:
1.745 raeburn 9086: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9087:
1.745 raeburn 9088: sub get_portfile_permissions {
9089: my ($domain,$user) = @_;
1.613 albertel 9090: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9091: my ($tmp)=keys(%current_permissions);
9092: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9093: return \%current_permissions;
9094: }
9095:
9096: #---------------------------------------------Get portfolio file access controls
9097:
1.749 raeburn 9098: sub get_access_controls {
1.745 raeburn 9099: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9100: my %access;
9101: my $real_file = $file;
9102: $file =~ s/\.meta$//;
1.745 raeburn 9103: if (defined($file)) {
1.749 raeburn 9104: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9105: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9106: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9107: }
9108: }
1.745 raeburn 9109: } else {
1.749 raeburn 9110: foreach my $key (keys(%{$current_permissions})) {
9111: if ($key =~ /\0accesscontrol$/) {
9112: if (defined($group)) {
9113: if ($key !~ m-^\Q$group\E/-) {
9114: next;
9115: }
9116: }
9117: my ($fullpath) = split(/\0/,$key);
9118: if (ref($$current_permissions{$key}) eq 'HASH') {
9119: foreach my $control (keys(%{$$current_permissions{$key}})) {
9120: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9121: }
9122: }
9123: }
9124: }
9125: }
9126: return %access;
9127: }
9128:
9129: sub modify_access_controls {
9130: my ($file_name,$changes,$domain,$user)=@_;
9131: my ($outcome,$deloutcome);
9132: my %store_permissions;
9133: my %new_values;
9134: my %new_control;
9135: my %translation;
9136: my @deletions = ();
9137: my $now = time;
9138: if (exists($$changes{'activate'})) {
9139: if (ref($$changes{'activate'}) eq 'HASH') {
9140: my @newitems = sort(keys(%{$$changes{'activate'}}));
9141: my $numnew = scalar(@newitems);
9142: for (my $i=0; $i<$numnew; $i++) {
9143: my $newkey = $newitems[$i];
9144: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9145: if ($newkey =~ /^\d+:/) {
9146: $newkey =~ s/^(\d+)/$newid/;
9147: $translation{$1} = $newid;
9148: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9149: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9150: $translation{$1} = $newid;
9151: }
1.749 raeburn 9152: $new_values{$file_name."\0".$newkey} =
9153: $$changes{'activate'}{$newitems[$i]};
9154: $new_control{$newkey} = $now;
9155: }
9156: }
9157: }
9158: my %todelete;
9159: my %changed_items;
9160: foreach my $action ('delete','update') {
9161: if (exists($$changes{$action})) {
9162: if (ref($$changes{$action}) eq 'HASH') {
9163: foreach my $key (keys(%{$$changes{$action}})) {
9164: my ($itemnum) = ($key =~ /^([^:]+):/);
9165: if ($action eq 'delete') {
9166: $todelete{$itemnum} = 1;
9167: } else {
9168: $changed_items{$itemnum} = $key;
9169: }
9170: }
1.745 raeburn 9171: }
9172: }
1.749 raeburn 9173: }
9174: # get lock on access controls for file.
9175: my $lockhash = {
9176: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9177: ':'.$env{'user.domain'},
9178: };
9179: my $tries = 0;
9180: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9181:
9182: while (($gotlock ne 'ok') && $tries <3) {
9183: $tries ++;
9184: sleep 1;
9185: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9186: }
9187: if ($gotlock eq 'ok') {
9188: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9189: my ($tmp)=keys(%curr_permissions);
9190: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9191: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9192: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9193: if (ref($curr_controls) eq 'HASH') {
9194: foreach my $control_item (keys(%{$curr_controls})) {
9195: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9196: if (defined($todelete{$itemnum})) {
9197: push(@deletions,$file_name."\0".$control_item);
9198: } else {
9199: if (defined($changed_items{$itemnum})) {
9200: $new_control{$changed_items{$itemnum}} = $now;
9201: push(@deletions,$file_name."\0".$control_item);
9202: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9203: } else {
9204: $new_control{$control_item} = $$curr_controls{$control_item};
9205: }
9206: }
1.745 raeburn 9207: }
9208: }
9209: }
1.970 raeburn 9210: my ($group);
9211: if (&is_course($domain,$user)) {
9212: ($group,my $file) = split(/\//,$file_name,2);
9213: }
1.749 raeburn 9214: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9215: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9216: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9217: # remove lock
9218: my @del_lock = ($file_name."\0".'locked_access_records');
9219: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9220: my $sqlresult =
1.970 raeburn 9221: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9222: $group);
1.749 raeburn 9223: } else {
9224: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9225: }
1.749 raeburn 9226: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9227: }
9228:
1.827 raeburn 9229: sub make_public_indefinitely {
9230: my ($requrl) = @_;
9231: my $now = time;
9232: my $action = 'activate';
9233: my $aclnum = 0;
9234: if (&is_portfolio_url($requrl)) {
9235: my (undef,$udom,$unum,$file_name,$group) =
9236: &parse_portfolio_url($requrl);
9237: my $current_perms = &get_portfile_permissions($udom,$unum);
9238: my %access_controls = &get_access_controls($current_perms,
9239: $group,$file_name);
9240: foreach my $key (keys(%{$access_controls{$file_name}})) {
9241: my ($num,$scope,$end,$start) =
9242: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9243: if ($scope eq 'public') {
9244: if ($start <= $now && $end == 0) {
9245: $action = 'none';
9246: } else {
9247: $action = 'update';
9248: $aclnum = $num;
9249: }
9250: last;
9251: }
9252: }
9253: if ($action eq 'none') {
9254: return 'ok';
9255: } else {
9256: my %changes;
9257: my $newend = 0;
9258: my $newstart = $now;
9259: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9260: $changes{$action}{$newkey} = {
9261: type => 'public',
9262: time => {
9263: start => $newstart,
9264: end => $newend,
9265: },
9266: };
9267: my ($outcome,$deloutcome,$new_values,$translation) =
9268: &modify_access_controls($file_name,\%changes,$udom,$unum);
9269: return $outcome;
9270: }
9271: } else {
9272: return 'invalid';
9273: }
9274: }
9275:
1.745 raeburn 9276: #------------------------------------------------------Get Marked as Read Only
9277:
9278: sub get_marked_as_readonly {
9279: my ($domain,$user,$what,$group) = @_;
9280: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9281: my @readonly_files;
1.629 banghart 9282: my $cmp1=$what;
9283: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9284: while (my ($file_name,$value) = each(%{$current_permissions})) {
9285: if (defined($group)) {
9286: if ($file_name !~ m-^\Q$group\E/-) {
9287: next;
9288: }
9289: }
1.561 banghart 9290: if (ref($value) eq "ARRAY"){
9291: foreach my $stored_what (@{$value}) {
1.629 banghart 9292: my $cmp2=$stored_what;
1.759 albertel 9293: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9294: $cmp2=join('',@{$stored_what});
1.745 raeburn 9295: }
1.629 banghart 9296: if ($cmp1 eq $cmp2) {
1.561 banghart 9297: push(@readonly_files, $file_name);
1.745 raeburn 9298: last;
1.563 banghart 9299: } elsif (!defined($what)) {
9300: push(@readonly_files, $file_name);
1.745 raeburn 9301: last;
1.561 banghart 9302: }
9303: }
1.745 raeburn 9304: }
1.561 banghart 9305: }
9306: return @readonly_files;
9307: }
1.577 banghart 9308: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9309:
1.577 banghart 9310: sub get_marked_as_readonly_hash {
1.745 raeburn 9311: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9312: my %readonly_files;
1.745 raeburn 9313: while (my ($file_name,$value) = each(%{$current_permissions})) {
9314: if (defined($group)) {
9315: if ($file_name !~ m-^\Q$group\E/-) {
9316: next;
9317: }
9318: }
1.577 banghart 9319: if (ref($value) eq "ARRAY"){
9320: foreach my $stored_what (@{$value}) {
1.745 raeburn 9321: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9322: foreach my $lock_descriptor(@{$stored_what}) {
9323: if ($lock_descriptor eq 'graded') {
9324: $readonly_files{$file_name} = 'graded';
9325: } elsif ($lock_descriptor eq 'handback') {
9326: $readonly_files{$file_name} = 'handback';
9327: } else {
9328: if (!exists($readonly_files{$file_name})) {
9329: $readonly_files{$file_name} = 'locked';
9330: }
9331: }
1.745 raeburn 9332: }
1.750 banghart 9333: }
1.577 banghart 9334: }
9335: }
9336: }
9337: return %readonly_files;
9338: }
1.559 banghart 9339: # ------------------------------------------------------------ Unmark as Read Only
9340:
9341: sub unmark_as_readonly {
1.629 banghart 9342: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9343: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9344: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9345: $file_name = &declutter_portfile($file_name);
1.634 albertel 9346: my $symb_crs = $what;
9347: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9348: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9349: my ($tmp)=keys(%current_permissions);
9350: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9351: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9352: foreach my $file (@readonly_files) {
1.759 albertel 9353: my $clean_file = &declutter_portfile($file);
9354: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9355: my $current_locks = $current_permissions{$file};
1.563 banghart 9356: my @new_locks;
9357: my @del_keys;
9358: if (ref($current_locks) eq "ARRAY"){
9359: foreach my $locker (@{$current_locks}) {
1.632 albertel 9360: my $compare=$locker;
1.749 raeburn 9361: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9362: $compare=join('',@{$locker});
1.746 raeburn 9363: if ($compare ne $symb_crs) {
9364: push(@new_locks, $locker);
9365: }
1.563 banghart 9366: }
9367: }
1.650 albertel 9368: if (scalar(@new_locks) > 0) {
1.563 banghart 9369: $current_permissions{$file} = \@new_locks;
9370: } else {
9371: push(@del_keys, $file);
1.613 albertel 9372: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9373: delete($current_permissions{$file});
1.563 banghart 9374: }
9375: }
1.561 banghart 9376: }
1.613 albertel 9377: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9378: return;
9379: }
1.512 banghart 9380:
1.17 www 9381: # ------------------------------------------------------------ Directory lister
9382:
9383: sub dirlist {
1.955 raeburn 9384: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9385: $uri=~s/^\///;
9386: $uri=~s/\/$//;
1.253 stredwic 9387: my ($udom, $uname);
1.955 raeburn 9388: if ($getuserdir) {
1.253 stredwic 9389: $udom = $userdomain;
9390: $uname = $username;
1.955 raeburn 9391: } else {
9392: (undef,$udom,$uname)=split(/\//,$uri);
9393: if(defined($userdomain)) {
9394: $udom = $userdomain;
9395: }
9396: if(defined($username)) {
9397: $uname = $username;
9398: }
1.253 stredwic 9399: }
1.955 raeburn 9400: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9401:
1.955 raeburn 9402: $dirRoot = $perlvar{'lonDocRoot'};
9403: if (defined($getpropath)) {
9404: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9405: $dirRoot =~ s/\/$//;
1.955 raeburn 9406: } elsif (defined($getuserdir)) {
9407: my $subdir=$uname.'__';
9408: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9409: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9410: ."/$udom/$subdir/$uname";
9411: } elsif (defined($alternateRoot)) {
9412: $dirRoot = $alternateRoot;
1.751 banghart 9413: }
1.253 stredwic 9414:
9415: if($udom) {
9416: if($uname) {
1.1135 raeburn 9417: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9418: if ($uhome eq 'no_host') {
9419: return ([],'no_host');
9420: }
1.955 raeburn 9421: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9422: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9423: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9424: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9425: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9426: } else {
9427: @listing_results = map { &unescape($_); } split(/:/,$listing);
9428: }
1.605 matthew 9429: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9430: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9431: @listing_results = split(/:/,$listing);
9432: } else {
9433: @listing_results = map { &unescape($_); } split(/:/,$listing);
9434: }
1.1135 raeburn 9435: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9436: ($listing eq 'rejected') || ($listing eq 'refused') ||
9437: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9438: return ([],$listing);
9439: } else {
9440: return (\@listing_results);
1.1135 raeburn 9441: }
1.955 raeburn 9442: } elsif(!$alternateRoot) {
1.1136 raeburn 9443: my (%allusers,%listerror);
1.841 albertel 9444: my %servers = &get_servers($udom,'library');
1.955 raeburn 9445: foreach my $tryserver (keys(%servers)) {
9446: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9447: &escape($udom),$tryserver);
9448: if ($listing eq 'unknown_cmd') {
9449: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9450: $udom, $tryserver);
9451: } else {
9452: @listing_results = map { &unescape($_); } split(/:/,$listing);
9453: }
1.841 albertel 9454: if ($listing eq 'unknown_cmd') {
9455: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9456: $udom, $tryserver);
9457: @listing_results = split(/:/,$listing);
9458: } else {
9459: @listing_results =
9460: map { &unescape($_); } split(/:/,$listing);
9461: }
1.1136 raeburn 9462: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9463: ($listing eq 'rejected') || ($listing eq 'refused') ||
9464: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9465: $listerror{$tryserver} = $listing;
9466: } else {
1.841 albertel 9467: foreach my $line (@listing_results) {
9468: my ($entry) = split(/&/,$line,2);
9469: $allusers{$entry} = 1;
9470: }
9471: }
1.253 stredwic 9472: }
1.1136 raeburn 9473: my @alluserslist=();
1.800 albertel 9474: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9475: push(@alluserslist,$user.'&user');
1.253 stredwic 9476: }
1.1136 raeburn 9477: return (\@alluserslist);
1.253 stredwic 9478: } else {
1.1136 raeburn 9479: return ([],'missing username');
1.253 stredwic 9480: }
1.955 raeburn 9481: } elsif(!defined($getpropath)) {
1.1136 raeburn 9482: my $path = $perlvar{'lonDocRoot'}.'/res/';
9483: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9484: return (\@all_domains);
1.955 raeburn 9485: } else {
1.1136 raeburn 9486: return ([],'missing domain');
1.275 stredwic 9487: }
9488: }
9489:
9490: # --------------------------------------------- GetFileTimestamp
9491: # This function utilizes dirlist and returns the date stamp for
9492: # when it was last modified. It will also return an error of -1
9493: # if an error occurs
9494:
9495: sub GetFileTimestamp {
1.955 raeburn 9496: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9497: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9498: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9499: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9500: undef,$getuserdir);
9501: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9502: return -1;
9503: }
9504: if (ref($fileref) eq 'ARRAY') {
9505: my @stats = split('&',$fileref->[0]);
1.375 matthew 9506: # @stats contains first the filename, then the stat output
9507: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9508: } else {
9509: return -1;
1.253 stredwic 9510: }
1.26 www 9511: }
9512:
1.712 albertel 9513: sub stat_file {
9514: my ($uri) = @_;
1.787 albertel 9515: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9516:
1.955 raeburn 9517: my ($udom,$uname,$file);
1.712 albertel 9518: if ($uri =~ m-^/(uploaded|editupload)/-) {
9519: ($udom,$uname,$file) =
1.811 albertel 9520: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9521: $file = 'userfiles/'.$file;
9522: }
9523: if ($uri =~ m-^/res/-) {
9524: ($udom,$uname) =
1.807 albertel 9525: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9526: $file = $uri;
9527: }
9528:
9529: if (!$udom || !$uname || !$file) {
9530: # unable to handle the uri
9531: return ();
9532: }
1.956 raeburn 9533: my $getpropath;
9534: if ($file =~ /^userfiles\//) {
9535: $getpropath = 1;
9536: }
1.1136 raeburn 9537: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9538: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9539: return ();
9540: } else {
9541: if (ref($listref) eq 'ARRAY') {
9542: my @stats = split('&',$listref->[0]);
9543: shift(@stats); #filename is first
9544: return @stats;
9545: }
1.712 albertel 9546: }
9547: return ();
9548: }
9549:
1.26 www 9550: # -------------------------------------------------------- Value of a Condition
9551:
1.713 albertel 9552: # gets the value of a specific preevaluated condition
9553: # stored in the string $env{user.state.<cid>}
9554: # or looks up a condition reference in the bighash and if if hasn't
9555: # already been evaluated recurses into docondval to get the value of
9556: # the condition, then memoizing it to
9557: # $env{user.state.<cid>.<condition>}
1.40 www 9558: sub directcondval {
9559: my $number=shift;
1.620 albertel 9560: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9561: &Apache::lonuserstate::evalstate();
9562: }
1.713 albertel 9563: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9564: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9565: } elsif ($number =~ /^_/) {
9566: my $sub_condition;
9567: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9568: &GDBM_READER(),0640)) {
9569: $sub_condition=$bighash{'conditions'.$number};
9570: untie(%bighash);
9571: }
9572: my $value = &docondval($sub_condition);
1.949 raeburn 9573: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9574: return $value;
9575: }
1.620 albertel 9576: if ($env{'user.state.'.$env{'request.course.id'}}) {
9577: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9578: } else {
9579: return 2;
9580: }
9581: }
9582:
1.713 albertel 9583: # get the collection of conditions for this resource
1.26 www 9584: sub condval {
9585: my $condidx=shift;
1.54 www 9586: my $allpathcond='';
1.713 albertel 9587: foreach my $cond (split(/\|/,$condidx)) {
9588: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9589: $allpathcond.=
9590: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9591: }
1.191 harris41 9592: }
1.54 www 9593: $allpathcond=~s/\|$//;
1.713 albertel 9594: return &docondval($allpathcond);
9595: }
9596:
9597: #evaluates an expression of conditions
9598: sub docondval {
9599: my ($allpathcond) = @_;
9600: my $result=0;
9601: if ($env{'request.course.id'}
9602: && defined($allpathcond)) {
9603: my $operand='|';
9604: my @stack;
9605: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9606: if ($chunk eq '(') {
9607: push @stack,($operand,$result);
9608: } elsif ($chunk eq ')') {
9609: my $before=pop @stack;
9610: if (pop @stack eq '&') {
9611: $result=$result>$before?$before:$result;
9612: } else {
9613: $result=$result>$before?$result:$before;
9614: }
9615: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9616: $operand=$chunk;
9617: } else {
9618: my $new=directcondval($chunk);
9619: if ($operand eq '&') {
9620: $result=$result>$new?$new:$result;
9621: } else {
9622: $result=$result>$new?$result:$new;
9623: }
9624: }
9625: }
1.26 www 9626: }
9627: return $result;
1.421 albertel 9628: }
9629:
9630: # ---------------------------------------------------- Devalidate courseresdata
9631:
9632: sub devalidatecourseresdata {
9633: my ($coursenum,$coursedomain)=@_;
9634: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9635: &devalidate_cache_new('courseres',$hashid);
1.28 www 9636: }
9637:
1.763 www 9638:
1.200 www 9639: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9640: #
9641: # Parameters:
9642: # $coursenum - Number of the course.
9643: # $coursedomain - Domain at which the course was created.
9644: # Returns:
9645: # A hash of the course parameters along (I think) with timestamps
9646: # and version info.
1.877 foxr 9647:
1.624 albertel 9648: sub get_courseresdata {
9649: my ($coursenum,$coursedomain)=@_;
1.200 www 9650: my $coursehom=&homeserver($coursenum,$coursedomain);
9651: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9652: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9653: my %dumpreply;
1.417 albertel 9654: unless (defined($cached)) {
1.624 albertel 9655: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9656: $result=\%dumpreply;
1.251 albertel 9657: my ($tmp) = keys(%dumpreply);
9658: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9659: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9660: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9661: return $tmp;
1.416 albertel 9662: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9663: $result=undef;
1.599 albertel 9664: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9665: }
9666: }
1.624 albertel 9667: return $result;
9668: }
9669:
1.633 albertel 9670: sub devalidateuserresdata {
9671: my ($uname,$udom)=@_;
9672: my $hashid="$udom:$uname";
9673: &devalidate_cache_new('userres',$hashid);
9674: }
9675:
1.624 albertel 9676: sub get_userresdata {
9677: my ($uname,$udom)=@_;
9678: #most student don\'t have any data set, check if there is some data
9679: if (&EXT_cache_status($udom,$uname)) { return undef; }
9680:
9681: my $hashid="$udom:$uname";
9682: my ($result,$cached)=&is_cached_new('userres',$hashid);
9683: if (!defined($cached)) {
9684: my %resourcedata=&dump('resourcedata',$udom,$uname);
9685: $result=\%resourcedata;
9686: &do_cache_new('userres',$hashid,$result,600);
9687: }
9688: my ($tmp)=keys(%$result);
9689: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9690: return $result;
9691: }
9692: #error 2 occurs when the .db doesn't exist
9693: if ($tmp!~/error: 2 /) {
1.672 albertel 9694: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9695: " Trying to get resource data for ".
9696: $uname." at ".$udom.": ".
9697: $tmp."</font>");
9698: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9699: #&EXT_cache_set($udom,$uname);
9700: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9701: undef($tmp); # not really an error so don't send it back
1.624 albertel 9702: }
9703: return $tmp;
9704: }
1.879 foxr 9705: #----------------------------------------------- resdata - return resource data
9706: # Purpose:
9707: # Return resource data for either users or for a course.
9708: # Parameters:
9709: # $name - Course/user name.
9710: # $domain - Name of the domain the user/course is registered on.
9711: # $type - Type of thing $name is (must be 'course' or 'user'
9712: # @which - Array of names of resources desired.
9713: # Returns:
9714: # The value of the first reasource in @which that is found in the
9715: # resource hash.
9716: # Exceptional Conditions:
9717: # If the $type passed in is not valid (not the string 'course' or
9718: # 'user', an undefined reference is returned.
9719: # If none of the resources are found, an undef is returned
1.624 albertel 9720: sub resdata {
9721: my ($name,$domain,$type,@which)=@_;
9722: my $result;
9723: if ($type eq 'course') {
9724: $result=&get_courseresdata($name,$domain);
9725: } elsif ($type eq 'user') {
9726: $result=&get_userresdata($name,$domain);
9727: }
9728: if (!ref($result)) { return $result; }
1.251 albertel 9729: foreach my $item (@which) {
1.927 albertel 9730: if (defined($result->{$item->[0]})) {
9731: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9732: }
1.250 albertel 9733: }
1.291 albertel 9734: return undef;
1.200 www 9735: }
9736:
1.1172.2.31 raeburn 9737: sub get_numsuppfiles {
9738: my ($cnum,$cdom,$ignorecache)=@_;
9739: my $hashid=$cnum.':'.$cdom;
9740: my ($suppcount,$cached);
9741: unless ($ignorecache) {
9742: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9743: }
9744: unless (defined($cached)) {
9745: my $chome=&homeserver($cnum,$cdom);
9746: unless ($chome eq 'no_host') {
9747: ($suppcount,my $errors) = (0,0);
9748: my $suppmap = 'supplemental.sequence';
9749: ($suppcount,$errors) =
9750: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9751: }
9752: &do_cache_new('suppcount',$hashid,$suppcount,600);
9753: }
9754: return $suppcount;
9755: }
9756:
1.379 matthew 9757: #
9758: # EXT resource caching routines
9759: #
9760:
9761: sub clear_EXT_cache_status {
1.383 albertel 9762: &delenv('cache.EXT.');
1.379 matthew 9763: }
9764:
9765: sub EXT_cache_status {
9766: my ($target_domain,$target_user) = @_;
1.383 albertel 9767: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9768: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9769: # We know already the user has no data
9770: return 1;
9771: } else {
9772: return 0;
9773: }
9774: }
9775:
9776: sub EXT_cache_set {
9777: my ($target_domain,$target_user) = @_;
1.383 albertel 9778: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9779: #&appenv({$cachename => time});
1.379 matthew 9780: }
9781:
1.28 www 9782: # --------------------------------------------------------- Value of a Variable
1.58 www 9783: sub EXT {
1.715 albertel 9784:
1.1172.2.28 raeburn 9785: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9786: unless ($varname) { return ''; }
1.218 albertel 9787: #get real user name/domain, courseid and symb
9788: my $courseid;
1.359 albertel 9789: my $publicuser;
1.427 www 9790: if ($symbparm) {
9791: $symbparm=&get_symb_from_alias($symbparm);
9792: }
1.218 albertel 9793: if (!($uname && $udom)) {
1.790 albertel 9794: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9795: if (!$symbparm) { $symbparm=$cursymb; }
9796: } else {
1.620 albertel 9797: $courseid=$env{'request.course.id'};
1.218 albertel 9798: }
1.48 www 9799: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9800: my $rest;
1.320 albertel 9801: if (defined($therest[0])) {
1.48 www 9802: $rest=join('.',@therest);
9803: } else {
9804: $rest='';
9805: }
1.320 albertel 9806:
1.57 www 9807: my $qualifierrest=$qualifier;
9808: if ($rest) { $qualifierrest.='.'.$rest; }
9809: my $spacequalifierrest=$space;
9810: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9811: if ($realm eq 'user') {
1.48 www 9812: # --------------------------------------------------------------- user.resource
9813: if ($space eq 'resource') {
1.651 albertel 9814: if ( (defined($Apache::lonhomework::parsing_a_problem)
9815: || defined($Apache::lonhomework::parsing_a_task))
9816: &&
1.744 albertel 9817: ($symbparm eq &symbread()) ) {
9818: # if we are in the middle of processing the resource the
9819: # get the value we are planning on committing
9820: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9821: return $Apache::lonhomework::results{$qualifierrest};
9822: } else {
9823: return $Apache::lonhomework::history{$qualifierrest};
9824: }
1.335 albertel 9825: } else {
1.359 albertel 9826: my %restored;
1.620 albertel 9827: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9828: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9829: } else {
9830: %restored=&restore($symbparm,$courseid,$udom,$uname);
9831: }
1.335 albertel 9832: return $restored{$qualifierrest};
9833: }
1.48 www 9834: # ----------------------------------------------------------------- user.access
9835: } elsif ($space eq 'access') {
1.218 albertel 9836: # FIXME - not supporting calls for a specific user
1.48 www 9837: return &allowed($qualifier,$rest);
9838: # ------------------------------------------ user.preferences, user.environment
9839: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9840: if (($uname eq $env{'user.name'}) &&
9841: ($udom eq $env{'user.domain'})) {
9842: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9843: } else {
1.359 albertel 9844: my %returnhash;
9845: if (!$publicuser) {
9846: %returnhash=&userenvironment($udom,$uname,
9847: $qualifierrest);
9848: }
1.218 albertel 9849: return $returnhash{$qualifierrest};
9850: }
1.48 www 9851: # ----------------------------------------------------------------- user.course
9852: } elsif ($space eq 'course') {
1.218 albertel 9853: # FIXME - not supporting calls for a specific user
1.620 albertel 9854: return $env{join('.',('request.course',$qualifier))};
1.48 www 9855: # ------------------------------------------------------------------- user.role
9856: } elsif ($space eq 'role') {
1.218 albertel 9857: # FIXME - not supporting calls for a specific user
1.620 albertel 9858: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9859: if ($qualifier eq 'value') {
9860: return $role;
9861: } elsif ($qualifier eq 'extent') {
9862: return $where;
9863: }
9864: # ----------------------------------------------------------------- user.domain
9865: } elsif ($space eq 'domain') {
1.218 albertel 9866: return $udom;
1.48 www 9867: # ------------------------------------------------------------------- user.name
9868: } elsif ($space eq 'name') {
1.218 albertel 9869: return $uname;
1.48 www 9870: # ---------------------------------------------------- Any other user namespace
1.29 www 9871: } else {
1.359 albertel 9872: my %reply;
9873: if (!$publicuser) {
9874: %reply=&get($space,[$qualifierrest],$udom,$uname);
9875: }
9876: return $reply{$qualifierrest};
1.48 www 9877: }
1.236 www 9878: } elsif ($realm eq 'query') {
9879: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9880: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9881: [$spacequalifierrest]);
1.620 albertel 9882: return $env{'form.'.$spacequalifierrest};
1.236 www 9883: } elsif ($realm eq 'request') {
1.48 www 9884: # ------------------------------------------------------------- request.browser
9885: if ($space eq 'browser') {
1.1145 bisitz 9886: return $env{'browser.'.$qualifier};
1.57 www 9887: # ------------------------------------------------------------ request.filename
9888: } else {
1.620 albertel 9889: return $env{'request.'.$spacequalifierrest};
1.29 www 9890: }
1.28 www 9891: } elsif ($realm eq 'course') {
1.48 www 9892: # ---------------------------------------------------------- course.description
1.620 albertel 9893: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9894: } elsif ($realm eq 'resource') {
1.165 www 9895:
1.620 albertel 9896: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9897: if (!$symbparm) { $symbparm=&symbread(); }
9898: }
1.693 albertel 9899:
1.1172.2.30 raeburn 9900: if ($qualifier eq '') {
9901: if ($space eq 'title') {
9902: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9903: return &gettitle($symbparm);
9904: }
1.693 albertel 9905:
1.1172.2.30 raeburn 9906: if ($space eq 'map') {
9907: my ($map) = &decode_symb($symbparm);
9908: return &symbread($map);
9909: }
9910: if ($space eq 'maptitle') {
9911: my ($map) = &decode_symb($symbparm);
9912: return &gettitle($map);
9913: }
9914: if ($space eq 'filename') {
9915: if ($symbparm) {
9916: return &clutter((&decode_symb($symbparm))[2]);
9917: }
9918: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9919: }
1.1172.2.30 raeburn 9920:
9921: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9922: if ($space eq 'visibleparts') {
9923: my $navmap = Apache::lonnavmaps::navmap->new();
9924: my $item;
9925: if (ref($navmap)) {
9926: my $res = $navmap->getBySymb($symbparm);
9927: my $parts = $res->parts();
9928: if (ref($parts) eq 'ARRAY') {
9929: $item = join(',',@{$parts});
9930: }
9931: undef($navmap);
9932: }
9933: return $item;
9934: }
9935: }
9936: }
1.693 albertel 9937:
9938: my ($section, $group, @groups);
1.593 albertel 9939: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 9940: if (($courseid eq '') && ($cid)) {
9941: $courseid = $cid;
9942: }
9943: if (($symbparm && $courseid) &&
9944: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9945:
1.218 albertel 9946: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9947:
1.60 www 9948: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9949: my $symbp=$symbparm;
1.735 albertel 9950: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9951:
9952: my $symbparm=$symbp.'.'.$spacequalifierrest;
9953: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9954:
1.620 albertel 9955: if (($env{'user.name'} eq $uname) &&
9956: ($env{'user.domain'} eq $udom)) {
9957: $section=$env{'request.course.sec'};
1.733 raeburn 9958: @groups = split(/:/,$env{'request.course.groups'});
9959: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9960: } else {
1.539 albertel 9961: if (! defined($usection)) {
1.551 albertel 9962: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9963: } else {
9964: $section = $usection;
9965: }
1.733 raeburn 9966: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9967: }
9968:
9969: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9970: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9971: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9972:
1.593 albertel 9973: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9974: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9975: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9976:
1.60 www 9977: # ----------------------------------------------------------- first, check user
1.624 albertel 9978:
9979: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9980: ([$courselevelr,'resource'],
9981: [$courselevelm,'map' ],
9982: [$courselevel, 'course' ]));
1.931 albertel 9983: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9984:
1.594 albertel 9985: # ------------------------------------------------ second, check some of course
1.684 raeburn 9986: my $coursereply;
1.691 raeburn 9987: if (@groups > 0) {
9988: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9989: $mapparm,$spacequalifierrest);
1.927 albertel 9990: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9991: }
1.96 www 9992:
1.684 raeburn 9993: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9994: $env{'course.'.$courseid.'.domain'},
9995: 'course',
9996: ([$seclevelr, 'resource'],
9997: [$seclevelm, 'map' ],
9998: [$seclevel, 'course' ],
9999: [$courselevelr,'resource']));
10000: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10001:
1.60 www 10002: # ------------------------------------------------------ third, check map parms
1.218 albertel 10003: my %parmhash=();
10004: my $thisparm='';
10005: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10006: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10007: &GDBM_READER(),0640)) {
1.218 albertel 10008: $thisparm=$parmhash{$symbparm};
10009: untie(%parmhash);
10010: }
1.927 albertel 10011: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10012: }
1.594 albertel 10013: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10014:
1.218 albertel 10015: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10016: my $filename;
10017: if (!$symbparm) { $symbparm=&symbread(); }
10018: if ($symbparm) {
1.409 www 10019: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10020: } else {
1.620 albertel 10021: $filename=$env{'request.filename'};
1.282 albertel 10022: }
10023: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10024: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10025: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10026: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10027:
1.927 albertel 10028: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10029: if ($symbparm && defined($courseid) &&
1.620 albertel 10030: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10031: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10032: $env{'course.'.$courseid.'.domain'},
10033: 'course',
1.927 albertel 10034: ([$courselevelm,'map' ],
10035: [$courselevel, 'course']));
10036: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10037: }
1.145 www 10038: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10039: unless ($space eq '0') {
1.336 albertel 10040: my @parts=split(/_/,$space);
10041: my $id=pop(@parts);
10042: my $part=join('_',@parts);
10043: if ($part eq '') { $part='0'; }
1.927 albertel 10044: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10045: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10046: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10047: }
1.395 albertel 10048: if ($recurse) { return undef; }
10049: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10050: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10051: # ---------------------------------------------------- Any other user namespace
10052: } elsif ($realm eq 'environment') {
10053: # ----------------------------------------------------------------- environment
1.620 albertel 10054: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10055: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10056: } else {
1.770 albertel 10057: if ($uname eq 'anonymous' && $udom eq '') {
10058: return '';
10059: }
1.219 albertel 10060: my %returnhash=&userenvironment($udom,$uname,
10061: $spacequalifierrest);
10062: return $returnhash{$spacequalifierrest};
10063: }
1.28 www 10064: } elsif ($realm eq 'system') {
1.48 www 10065: # ----------------------------------------------------------------- system.time
10066: if ($space eq 'time') {
10067: return time;
10068: }
1.696 albertel 10069: } elsif ($realm eq 'server') {
10070: # ----------------------------------------------------------------- system.time
10071: if ($space eq 'name') {
10072: return $ENV{'SERVER_NAME'};
10073: }
1.28 www 10074: }
1.48 www 10075: return '';
1.61 www 10076: }
10077:
1.927 albertel 10078: sub get_reply {
10079: my ($reply_value) = @_;
1.940 raeburn 10080: if (ref($reply_value) eq 'ARRAY') {
10081: if (wantarray) {
10082: return @$reply_value;
10083: }
10084: return $reply_value->[0];
10085: } else {
10086: return $reply_value;
1.927 albertel 10087: }
10088: }
10089:
1.691 raeburn 10090: sub check_group_parms {
10091: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10092: my @groupitems = ();
10093: my $resultitem;
1.927 albertel 10094: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10095: foreach my $group (@{$groups}) {
10096: foreach my $level (@levels) {
1.927 albertel 10097: my $item = $courseid.'.['.$group.'].'.$level->[0];
10098: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10099: }
10100: }
10101: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10102: $env{'course.'.$courseid.'.domain'},
10103: 'course',@groupitems);
10104: return $coursereply;
10105: }
10106:
10107: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10108: my ($courseid,@groups) = @_;
10109: @groups = sort(@groups);
1.691 raeburn 10110: return @groups;
10111: }
10112:
1.395 albertel 10113: sub packages_tab_default {
10114: my ($uri,$varname)=@_;
10115: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10116:
10117: my (@extension,@specifics,$do_default);
10118: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10119: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10120: if ($pack_type eq 'default') {
10121: $do_default=1;
10122: } elsif ($pack_type eq 'extension') {
10123: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10124: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10125: # only look at packages defaults for packages that this id is
1.738 albertel 10126: push(@specifics,[$package,$pack_type,$pack_part]);
10127: }
10128: }
10129: # first look for a package that matches the requested part id
10130: foreach my $package (@specifics) {
10131: my (undef,$pack_type,$pack_part)=@{$package};
10132: next if ($pack_part ne $part);
10133: if (defined($packagetab{"$pack_type&$name&default"})) {
10134: return $packagetab{"$pack_type&$name&default"};
10135: }
10136: }
10137: # look for any possible matching non extension_ package
10138: foreach my $package (@specifics) {
10139: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10140: if (defined($packagetab{"$pack_type&$name&default"})) {
10141: return $packagetab{"$pack_type&$name&default"};
10142: }
1.585 albertel 10143: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10144: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10145: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10146: }
10147: }
1.738 albertel 10148: # look for any posible extension_ match
10149: foreach my $package (@extension) {
10150: my ($package,$pack_type)=@{$package};
10151: if (defined($packagetab{"$pack_type&$name&default"})) {
10152: return $packagetab{"$pack_type&$name&default"};
10153: }
10154: if (defined($packagetab{$package."&$name&default"})) {
10155: return $packagetab{$package."&$name&default"};
10156: }
10157: }
10158: # look for a global default setting
10159: if ($do_default && defined($packagetab{"default&$name&default"})) {
10160: return $packagetab{"default&$name&default"};
10161: }
1.395 albertel 10162: return undef;
10163: }
10164:
1.334 albertel 10165: sub add_prefix_and_part {
10166: my ($prefix,$part)=@_;
10167: my $keyroot;
10168: if (defined($prefix) && $prefix !~ /^__/) {
10169: # prefix that has a part already
10170: $keyroot=$prefix;
10171: } elsif (defined($prefix)) {
10172: # prefix that is missing a part
10173: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10174: } else {
10175: # no prefix at all
10176: if (defined($part)) { $keyroot='_'.$part; }
10177: }
10178: return $keyroot;
10179: }
10180:
1.71 www 10181: # ---------------------------------------------------------------- Get metadata
10182:
1.599 albertel 10183: my %metaentry;
1.1070 www 10184: my %importedpartids;
1.71 www 10185: sub metadata {
1.176 www 10186: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10187: $uri=&declutter($uri);
1.288 albertel 10188: # if it is a non metadata possible uri return quickly
1.529 albertel 10189: if (($uri eq '') ||
10190: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10191: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10192: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10193: return undef;
10194: }
1.1140 www 10195: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10196: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10197: return undef;
1.288 albertel 10198: }
1.73 www 10199: my $filename=$uri;
10200: $uri=~s/\.meta$//;
1.172 www 10201: #
10202: # Is the metadata already cached?
1.177 www 10203: # Look at timestamp of caching
1.172 www 10204: # Everything is cached by the main uri, libraries are never directly cached
10205: #
1.428 albertel 10206: if (!defined($liburi)) {
1.599 albertel 10207: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10208: if (defined($cached)) { return $result->{':'.$what}; }
10209: }
10210: {
1.1069 www 10211: # Imported parts would go here
1.1070 www 10212: my %importedids=();
10213: my @origfileimportpartids=();
1.1069 www 10214: my $importedparts=0;
1.172 www 10215: #
10216: # Is this a recursive call for a library?
10217: #
1.599 albertel 10218: # if (! exists($metacache{$uri})) {
10219: # $metacache{$uri}={};
10220: # }
1.924 albertel 10221: my $cachetime = 60*60;
1.171 www 10222: if ($liburi) {
10223: $liburi=&declutter($liburi);
10224: $filename=$liburi;
1.401 bowersj2 10225: } else {
1.599 albertel 10226: &devalidate_cache_new('meta',$uri);
10227: undef(%metaentry);
1.401 bowersj2 10228: }
1.140 www 10229: my %metathesekeys=();
1.73 www 10230: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10231: my $metastring;
1.1140 www 10232: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10233: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10234: $metastring =
1.929 albertel 10235: &Apache::lonnet::ssi_body($which,
1.924 albertel 10236: ('grade_target' => 'meta'));
10237: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10238: } elsif (($uri !~ m -^(editupload)/-) &&
10239: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10240: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10241: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10242: $metastring=&getfile($file);
1.489 albertel 10243: }
1.208 albertel 10244: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10245: my $token;
1.140 www 10246: undef %metathesekeys;
1.71 www 10247: while ($token=$parser->get_token) {
1.339 albertel 10248: if ($token->[0] eq 'S') {
10249: if (defined($token->[2]->{'package'})) {
1.172 www 10250: #
10251: # This is a package - get package info
10252: #
1.339 albertel 10253: my $package=$token->[2]->{'package'};
10254: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10255: if (defined($token->[2]->{'id'})) {
10256: $keyroot.='_'.$token->[2]->{'id'};
10257: }
1.599 albertel 10258: if ($metaentry{':packages'}) {
10259: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10260: } else {
1.599 albertel 10261: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10262: }
1.736 albertel 10263: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10264: my $part=$keyroot;
10265: $part=~s/^\_//;
1.736 albertel 10266: if ($pack_entry=~/^\Q$package\E\&/ ||
10267: $pack_entry=~/^\Q$package\E_0\&/) {
10268: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10269: # ignore package.tab specified default values
10270: # here &package_tab_default() will fetch those
10271: if ($subp eq 'default') { next; }
1.736 albertel 10272: my $value=$packagetab{$pack_entry};
1.432 albertel 10273: my $unikey;
10274: if ($pack =~ /_0$/) {
10275: $unikey='parameter_0_'.$name;
10276: $part=0;
10277: } else {
10278: $unikey='parameter'.$keyroot.'_'.$name;
10279: }
1.339 albertel 10280: if ($subp eq 'display') {
10281: $value.=' [Part: '.$part.']';
10282: }
1.599 albertel 10283: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10284: $metathesekeys{$unikey}=1;
1.599 albertel 10285: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10286: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10287: }
1.599 albertel 10288: if (defined($metaentry{':'.$unikey.'.default'})) {
10289: $metaentry{':'.$unikey}=
10290: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10291: }
1.339 albertel 10292: }
10293: }
10294: } else {
1.172 www 10295: #
10296: # This is not a package - some other kind of start tag
1.339 albertel 10297: #
10298: my $entry=$token->[1];
1.1068 www 10299: my $unikey='';
1.175 www 10300:
1.339 albertel 10301: if ($entry eq 'import') {
1.175 www 10302: #
10303: # Importing a library here
1.339 albertel 10304: #
1.1067 www 10305: my $location=$parser->get_text('/import');
10306: my $dir=$filename;
10307: $dir=~s|[^/]*$||;
10308: $location=&filelocation($dir,$location);
1.1069 www 10309:
1.1068 www 10310: my $importmode=$token->[2]->{'importmode'};
10311: if ($importmode eq 'problem') {
1.1069 www 10312: # Import as problem/response
1.1068 www 10313: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10314: } elsif ($importmode eq 'part') {
10315: # Import as part(s)
1.1069 www 10316: $importedparts=1;
10317: # We need to get the original file and the imported file to get the part order correct
10318: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10319: # Load and inspect original file
1.1070 www 10320: if ($#origfileimportpartids<0) {
10321: undef(%importedpartids);
10322: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10323: my $origfile=&getfile($origfilelocation);
10324: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10325: }
10326:
1.1069 www 10327: # Load and inspect imported file
10328: my $impfile=&getfile($location);
10329: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10330: if ($#impfilepartids>=0) {
10331: # This problem had parts
1.1070 www 10332: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10333: } else {
10334: # Importing by turning a single problem into a problem part
10335: # It gets the import-tags ID as part-ID
10336: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10337: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10338: }
1.1068 www 10339: } else {
10340: # Normal import
10341: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10342: if (defined($token->[2]->{'id'})) {
10343: $unikey.='_'.$token->[2]->{'id'};
10344: }
1.1067 www 10345: }
10346:
1.339 albertel 10347: if ($depthcount<20) {
1.736 albertel 10348: my $metadata =
10349: &metadata($uri,'keys', $location,$unikey,
10350: $depthcount+1);
10351: foreach my $meta (split(',',$metadata)) {
10352: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10353: $metathesekeys{$meta}=1;
1.339 albertel 10354: }
1.1068 www 10355:
10356: }
1.1067 www 10357: } else {
10358: #
10359: # Not importing, some other kind of non-package, non-library start tag
10360: #
10361: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10362: if (defined($token->[2]->{'id'})) {
10363: $unikey.='_'.$token->[2]->{'id'};
10364: }
1.339 albertel 10365: if (defined($token->[2]->{'name'})) {
10366: $unikey.='_'.$token->[2]->{'name'};
10367: }
10368: $metathesekeys{$unikey}=1;
1.736 albertel 10369: foreach my $param (@{$token->[3]}) {
10370: $metaentry{':'.$unikey.'.'.$param} =
10371: $token->[2]->{$param};
1.339 albertel 10372: }
10373: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10374: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10375: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10376: # only ws inside the tag, and not in default, so use default
10377: # as value
1.599 albertel 10378: $metaentry{':'.$unikey}=$default;
1.908 albertel 10379: } elsif ( $internaltext =~ /\S/ ) {
10380: # something interesting inside the tag
10381: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10382: } else {
1.908 albertel 10383: # no interesting values, don't set a default
1.339 albertel 10384: }
1.172 www 10385: # end of not-a-package not-a-library import
1.339 albertel 10386: }
1.172 www 10387: # end of not-a-package start tag
1.339 albertel 10388: }
1.172 www 10389: # the next is the end of "start tag"
1.339 albertel 10390: }
10391: }
1.483 albertel 10392: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10393: $extension = lc($extension);
10394: if ($extension eq 'htm') { $extension='html'; }
10395:
1.737 albertel 10396: foreach my $key (keys(%packagetab)) {
1.483 albertel 10397: #no specific packages #how's our extension
10398: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10399: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10400: \%metathesekeys);
10401: }
1.883 albertel 10402:
10403: if (!exists($metaentry{':packages'})
10404: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10405: foreach my $key (keys(%packagetab)) {
1.483 albertel 10406: #no specific packages well let's get default then
10407: if ($key!~/^default&/) { next; }
1.488 albertel 10408: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10409: \%metathesekeys);
10410: }
10411: }
1.338 www 10412: # are there custom rights to evaluate
1.599 albertel 10413: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10414:
1.338 www 10415: #
10416: # Importing a rights file here
1.339 albertel 10417: #
10418: unless ($depthcount) {
1.599 albertel 10419: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10420: my $dir=$filename;
10421: $dir=~s|[^/]*$||;
10422: $location=&filelocation($dir,$location);
1.736 albertel 10423: my $rights_metadata =
10424: &metadata($uri,'keys',$location,'_rights',
10425: $depthcount+1);
10426: foreach my $rights (split(',',$rights_metadata)) {
10427: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10428: $metathesekeys{$rights}=1;
1.339 albertel 10429: }
10430: }
10431: }
1.737 albertel 10432: # uniqifiy package listing
10433: my %seen;
10434: my @uniq_packages =
10435: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10436: $metaentry{':packages'} = join(',',@uniq_packages);
10437:
1.1070 www 10438: if ($importedparts) {
10439: # We had imported parts and need to rebuild partorder
10440: $metaentry{':partorder'}='';
10441: $metathesekeys{'partorder'}=1;
10442: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10443: if ($origfileimportpartids[$index] eq 'part') {
10444: # original part, part of the problem
10445: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10446: } else {
10447: # we have imported parts at this position
10448: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10449: }
10450: }
10451: $metaentry{':partorder'}=~s/^\,//;
10452: }
10453:
1.737 albertel 10454: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10455: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10456: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10457: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10458: # this is the end of "was not already recently cached
1.71 www 10459: }
1.599 albertel 10460: return $metaentry{':'.$what};
1.261 albertel 10461: }
10462:
1.488 albertel 10463: sub metadata_create_package_def {
1.483 albertel 10464: my ($uri,$key,$package,$metathesekeys)=@_;
10465: my ($pack,$name,$subp)=split(/\&/,$key);
10466: if ($subp eq 'default') { next; }
10467:
1.599 albertel 10468: if (defined($metaentry{':packages'})) {
10469: $metaentry{':packages'}.=','.$package;
1.483 albertel 10470: } else {
1.599 albertel 10471: $metaentry{':packages'}=$package;
1.483 albertel 10472: }
10473: my $value=$packagetab{$key};
10474: my $unikey;
10475: $unikey='parameter_0_'.$name;
1.599 albertel 10476: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10477: $$metathesekeys{$unikey}=1;
1.599 albertel 10478: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10479: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10480: }
1.599 albertel 10481: if (defined($metaentry{':'.$unikey.'.default'})) {
10482: $metaentry{':'.$unikey}=
10483: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10484: }
10485: }
10486:
1.261 albertel 10487: sub metadata_generate_part0 {
10488: my ($metadata,$metacache,$uri) = @_;
10489: my %allnames;
1.737 albertel 10490: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10491: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10492: my $part=$$metacache{':'.$metakey.'.part'};
10493: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10494: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10495: $allnames{$name}=$part;
10496: }
10497: }
10498: }
10499: foreach my $name (keys(%allnames)) {
10500: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10501: my $key=":parameter_0_$name";
1.261 albertel 10502: $$metacache{"$key.part"}='0';
10503: $$metacache{"$key.name"}=$name;
1.428 albertel 10504: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10505: $allnames{$name}.'_'.$name.
10506: '.type'};
1.428 albertel 10507: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10508: '.display'};
1.644 www 10509: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10510: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10511: $$metacache{"$key.display"}=$olddis;
10512: }
1.71 www 10513: }
10514:
1.764 albertel 10515: # ------------------------------------------------------ Devalidate title cache
10516:
10517: sub devalidate_title_cache {
10518: my ($url)=@_;
10519: if (!$env{'request.course.id'}) { return; }
10520: my $symb=&symbread($url);
10521: if (!$symb) { return; }
10522: my $key=$env{'request.course.id'}."\0".$symb;
10523: &devalidate_cache_new('title',$key);
10524: }
10525:
1.1014 droeschl 10526: # ------------------------------------------------- Get the title of a course
10527:
10528: sub current_course_title {
10529: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10530: }
1.301 www 10531: # ------------------------------------------------- Get the title of a resource
10532:
10533: sub gettitle {
10534: my $urlsymb=shift;
10535: my $symb=&symbread($urlsymb);
1.534 albertel 10536: if ($symb) {
1.620 albertel 10537: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10538: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10539: if (defined($cached)) {
10540: return $result;
10541: }
1.534 albertel 10542: my ($map,$resid,$url)=&decode_symb($symb);
10543: my $title='';
1.907 albertel 10544: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10545: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10546: } else {
10547: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10548: &GDBM_READER(),0640)) {
10549: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10550: $title=$bighash{'title_'.$mapid.'.'.$resid};
10551: untie(%bighash);
10552: }
1.534 albertel 10553: }
10554: $title=~s/\&colon\;/\:/gs;
10555: if ($title) {
1.1159 www 10556: # Remember both $symb and $title for dynamic metadata
10557: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10558: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10559: # Cache this title and then return it
1.599 albertel 10560: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10561: }
10562: $urlsymb=$url;
10563: }
10564: my $title=&metadata($urlsymb,'title');
10565: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10566: return $title;
1.301 www 10567: }
1.613 albertel 10568:
1.614 albertel 10569: sub get_slot {
10570: my ($which,$cnum,$cdom)=@_;
10571: if (!$cnum || !$cdom) {
1.790 albertel 10572: (undef,my $courseid)=&whichuser();
1.620 albertel 10573: $cdom=$env{'course.'.$courseid.'.domain'};
10574: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10575: }
1.703 albertel 10576: my $key=join("\0",'slots',$cdom,$cnum,$which);
10577: my %slotinfo;
10578: if (exists($remembered{$key})) {
10579: $slotinfo{$which} = $remembered{$key};
10580: } else {
10581: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10582: &Apache::lonhomework::showhash(%slotinfo);
10583: my ($tmp)=keys(%slotinfo);
10584: if ($tmp=~/^error:/) { return (); }
10585: $remembered{$key} = $slotinfo{$which};
10586: }
1.616 albertel 10587: if (ref($slotinfo{$which}) eq 'HASH') {
10588: return %{$slotinfo{$which}};
10589: }
10590: return $slotinfo{$which};
1.614 albertel 10591: }
1.1150 raeburn 10592:
10593: sub get_reservable_slots {
10594: my ($cnum,$cdom,$uname,$udom) = @_;
10595: my $now = time;
10596: my $reservable_info;
10597: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10598: if (exists($remembered{$key})) {
10599: $reservable_info = $remembered{$key};
10600: } else {
10601: my %resv;
10602: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10603: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10604: $reservable_info = \%resv;
10605: $remembered{$key} = $reservable_info;
10606: }
10607: return $reservable_info;
10608: }
10609:
10610: sub get_course_slots {
10611: my ($cnum,$cdom) = @_;
10612: my $hashid=$cnum.':'.$cdom;
10613: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10614: if (defined($cached)) {
10615: if (ref($result) eq 'HASH') {
10616: return %{$result};
10617: }
10618: } else {
10619: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10620: my ($tmp) = keys(%slots);
10621: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10622: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10623: return %slots;
10624: }
10625: }
10626: return;
10627: }
10628:
10629: sub devalidate_slots_cache {
10630: my ($cnum,$cdom)=@_;
10631: my $hashid=$cnum.':'.$cdom;
10632: &devalidate_cache_new('allslots',$hashid);
10633: }
10634:
1.1172.2.8 raeburn 10635: sub get_coursechange {
10636: my ($cdom,$cnum) = @_;
10637: if ($cdom eq '' || $cnum eq '') {
10638: return unless ($env{'request.course.id'});
10639: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10640: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10641: }
10642: my $hashid=$cdom.'_'.$cnum;
10643: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10644: if ((defined($cached)) && ($change ne '')) {
10645: return $change;
10646: } else {
10647: my %crshash;
10648: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10649: if ($crshash{'internal.contentchange'} eq '') {
10650: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10651: if ($change eq '') {
10652: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10653: $change = $crshash{'internal.created'};
10654: }
10655: } else {
10656: $change = $crshash{'internal.contentchange'};
10657: }
10658: my $cachetime = 600;
10659: &do_cache_new('crschange',$hashid,$change,$cachetime);
10660: }
10661: return $change;
10662: }
10663:
10664: sub devalidate_coursechange_cache {
10665: my ($cnum,$cdom)=@_;
10666: my $hashid=$cnum.':'.$cdom;
10667: &devalidate_cache_new('crschange',$hashid);
10668: }
10669:
1.31 www 10670: # ------------------------------------------------- Update symbolic store links
10671:
10672: sub symblist {
10673: my ($mapname,%newhash)=@_;
1.438 www 10674: $mapname=&deversion(&declutter($mapname));
1.31 www 10675: my %hash;
1.620 albertel 10676: if (($env{'request.course.fn'}) && (%newhash)) {
10677: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10678: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10679: foreach my $url (keys(%newhash)) {
1.711 albertel 10680: next if ($url eq 'last_known'
10681: && $env{'form.no_update_last_known'});
10682: $hash{declutter($url)}=&encode_symb($mapname,
10683: $newhash{$url}->[1],
10684: $newhash{$url}->[0]);
1.191 harris41 10685: }
1.31 www 10686: if (untie(%hash)) {
10687: return 'ok';
10688: }
10689: }
10690: }
10691: return 'error';
1.212 www 10692: }
10693:
10694: # --------------------------------------------------------------- Verify a symb
10695:
10696: sub symbverify {
1.1172.2.11 raeburn 10697: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10698: my $thisfn=$thisurl;
1.439 www 10699: $thisfn=&declutter($thisfn);
1.215 www 10700: # direct jump to resource in page or to a sequence - will construct own symbs
10701: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10702: # check URL part
1.409 www 10703: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10704:
1.431 www 10705: unless ($url eq $thisfn) { return 0; }
1.213 www 10706:
1.216 www 10707: $symb=&symbclean($symb);
1.510 www 10708: $thisurl=&deversion($thisurl);
1.439 www 10709: $thisfn=&deversion($thisfn);
1.213 www 10710:
10711: my %bighash;
10712: my $okay=0;
1.431 www 10713:
1.620 albertel 10714: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10715: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10716: my $noclutter;
1.1032 raeburn 10717: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10718: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10719: if ($map =~ m{^uploaded/.+\.page$}) {
10720: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10721: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10722: $noclutter = 1;
10723: }
10724: }
10725: my $ids;
10726: if ($noclutter) {
10727: $ids=$bighash{'ids_'.$thisurl};
10728: } else {
10729: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10730: }
1.1102 raeburn 10731: unless ($ids) {
1.1172.2.13 raeburn 10732: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10733: $ids=$bighash{$idkey};
1.216 www 10734: }
10735: if ($ids) {
10736: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10737: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10738: $symb =~ s/\?.+$//;
10739: }
1.800 albertel 10740: foreach my $id (split(/\,/,$ids)) {
10741: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10742: if (
10743: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10744: eq $symb) {
1.1172.2.11 raeburn 10745: if (ref($encstate)) {
10746: $$encstate = $bighash{'encrypted_'.$id};
10747: }
1.1172.2.13 raeburn 10748: if (($env{'request.role.adv'}) ||
10749: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10750: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10751: $okay=1;
10752: last;
10753: }
10754: }
10755: }
1.216 www 10756: }
1.213 www 10757: untie(%bighash);
10758: }
10759: return $okay;
1.31 www 10760: }
10761:
1.210 www 10762: # --------------------------------------------------------------- Clean-up symb
10763:
10764: sub symbclean {
10765: my $symb=shift;
1.568 albertel 10766: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10767: # remove version from map
10768: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10769:
1.210 www 10770: # remove version from URL
10771: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10772:
1.507 www 10773: # remove wrapper
10774:
1.510 www 10775: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10776: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10777: return $symb;
1.409 www 10778: }
10779:
10780: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10781:
10782: sub encode_symb {
10783: my ($map,$resid,$url)=@_;
10784: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10785: }
1.409 www 10786:
10787: sub decode_symb {
1.568 albertel 10788: my $symb=shift;
10789: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10790: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10791: return (&fixversion($map),$resid,&fixversion($url));
10792: }
10793:
10794: sub fixversion {
10795: my $fn=shift;
1.609 banghart 10796: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10797: my %bighash;
10798: my $uri=&clutter($fn);
1.620 albertel 10799: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10800: # is this cached?
1.599 albertel 10801: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10802: if (defined($cached)) { return $result; }
10803: # unfortunately not cached, or expired
1.620 albertel 10804: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10805: &GDBM_READER(),0640)) {
10806: if ($bighash{'version_'.$uri}) {
10807: my $version=$bighash{'version_'.$uri};
1.444 www 10808: unless (($version eq 'mostrecent') ||
10809: ($version==&getversion($uri))) {
1.440 www 10810: $uri=~s/\.(\w+)$/\.$version\.$1/;
10811: }
10812: }
10813: untie %bighash;
1.413 www 10814: }
1.599 albertel 10815: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10816: }
10817:
10818: sub deversion {
10819: my $url=shift;
10820: $url=~s/\.\d+\.(\w+)$/\.$1/;
10821: return $url;
1.210 www 10822: }
10823:
1.31 www 10824: # ------------------------------------------------------ Return symb list entry
10825:
10826: sub symbread {
1.249 www 10827: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10828: my $cache_str;
10829: if ($thisfn ne '') {
10830: $cache_str='request.symbread.cached.'.$thisfn;
10831: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10832: return $env{$cache_str};
10833: }
1.1172.2.13 raeburn 10834: } else {
1.242 www 10835: # no filename provided? try from environment
1.620 albertel 10836: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10837: return $env{$cache_str}=&symbclean($env{'request.symb'});
10838: }
10839: $thisfn=$env{'request.filename'};
1.44 www 10840: }
1.569 albertel 10841: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10842: # is that filename actually a symb? Verify, clean, and return
10843: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10844: if (&symbverify($thisfn,$1)) {
1.620 albertel 10845: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10846: }
1.242 www 10847: }
1.44 www 10848: $thisfn=declutter($thisfn);
1.31 www 10849: my %hash;
1.37 www 10850: my %bighash;
10851: my $syval='';
1.620 albertel 10852: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10853: my $targetfn = $thisfn;
1.609 banghart 10854: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10855: $targetfn = 'adm/wrapper/'.$thisfn;
10856: }
1.687 albertel 10857: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10858: $targetfn=$1;
10859: }
1.620 albertel 10860: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10861: &GDBM_READER(),0640)) {
1.481 raeburn 10862: $syval=$hash{$targetfn};
1.37 www 10863: untie(%hash);
10864: }
10865: # ---------------------------------------------------------- There was an entry
10866: if ($syval) {
1.601 albertel 10867: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10868: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10869: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10870: #return $env{$cache_str}='';
1.601 albertel 10871: #}
10872: #$syval.=$1;
10873: #}
1.37 www 10874: } else {
10875: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10876: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10877: &GDBM_READER(),0640)) {
1.37 www 10878: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10879: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10880: unless ($ids) {
10881: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10882: }
10883: unless ($ids) {
10884: # alias?
10885: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10886: }
1.37 www 10887: if ($ids) {
10888: # ------------------------------------------------------------------- Has ID(s)
10889: my @possibilities=split(/\,/,$ids);
1.39 www 10890: if ($#possibilities==0) {
10891: # ----------------------------------------------- There is only one possibility
1.37 www 10892: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10893: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10894: $resid,$thisfn);
1.249 www 10895: } elsif (!$donotrecurse) {
1.39 www 10896: # ------------------------------------------ There is more than one possibility
10897: my $realpossible=0;
1.800 albertel 10898: foreach my $id (@possibilities) {
10899: my $file=$bighash{'src_'.$id};
1.39 www 10900: if (&allowed('bre',$file)) {
1.800 albertel 10901: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10902: if ($bighash{'map_type_'.$mapid} ne 'page') {
10903: $realpossible++;
1.626 albertel 10904: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10905: $resid,$thisfn);
1.39 www 10906: }
10907: }
1.191 harris41 10908: }
1.39 www 10909: if ($realpossible!=1) { $syval=''; }
1.249 www 10910: } else {
10911: $syval='';
1.37 www 10912: }
10913: }
10914: untie(%bighash)
1.481 raeburn 10915: }
1.31 www 10916: }
1.62 www 10917: if ($syval) {
1.620 albertel 10918: return $env{$cache_str}=$syval;
1.62 www 10919: }
1.31 www 10920: }
1.949 raeburn 10921: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10922: return $env{$cache_str}='';
1.31 www 10923: }
10924:
10925: # ---------------------------------------------------------- Return random seed
10926:
1.32 www 10927: sub numval {
10928: my $txt=shift;
10929: $txt=~tr/A-J/0-9/;
10930: $txt=~tr/a-j/0-9/;
10931: $txt=~tr/K-T/0-9/;
10932: $txt=~tr/k-t/0-9/;
10933: $txt=~tr/U-Z/0-5/;
10934: $txt=~tr/u-z/0-5/;
10935: $txt=~s/\D//g;
1.564 albertel 10936: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10937: return int($txt);
1.368 albertel 10938: }
10939:
1.484 albertel 10940: sub numval2 {
10941: my $txt=shift;
10942: $txt=~tr/A-J/0-9/;
10943: $txt=~tr/a-j/0-9/;
10944: $txt=~tr/K-T/0-9/;
10945: $txt=~tr/k-t/0-9/;
10946: $txt=~tr/U-Z/0-5/;
10947: $txt=~tr/u-z/0-5/;
10948: $txt=~s/\D//g;
10949: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10950: my $total;
10951: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10952: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10953: return int($total);
10954: }
10955:
1.575 albertel 10956: sub numval3 {
10957: use integer;
10958: my $txt=shift;
10959: $txt=~tr/A-J/0-9/;
10960: $txt=~tr/a-j/0-9/;
10961: $txt=~tr/K-T/0-9/;
10962: $txt=~tr/k-t/0-9/;
10963: $txt=~tr/U-Z/0-5/;
10964: $txt=~tr/u-z/0-5/;
10965: $txt=~s/\D//g;
10966: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10967: my $total;
10968: foreach my $val (@txts) { $total+=$val; }
10969: if ($_64bit) { $total=(($total<<32)>>32); }
10970: return $total;
10971: }
10972:
1.675 albertel 10973: sub digest {
10974: my ($data)=@_;
10975: my $digest=&Digest::MD5::md5($data);
10976: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10977: my ($e,$f);
10978: {
10979: use integer;
10980: $e=($a+$b);
10981: $f=($c+$d);
10982: if ($_64bit) {
10983: $e=(($e<<32)>>32);
10984: $f=(($f<<32)>>32);
10985: }
10986: }
10987: if (wantarray) {
10988: return ($e,$f);
10989: } else {
10990: my $g;
10991: {
10992: use integer;
10993: $g=($e+$f);
10994: if ($_64bit) {
10995: $g=(($g<<32)>>32);
10996: }
10997: }
10998: return $g;
10999: }
11000: }
11001:
1.368 albertel 11002: sub latest_rnd_algorithm_id {
1.675 albertel 11003: return '64bit5';
1.366 albertel 11004: }
1.32 www 11005:
1.503 albertel 11006: sub get_rand_alg {
11007: my ($courseid)=@_;
1.790 albertel 11008: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11009: if ($courseid) {
1.620 albertel 11010: return $env{"course.$courseid.rndseed"};
1.503 albertel 11011: }
11012: return &latest_rnd_algorithm_id();
11013: }
11014:
1.562 albertel 11015: sub validCODE {
11016: my ($CODE)=@_;
11017: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11018: return 0;
11019: }
11020:
1.491 albertel 11021: sub getCODE {
1.620 albertel 11022: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11023: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11024: defined($Apache::lonhomework::parsing_a_task) ) &&
11025: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11026: return $Apache::lonhomework::history{'resource.CODE'};
11027: }
11028: return undef;
11029: }
1.1133 foxr 11030: #
11031: # Determines the random seed for a specific context:
11032: #
11033: # parameters:
11034: # symb - in course context the symb for the seed.
11035: # course_id - The course id of the form domain_coursenum.
11036: # domain - Domain for the user.
11037: # course - Course for the user.
11038: # cenv - environment of the course.
11039: #
11040: # NOTE:
11041: # All parameters are picked out of the environment if missing
11042: # or not defined.
11043: # If a symb cannot be determined the current time is used instead.
11044: #
11045: # For a given well defined symb, courside, domain, username,
11046: # and course environment, the seed is reproducible.
11047: #
1.31 www 11048: sub rndseed {
1.1133 foxr 11049: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11050: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11051: if (!defined($symb)) {
1.366 albertel 11052: unless ($symb=$wsymb) { return time; }
11053: }
1.1146 foxr 11054: if (!defined $courseid) {
11055: $courseid=$wcourseid;
11056: }
11057: if (!defined $domain) { $domain=$wdomain; }
11058: if (!defined $username) { $username=$wusername }
1.1133 foxr 11059:
11060: my $which;
11061: if (defined($cenv->{'rndseed'})) {
11062: $which = $cenv->{'rndseed'};
11063: } else {
11064: $which =&get_rand_alg($courseid);
11065: }
1.491 albertel 11066: if (defined(&getCODE())) {
1.675 albertel 11067: if ($which eq '64bit5') {
11068: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11069: } elsif ($which eq '64bit4') {
1.575 albertel 11070: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11071: } else {
11072: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11073: }
1.675 albertel 11074: } elsif ($which eq '64bit5') {
11075: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11076: } elsif ($which eq '64bit4') {
11077: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11078: } elsif ($which eq '64bit3') {
11079: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11080: } elsif ($which eq '64bit2') {
11081: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11082: } elsif ($which eq '64bit') {
11083: return &rndseed_64bit($symb,$courseid,$domain,$username);
11084: }
11085: return &rndseed_32bit($symb,$courseid,$domain,$username);
11086: }
11087:
11088: sub rndseed_32bit {
11089: my ($symb,$courseid,$domain,$username)=@_;
11090: {
11091: use integer;
11092: my $symbchck=unpack("%32C*",$symb) << 27;
11093: my $symbseed=numval($symb) << 22;
11094: my $namechck=unpack("%32C*",$username) << 17;
11095: my $nameseed=numval($username) << 12;
11096: my $domainseed=unpack("%32C*",$domain) << 7;
11097: my $courseseed=unpack("%32C*",$courseid);
11098: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11100: #&logthis("rndseed :$num:$symb");
1.564 albertel 11101: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11102: return $num;
11103: }
11104: }
11105:
11106: sub rndseed_64bit {
11107: my ($symb,$courseid,$domain,$username)=@_;
11108: {
11109: use integer;
11110: my $symbchck=unpack("%32S*",$symb) << 21;
11111: my $symbseed=numval($symb) << 10;
11112: my $namechck=unpack("%32S*",$username);
11113:
11114: my $nameseed=numval($username) << 21;
11115: my $domainseed=unpack("%32S*",$domain) << 10;
11116: my $courseseed=unpack("%32S*",$courseid);
11117:
11118: my $num1=$symbchck+$symbseed+$namechck;
11119: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11120: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11121: #&logthis("rndseed :$num:$symb");
1.564 albertel 11122: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11123: return "$num1,$num2";
1.155 albertel 11124: }
1.366 albertel 11125: }
11126:
1.443 albertel 11127: sub rndseed_64bit2 {
11128: my ($symb,$courseid,$domain,$username)=@_;
11129: {
11130: use integer;
11131: # strings need to be an even # of cahracters long, it it is odd the
11132: # last characters gets thrown away
11133: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11134: my $symbseed=numval($symb) << 10;
11135: my $namechck=unpack("%32S*",$username.' ');
11136:
11137: my $nameseed=numval($username) << 21;
1.501 albertel 11138: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11139: my $courseseed=unpack("%32S*",$courseid.' ');
11140:
11141: my $num1=$symbchck+$symbseed+$namechck;
11142: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11143: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11144: #&logthis("rndseed :$num:$symb");
1.803 albertel 11145: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11146: return "$num1,$num2";
11147: }
11148: }
11149:
11150: sub rndseed_64bit3 {
11151: my ($symb,$courseid,$domain,$username)=@_;
11152: {
11153: use integer;
11154: # strings need to be an even # of cahracters long, it it is odd the
11155: # last characters gets thrown away
11156: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11157: my $symbseed=numval2($symb) << 10;
11158: my $namechck=unpack("%32S*",$username.' ');
11159:
11160: my $nameseed=numval2($username) << 21;
1.443 albertel 11161: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11162: my $courseseed=unpack("%32S*",$courseid.' ');
11163:
11164: my $num1=$symbchck+$symbseed+$namechck;
11165: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11166: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11167: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11168: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11169:
1.503 albertel 11170: return "$num1:$num2";
1.443 albertel 11171: }
11172: }
11173:
1.575 albertel 11174: sub rndseed_64bit4 {
11175: my ($symb,$courseid,$domain,$username)=@_;
11176: {
11177: use integer;
11178: # strings need to be an even # of cahracters long, it it is odd the
11179: # last characters gets thrown away
11180: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11181: my $symbseed=numval3($symb) << 10;
11182: my $namechck=unpack("%32S*",$username.' ');
11183:
11184: my $nameseed=numval3($username) << 21;
11185: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11186: my $courseseed=unpack("%32S*",$courseid.' ');
11187:
11188: my $num1=$symbchck+$symbseed+$namechck;
11189: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11190: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11191: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11192: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11193:
1.575 albertel 11194: return "$num1:$num2";
11195: }
11196: }
11197:
1.675 albertel 11198: sub rndseed_64bit5 {
11199: my ($symb,$courseid,$domain,$username)=@_;
11200: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11201: return "$num1:$num2";
11202: }
11203:
1.366 albertel 11204: sub rndseed_CODE_64bit {
11205: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11206: {
1.366 albertel 11207: use integer;
1.443 albertel 11208: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11209: my $symbseed=numval2($symb);
1.491 albertel 11210: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11211: my $CODEseed=numval(&getCODE());
1.443 albertel 11212: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11213: my $num1=$symbseed+$CODEchck;
11214: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11215: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11216: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11217: if ($_64bit) { $num1=(($num1<<32)>>32); }
11218: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11219: return "$num1:$num2";
1.366 albertel 11220: }
11221: }
11222:
1.575 albertel 11223: sub rndseed_CODE_64bit4 {
11224: my ($symb,$courseid,$domain,$username)=@_;
11225: {
11226: use integer;
11227: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11228: my $symbseed=numval3($symb);
11229: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11230: my $CODEseed=numval3(&getCODE());
11231: my $courseseed=unpack("%32S*",$courseid.' ');
11232: my $num1=$symbseed+$CODEchck;
11233: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11234: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11235: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11236: if ($_64bit) { $num1=(($num1<<32)>>32); }
11237: if ($_64bit) { $num2=(($num2<<32)>>32); }
11238: return "$num1:$num2";
11239: }
11240: }
11241:
1.675 albertel 11242: sub rndseed_CODE_64bit5 {
11243: my ($symb,$courseid,$domain,$username)=@_;
11244: my $code = &getCODE();
11245: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11246: return "$num1:$num2";
11247: }
11248:
1.366 albertel 11249: sub setup_random_from_rndseed {
11250: my ($rndseed)=@_;
1.503 albertel 11251: if ($rndseed =~/([,:])/) {
11252: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11253: &Math::Random::random_set_seed(abs($num1),abs($num2));
11254: } else {
11255: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11256: }
1.36 albertel 11257: }
11258:
1.474 albertel 11259: sub latest_receipt_algorithm_id {
1.835 albertel 11260: return 'receipt3';
1.474 albertel 11261: }
11262:
1.480 www 11263: sub recunique {
11264: my $fucourseid=shift;
11265: my $unique;
1.835 albertel 11266: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11267: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11268: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11269: } else {
11270: $unique=$perlvar{'lonReceipt'};
11271: }
11272: return unpack("%32C*",$unique);
11273: }
11274:
11275: sub recprefix {
11276: my $fucourseid=shift;
11277: my $prefix;
1.835 albertel 11278: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11279: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11280: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11281: } else {
11282: $prefix=$perlvar{'lonHostID'};
11283: }
11284: return unpack("%32C*",$prefix);
11285: }
11286:
1.76 www 11287: sub ireceipt {
1.474 albertel 11288: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11289:
11290: my $return =&recprefix($fucourseid).'-';
11291:
11292: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11293: $env{'request.state'} eq 'construct') {
11294: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11295: return $return;
11296: }
11297:
1.76 www 11298: my $cuname=unpack("%32C*",$funame);
11299: my $cudom=unpack("%32C*",$fudom);
11300: my $cucourseid=unpack("%32C*",$fucourseid);
11301: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11302: my $cunique=&recunique($fucourseid);
1.474 albertel 11303: my $cpart=unpack("%32S*",$part);
1.835 albertel 11304: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11305:
1.790 albertel 11306: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11307:
11308: $return.= ($cunique%$cuname+
11309: $cunique%$cudom+
11310: $cusymb%$cuname+
11311: $cusymb%$cudom+
11312: $cucourseid%$cuname+
11313: $cucourseid%$cudom+
11314: $cpart%$cuname+
11315: $cpart%$cudom);
11316: } else {
11317: $return.= ($cunique%$cuname+
11318: $cunique%$cudom+
11319: $cusymb%$cuname+
11320: $cusymb%$cudom+
11321: $cucourseid%$cuname+
11322: $cucourseid%$cudom);
11323: }
11324: return $return;
1.76 www 11325: }
11326:
11327: sub receipt {
1.474 albertel 11328: my ($part)=@_;
1.790 albertel 11329: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11330: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11331: }
1.260 ng 11332:
1.790 albertel 11333: sub whichuser {
11334: my ($passedsymb)=@_;
11335: my ($symb,$courseid,$domain,$name,$publicuser);
11336: if (defined($env{'form.grade_symb'})) {
11337: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11338: my $allowed=&allowed('vgr',$tmp_courseid);
11339: if (!$allowed &&
11340: exists($env{'request.course.sec'}) &&
11341: $env{'request.course.sec'} !~ /^\s*$/) {
11342: $allowed=&allowed('vgr',$tmp_courseid.
11343: '/'.$env{'request.course.sec'});
11344: }
11345: if ($allowed) {
11346: ($symb)=&get_env_multiple('form.grade_symb');
11347: $courseid=$tmp_courseid;
11348: ($domain)=&get_env_multiple('form.grade_domain');
11349: ($name)=&get_env_multiple('form.grade_username');
11350: return ($symb,$courseid,$domain,$name,$publicuser);
11351: }
11352: }
11353: if (!$passedsymb) {
11354: $symb=&symbread();
11355: } else {
11356: $symb=$passedsymb;
11357: }
11358: $courseid=$env{'request.course.id'};
11359: $domain=$env{'user.domain'};
11360: $name=$env{'user.name'};
11361: if ($name eq 'public' && $domain eq 'public') {
11362: if (!defined($env{'form.username'})) {
11363: $env{'form.username'}.=time.rand(10000000);
11364: }
11365: $name.=$env{'form.username'};
11366: }
11367: return ($symb,$courseid,$domain,$name,$publicuser);
11368:
11369: }
11370:
1.36 albertel 11371: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11372: # returns either the contents of the file or
11373: # -1 if the file doesn't exist
1.481 raeburn 11374: #
11375: # if the target is a file that was uploaded via DOCS,
11376: # a check will be made to see if a current copy exists on the local server,
11377: # if it does this will be served, otherwise a copy will be retrieved from
11378: # the home server for the course and stored in /home/httpd/html/userfiles on
11379: # the local server.
1.472 albertel 11380:
1.36 albertel 11381: sub getfile {
1.538 albertel 11382: my ($file) = @_;
1.609 banghart 11383: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11384: &repcopy($file);
11385: return &readfile($file);
11386: }
11387:
11388: sub repcopy_userfile {
11389: my ($file)=@_;
1.1142 raeburn 11390: my $londocroot = $perlvar{'lonDocRoot'};
11391: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11392: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11393: my ($cdom,$cnum,$filename) =
1.811 albertel 11394: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11395: my $uri="/uploaded/$cdom/$cnum/$filename";
11396: if (-e "$file") {
1.828 www 11397: # we already have a local copy, check it out
1.538 albertel 11398: my @fileinfo = stat($file);
1.828 www 11399: my $rtncode;
11400: my $info;
1.538 albertel 11401: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11402: if ($lwpresp ne 'ok') {
1.828 www 11403: # there is no such file anymore, even though we had a local copy
1.482 albertel 11404: if ($rtncode eq '404') {
1.538 albertel 11405: unlink($file);
1.482 albertel 11406: }
11407: return -1;
11408: }
11409: if ($info < $fileinfo[9]) {
1.828 www 11410: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11411: return 'ok';
1.828 www 11412: } else {
11413: # the file is outdated, get rid of it
11414: unlink($file);
1.482 albertel 11415: }
1.828 www 11416: }
11417: # one way or the other, at this point, we don't have the file
11418: # construct the correct path for the file
11419: my @parts = ($cdom,$cnum);
11420: if ($filename =~ m|^(.+)/[^/]+$|) {
11421: push @parts, split(/\//,$1);
11422: }
11423: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11424: foreach my $part (@parts) {
11425: $path .= '/'.$part;
11426: if (!-e $path) {
11427: mkdir($path,0770);
1.482 albertel 11428: }
11429: }
1.828 www 11430: # now the path exists for sure
11431: # get a user agent
11432: my $ua=new LWP::UserAgent;
11433: my $transferfile=$file.'.in.transfer';
11434: # FIXME: this should flock
11435: if (-e $transferfile) { return 'ok'; }
11436: my $request;
11437: $uri=~s/^\///;
1.980 raeburn 11438: my $homeserver = &homeserver($cnum,$cdom);
11439: my $protocol = $protocol{$homeserver};
11440: $protocol = 'http' if ($protocol ne 'https');
11441: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11442: my $response=$ua->request($request,$transferfile);
11443: # did it work?
11444: if ($response->is_error()) {
11445: unlink($transferfile);
11446: &logthis("Userfile repcopy failed for $uri");
11447: return -1;
11448: }
11449: # worked, rename the transfer file
11450: rename($transferfile,$file);
1.607 raeburn 11451: return 'ok';
1.481 raeburn 11452: }
11453:
1.517 albertel 11454: sub tokenwrapper {
11455: my $uri=shift;
1.980 raeburn 11456: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11457: $uri=~s|^/||;
1.620 albertel 11458: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11459: my $token=$1;
1.552 albertel 11460: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11461: if ($udom && $uname && $file) {
11462: $file=~s|(\?\.*)*$||;
1.949 raeburn 11463: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11464: my $homeserver = &homeserver($uname,$udom);
11465: my $protocol = $protocol{$homeserver};
11466: $protocol = 'http' if ($protocol ne 'https');
11467: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11468: (($uri=~/\?/)?'&':'?').'token='.$token.
11469: '&tokenissued='.$perlvar{'lonHostID'};
11470: } else {
11471: return '/adm/notfound.html';
11472: }
11473: }
11474:
1.828 www 11475: # call with reqtype HEAD: get last modification time
11476: # call with reqtype GET: get the file contents
11477: # Do not call this with reqtype GET for large files! It loads everything into memory
11478: #
1.481 raeburn 11479: sub getuploaded {
11480: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11481: $uri=~s/^\///;
1.980 raeburn 11482: my $homeserver = &homeserver($cnum,$cdom);
11483: my $protocol = $protocol{$homeserver};
11484: $protocol = 'http' if ($protocol ne 'https');
11485: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11486: my $ua=new LWP::UserAgent;
11487: my $request=new HTTP::Request($reqtype,$uri);
11488: my $response=$ua->request($request);
11489: $$rtncode = $response->code;
1.482 albertel 11490: if (! $response->is_success()) {
11491: return 'failed';
11492: }
11493: if ($reqtype eq 'HEAD') {
1.486 www 11494: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11495: } elsif ($reqtype eq 'GET') {
11496: $$info = $response->content;
1.472 albertel 11497: }
1.482 albertel 11498: return 'ok';
1.36 albertel 11499: }
11500:
1.481 raeburn 11501: sub readfile {
11502: my $file = shift;
11503: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11504: my $fh;
11505: open($fh,"<$file");
11506: my $a='';
1.800 albertel 11507: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11508: return $a;
11509: }
11510:
1.36 albertel 11511: sub filelocation {
1.590 banghart 11512: my ($dir,$file) = @_;
11513: my $location;
11514: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11515:
11516: if ($file =~ m-^/adm/-) {
11517: $file=~s-^/adm/wrapper/-/-;
11518: $file=~s-^/adm/coursedocs/showdoc/-/-;
11519: }
1.882 albertel 11520:
1.1139 www 11521: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11522: $location = $file;
1.609 banghart 11523: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11524: my ($udom,$uname,$filename)=
1.811 albertel 11525: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11526: my $home=&homeserver($uname,$udom);
11527: my $is_me=0;
11528: my @ids=¤t_machine_ids();
11529: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11530: if ($is_me) {
1.1117 foxr 11531: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11532: } else {
11533: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11534: $udom.'/'.$uname.'/'.$filename;
11535: }
1.882 albertel 11536: } elsif ($file =~ m-^/adm/-) {
11537: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11538: } else {
11539: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11540: $file=~s:^/(res|priv)/:/:;
11541: my $space=$1;
1.590 banghart 11542: if ( !( $file =~ m:^/:) ) {
11543: $location = $dir. '/'.$file;
11544: } else {
1.1142 raeburn 11545: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11546: }
1.59 albertel 11547: }
1.590 banghart 11548: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11549: while ($location=~m{/\.\./}) {
11550: if ($location =~ m{/[^/]+/\.\./}) {
11551: $location=~ s{/[^/]+/\.\./}{/}g;
11552: } else {
11553: $location=~ s{/\.\./}{/}g;
11554: }
11555: } #remove dir/..
1.590 banghart 11556: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11557: return $location;
1.46 www 11558: }
1.36 albertel 11559:
1.46 www 11560: sub hreflocation {
11561: my ($dir,$file)=@_;
1.980 raeburn 11562: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11563: $file=filelocation($dir,$file);
1.700 albertel 11564: } elsif ($file=~m-^/adm/-) {
11565: $file=~s-^/adm/wrapper/-/-;
11566: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11567: }
11568: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11569: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11570: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11571: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11572: {/uploaded/$1/$2/}x;
1.46 www 11573: }
1.913 albertel 11574: if ($file=~ m{^/userfiles/}) {
11575: $file =~ s{^/userfiles/}{/uploaded/};
11576: }
1.462 albertel 11577: return $file;
1.465 albertel 11578: }
11579:
1.1139 www 11580:
11581:
11582:
11583:
1.465 albertel 11584: sub current_machine_domains {
1.853 albertel 11585: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11586: }
11587:
11588: sub machine_domains {
11589: my ($hostname) = @_;
1.465 albertel 11590: my @domains;
1.838 albertel 11591: my %hostname = &all_hostnames();
1.465 albertel 11592: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11593: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11594: if ($hostname eq $name) {
1.844 albertel 11595: push(@domains,&host_domain($id));
1.465 albertel 11596: }
11597: }
11598: return @domains;
11599: }
11600:
11601: sub current_machine_ids {
1.853 albertel 11602: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11603: }
11604:
11605: sub machine_ids {
11606: my ($hostname) = @_;
11607: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11608: my @ids;
1.888 albertel 11609: my %name_to_host = &all_names();
1.889 albertel 11610: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11611: return @{ $name_to_host{$hostname} };
11612: }
11613: return;
1.31 www 11614: }
11615:
1.824 raeburn 11616: sub additional_machine_domains {
11617: my @domains;
11618: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11619: while( my $line = <$fh>) {
11620: $line =~ s/\s//g;
11621: push(@domains,$line);
11622: }
11623: return @domains;
11624: }
11625:
11626: sub default_login_domain {
11627: my $domain = $perlvar{'lonDefDomain'};
11628: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11629: foreach my $posdom (¤t_machine_domains(),
11630: &additional_machine_domains()) {
11631: if (lc($posdom) eq lc($testdomain)) {
11632: $domain=$posdom;
11633: last;
11634: }
11635: }
11636: return $domain;
11637: }
11638:
1.31 www 11639: # ------------------------------------------------------------- Declutters URLs
11640:
11641: sub declutter {
11642: my $thisfn=shift;
1.569 albertel 11643: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11644: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11645: $thisfn=~s/^\///;
1.697 albertel 11646: $thisfn=~s|^adm/wrapper/||;
11647: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11648: $thisfn=~s/^res\///;
1.1172 bisitz 11649: $thisfn=~s/^priv\///;
1.1032 raeburn 11650: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11651: $thisfn=~s/\?.+$//;
11652: }
1.268 www 11653: return $thisfn;
11654: }
11655:
11656: # ------------------------------------------------------------- Clutter up URLs
11657:
11658: sub clutter {
11659: my $thisfn='/'.&declutter(shift);
1.887 albertel 11660: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11661: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11662: $thisfn='/res'.$thisfn;
11663: }
1.1031 raeburn 11664: if ($thisfn !~m|^/adm|) {
11665: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11666: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11667: } else {
11668: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11669: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11670: if ($embstyle eq 'ssi'
11671: || ($embstyle eq 'hdn')
11672: || ($embstyle eq 'rat')
11673: || ($embstyle eq 'prv')
11674: || ($embstyle eq 'ign')) {
11675: #do nothing with these
11676: } elsif (($embstyle eq 'img')
1.695 albertel 11677: || ($embstyle eq 'emb')
11678: || ($embstyle eq 'wrp')) {
11679: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11680: } elsif ($embstyle eq 'unk'
11681: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11682: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11683: } else {
1.718 www 11684: # &logthis("Got a blank emb style");
1.695 albertel 11685: }
1.694 albertel 11686: }
11687: }
1.31 www 11688: return $thisfn;
1.12 www 11689: }
11690:
1.787 albertel 11691: sub clutter_with_no_wrapper {
11692: my $uri = &clutter(shift);
11693: if ($uri =~ m-^/adm/-) {
11694: $uri =~ s-^/adm/wrapper/-/-;
11695: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11696: }
11697: return $uri;
11698: }
11699:
1.557 albertel 11700: sub freeze_escape {
11701: my ($value)=@_;
11702: if (ref($value)) {
11703: $value=&nfreeze($value);
11704: return '__FROZEN__'.&escape($value);
11705: }
11706: return &escape($value);
11707: }
11708:
1.11 www 11709:
1.557 albertel 11710: sub thaw_unescape {
11711: my ($value)=@_;
11712: if ($value =~ /^__FROZEN__/) {
11713: substr($value,0,10,undef);
11714: $value=&unescape($value);
11715: return &thaw($value);
11716: }
11717: return &unescape($value);
11718: }
11719:
1.436 albertel 11720: sub correct_line_ends {
11721: my ($result)=@_;
11722: $$result =~s/\r\n/\n/mg;
11723: $$result =~s/\r/\n/mg;
1.415 albertel 11724: }
1.1 albertel 11725: # ================================================================ Main Program
11726:
1.184 www 11727: sub goodbye {
1.204 albertel 11728: &logthis("Starting Shut down");
1.443 albertel 11729: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11730: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11731: #converted
1.599 albertel 11732: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11733: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11734: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11735: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11736: #1.1 only
1.870 albertel 11737: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11738: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11739: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11740: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11741: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11742: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11743: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11744: &flushcourselogs();
11745: &logthis("Shutting down");
11746: }
11747:
1.852 albertel 11748: sub get_dns {
1.1172.2.17 raeburn 11749: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11750: if (!$ignore_cache) {
11751: my ($content,$cached)=
11752: &Apache::lonnet::is_cached_new('dns',$url);
11753: if ($cached) {
1.1172.2.17 raeburn 11754: &$func($content,$hashref);
1.869 albertel 11755: return;
11756: }
11757: }
11758:
11759: my %alldns;
1.852 albertel 11760: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11761: foreach my $dns (<$config>) {
11762: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11763: my $line = $1;
11764: my ($host,$protocol) = split(/:/,$line);
11765: if ($protocol ne 'https') {
11766: $protocol = 'http';
11767: }
11768: $alldns{$host} = $protocol;
1.869 albertel 11769: }
11770: while (%alldns) {
11771: my ($dns) = keys(%alldns);
1.852 albertel 11772: my $ua=new LWP::UserAgent;
1.1134 raeburn 11773: $ua->timeout(30);
1.979 raeburn 11774: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11775: my $response=$ua->request($request);
1.979 raeburn 11776: delete($alldns{$dns});
1.852 albertel 11777: next if ($response->is_error());
11778: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11779: unless ($nocache) {
1.1172.2.23 raeburn 11780: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11781: }
11782: &$func(\@content,$hashref);
1.869 albertel 11783: return;
1.852 albertel 11784: }
11785: close($config);
1.871 albertel 11786: my $which = (split('/',$url))[3];
11787: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11788: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11789: my @content = <$config>;
1.1172.2.17 raeburn 11790: &$func(\@content,$hashref);
11791: return;
11792: }
11793:
11794: # ------------------------------------------------------Get DNS checksums file
11795: sub parse_dns_checksums_tab {
11796: my ($lines,$hashref) = @_;
11797: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11798: my $loncaparev = &get_server_loncaparev($machine_dom);
11799: my ($release,$timestamp) = split(/\-/,$loncaparev);
11800: my (%chksum,%revnum);
11801: if (ref($lines) eq 'ARRAY') {
11802: chomp(@{$lines});
1.1172.2.34 raeburn 11803: my $version = shift(@{$lines});
11804: if ($version eq $release) {
1.1172.2.17 raeburn 11805: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11806: my ($file,$version,$shasum) = split(/,/,$line);
11807: $chksum{$file} = $shasum;
11808: $revnum{$file} = $version;
1.1172.2.17 raeburn 11809: }
11810: if (ref($hashref) eq 'HASH') {
11811: %{$hashref} = (
11812: sums => \%chksum,
11813: versions => \%revnum,
11814: );
11815: }
11816: }
11817: }
1.869 albertel 11818: return;
1.852 albertel 11819: }
1.1172.2.17 raeburn 11820:
11821: sub fetch_dns_checksums {
11822: my %checksums;
1.1172.2.34 raeburn 11823: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11824: my $loncaparev = &get_server_loncaparev($machine_dom);
11825: my ($release,$timestamp) = split(/\-/,$loncaparev);
11826: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11827: \%checksums);
11828: return \%checksums;
11829: }
11830:
1.327 albertel 11831: # ------------------------------------------------------------ Read domain file
11832: {
1.852 albertel 11833: my $loaded;
1.846 albertel 11834: my %domain;
11835:
1.852 albertel 11836: sub parse_domain_tab {
11837: my ($lines) = @_;
11838: foreach my $line (@$lines) {
11839: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11840:
1.846 albertel 11841: chomp($line);
1.852 albertel 11842: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11843: my %this_domain;
11844: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11845: 'lang_def', 'city', 'longi', 'lati',
11846: 'primary') {
11847: $this_domain{$field} = shift(@elements);
11848: }
11849: $domain{$name} = \%this_domain;
1.852 albertel 11850: }
11851: }
1.864 albertel 11852:
11853: sub reset_domain_info {
11854: undef($loaded);
11855: undef(%domain);
11856: }
11857:
1.852 albertel 11858: sub load_domain_tab {
1.869 albertel 11859: my ($ignore_cache) = @_;
11860: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11861: my $fh;
11862: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11863: my @lines = <$fh>;
11864: &parse_domain_tab(\@lines);
1.448 albertel 11865: }
1.852 albertel 11866: close($fh);
11867: $loaded = 1;
1.327 albertel 11868: }
1.846 albertel 11869:
11870: sub domain {
1.852 albertel 11871: &load_domain_tab() if (!$loaded);
11872:
1.846 albertel 11873: my ($name,$what) = @_;
11874: return if ( !exists($domain{$name}) );
11875:
11876: if (!$what) {
11877: return $domain{$name}{'description'};
11878: }
11879: return $domain{$name}{$what};
11880: }
1.974 raeburn 11881:
11882: sub domain_info {
11883: &load_domain_tab() if (!$loaded);
11884: return %domain;
11885: }
11886:
1.327 albertel 11887: }
11888:
11889:
1.1 albertel 11890: # ------------------------------------------------------------- Read hosts file
11891: {
1.838 albertel 11892: my %hostname;
1.844 albertel 11893: my %hostdom;
1.845 albertel 11894: my %libserv;
1.852 albertel 11895: my $loaded;
1.888 albertel 11896: my %name_to_host;
1.1074 raeburn 11897: my %internetdom;
1.1107 raeburn 11898: my %LC_dns_serv;
1.852 albertel 11899:
11900: sub parse_hosts_tab {
11901: my ($file) = @_;
11902: foreach my $configline (@$file) {
11903: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11904: chomp($configline);
11905: if ($configline =~ /^\^/) {
11906: if ($configline =~ /^\^([\w.\-]+)/) {
11907: $LC_dns_serv{$1} = 1;
11908: }
11909: next;
11910: }
1.1074 raeburn 11911: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11912: $name=~s/\s//g;
11913: if ($id && $domain && $role && $name) {
11914: $hostname{$id}=$name;
1.888 albertel 11915: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11916: $hostdom{$id}=$domain;
11917: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11918: if (defined($protocol)) {
11919: if ($protocol eq 'https') {
11920: $protocol{$id} = $protocol;
11921: } else {
11922: $protocol{$id} = 'http';
11923: }
1.968 raeburn 11924: } else {
1.969 raeburn 11925: $protocol{$id} = 'http';
1.968 raeburn 11926: }
1.1074 raeburn 11927: if (defined($intdom)) {
11928: $internetdom{$id} = $intdom;
11929: }
1.852 albertel 11930: }
11931: }
11932: }
1.864 albertel 11933:
11934: sub reset_hosts_info {
1.897 albertel 11935: &purge_remembered();
1.864 albertel 11936: &reset_domain_info();
11937: &reset_hosts_ip_info();
1.892 albertel 11938: undef(%name_to_host);
1.864 albertel 11939: undef(%hostname);
11940: undef(%hostdom);
11941: undef(%libserv);
11942: undef($loaded);
11943: }
1.1 albertel 11944:
1.852 albertel 11945: sub load_hosts_tab {
1.869 albertel 11946: my ($ignore_cache) = @_;
11947: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11948: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11949: my @config = <$config>;
11950: &parse_hosts_tab(\@config);
11951: close($config);
11952: $loaded=1;
1.1 albertel 11953: }
1.852 albertel 11954:
1.838 albertel 11955: sub hostname {
1.852 albertel 11956: &load_hosts_tab() if (!$loaded);
11957:
1.838 albertel 11958: my ($lonid) = @_;
11959: return $hostname{$lonid};
11960: }
1.845 albertel 11961:
1.838 albertel 11962: sub all_hostnames {
1.852 albertel 11963: &load_hosts_tab() if (!$loaded);
11964:
1.838 albertel 11965: return %hostname;
11966: }
1.845 albertel 11967:
1.888 albertel 11968: sub all_names {
11969: &load_hosts_tab() if (!$loaded);
11970:
11971: return %name_to_host;
11972: }
11973:
1.974 raeburn 11974: sub all_host_domain {
11975: &load_hosts_tab() if (!$loaded);
11976: return %hostdom;
11977: }
11978:
1.845 albertel 11979: sub is_library {
1.852 albertel 11980: &load_hosts_tab() if (!$loaded);
11981:
1.845 albertel 11982: return exists($libserv{$_[0]});
11983: }
11984:
11985: sub all_library {
1.852 albertel 11986: &load_hosts_tab() if (!$loaded);
11987:
1.845 albertel 11988: return %libserv;
11989: }
11990:
1.1062 droeschl 11991: sub unique_library {
11992: #2x reverse removes all hostnames that appear more than once
11993: my %unique = reverse &all_library();
11994: return reverse %unique;
11995: }
11996:
1.841 albertel 11997: sub get_servers {
1.852 albertel 11998: &load_hosts_tab() if (!$loaded);
11999:
1.841 albertel 12000: my ($domain,$type) = @_;
12001: my %possible_hosts = ($type eq 'library') ? %libserv
12002: : %hostname;
12003: my %result;
1.842 albertel 12004: if (ref($domain) eq 'ARRAY') {
12005: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12006: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12007: $result{$host} = $hostname;
12008: }
12009: }
12010: } else {
12011: while ( my ($host,$hostname) = each(%possible_hosts)) {
12012: if ($hostdom{$host} eq $domain) {
12013: $result{$host} = $hostname;
12014: }
1.841 albertel 12015: }
12016: }
12017: return %result;
12018: }
1.845 albertel 12019:
1.1062 droeschl 12020: sub get_unique_servers {
12021: my %unique = reverse &get_servers(@_);
12022: return reverse %unique;
12023: }
12024:
1.844 albertel 12025: sub host_domain {
1.852 albertel 12026: &load_hosts_tab() if (!$loaded);
12027:
1.844 albertel 12028: my ($lonid) = @_;
12029: return $hostdom{$lonid};
12030: }
12031:
1.841 albertel 12032: sub all_domains {
1.852 albertel 12033: &load_hosts_tab() if (!$loaded);
12034:
1.841 albertel 12035: my %seen;
12036: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12037: return @uniq;
12038: }
1.1074 raeburn 12039:
12040: sub internet_dom {
12041: &load_hosts_tab() if (!$loaded);
12042:
12043: my ($lonid) = @_;
12044: return $internetdom{$lonid};
12045: }
1.1107 raeburn 12046:
12047: sub is_LC_dns {
12048: &load_hosts_tab() if (!$loaded);
12049:
12050: my ($hostname) = @_;
12051: return exists($LC_dns_serv{$hostname});
12052: }
12053:
1.1 albertel 12054: }
12055:
1.847 albertel 12056: {
12057: my %iphost;
1.856 albertel 12058: my %name_to_ip;
12059: my %lonid_to_ip;
1.869 albertel 12060:
1.847 albertel 12061: sub get_hosts_from_ip {
12062: my ($ip) = @_;
12063: my %iphosts = &get_iphost();
12064: if (ref($iphosts{$ip})) {
12065: return @{$iphosts{$ip}};
12066: }
12067: return;
1.839 albertel 12068: }
1.864 albertel 12069:
12070: sub reset_hosts_ip_info {
12071: undef(%iphost);
12072: undef(%name_to_ip);
12073: undef(%lonid_to_ip);
12074: }
1.856 albertel 12075:
12076: sub get_host_ip {
12077: my ($lonid) = @_;
12078: if (exists($lonid_to_ip{$lonid})) {
12079: return $lonid_to_ip{$lonid};
12080: }
12081: my $name=&hostname($lonid);
12082: my $ip = gethostbyname($name);
12083: return if (!$ip || length($ip) ne 4);
12084: $ip=inet_ntoa($ip);
12085: $name_to_ip{$name} = $ip;
12086: $lonid_to_ip{$lonid} = $ip;
12087: return $ip;
12088: }
1.847 albertel 12089:
12090: sub get_iphost {
1.869 albertel 12091: my ($ignore_cache) = @_;
1.894 albertel 12092:
1.869 albertel 12093: if (!$ignore_cache) {
12094: if (%iphost) {
12095: return %iphost;
12096: }
12097: my ($ip_info,$cached)=
12098: &Apache::lonnet::is_cached_new('iphost','iphost');
12099: if ($cached) {
12100: %iphost = %{$ip_info->[0]};
12101: %name_to_ip = %{$ip_info->[1]};
12102: %lonid_to_ip = %{$ip_info->[2]};
12103: return %iphost;
12104: }
12105: }
1.894 albertel 12106:
12107: # get yesterday's info for fallback
12108: my %old_name_to_ip;
12109: my ($ip_info,$cached)=
12110: &Apache::lonnet::is_cached_new('iphost','iphost');
12111: if ($cached) {
12112: %old_name_to_ip = %{$ip_info->[1]};
12113: }
12114:
1.888 albertel 12115: my %name_to_host = &all_names();
12116: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12117: my $ip;
12118: if (!exists($name_to_ip{$name})) {
12119: $ip = gethostbyname($name);
12120: if (!$ip || length($ip) ne 4) {
1.894 albertel 12121: if (defined($old_name_to_ip{$name})) {
12122: $ip = $old_name_to_ip{$name};
12123: &logthis("Can't find $name defaulting to old $ip");
12124: } else {
12125: &logthis("Name $name no IP found");
12126: next;
12127: }
12128: } else {
12129: $ip=inet_ntoa($ip);
1.847 albertel 12130: }
12131: $name_to_ip{$name} = $ip;
12132: } else {
12133: $ip = $name_to_ip{$name};
1.653 albertel 12134: }
1.888 albertel 12135: foreach my $id (@{ $name_to_host{$name} }) {
12136: $lonid_to_ip{$id} = $ip;
12137: }
12138: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12139: }
1.1172.2.23 raeburn 12140: &do_cache_new('iphost','iphost',
12141: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12142: 48*60*60);
1.869 albertel 12143:
1.847 albertel 12144: return %iphost;
1.598 albertel 12145: }
12146:
1.992 raeburn 12147: #
12148: # Given a DNS returns the loncapa host name for that DNS
12149: #
12150: sub host_from_dns {
12151: my ($dns) = @_;
12152: my @hosts;
12153: my $ip;
12154:
1.993 raeburn 12155: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12156: $ip = $name_to_ip{$dns};
12157: }
12158: if (!$ip) {
12159: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12160: if (length($ip) == 4) {
12161: $ip = &IO::Socket::inet_ntoa($ip);
12162: }
12163: }
12164: if ($ip) {
12165: @hosts = get_hosts_from_ip($ip);
12166: return $hosts[0];
12167: }
12168: return undef;
1.986 foxr 12169: }
1.992 raeburn 12170:
1.1074 raeburn 12171: sub get_internet_names {
12172: my ($lonid) = @_;
12173: return if ($lonid eq '');
12174: my ($idnref,$cached)=
12175: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12176: if ($cached) {
12177: return $idnref;
12178: }
12179: my $ip = &get_host_ip($lonid);
12180: my @hosts = &get_hosts_from_ip($ip);
12181: my %iphost = &get_iphost();
12182: my (@idns,%seen);
12183: foreach my $id (@hosts) {
12184: my $dom = &host_domain($id);
12185: my $prim_id = &domain($dom,'primary');
12186: my $prim_ip = &get_host_ip($prim_id);
12187: next if ($seen{$prim_ip});
12188: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12189: foreach my $id (@{$iphost{$prim_ip}}) {
12190: my $intdom = &internet_dom($id);
12191: unless (grep(/^\Q$intdom\E$/,@idns)) {
12192: push(@idns,$intdom);
12193: }
12194: }
12195: }
12196: $seen{$prim_ip} = 1;
12197: }
1.1172.2.23 raeburn 12198: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12199: }
12200:
1.986 foxr 12201: }
12202:
1.1079 raeburn 12203: sub all_loncaparevs {
12204: 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);
12205: }
12206:
1.1172.2.27 raeburn 12207: # ------------------------------------------------------- Read loncaparev table
12208: {
12209: sub load_loncaparevs {
12210: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12211: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12212: while (my $configline=<$config>) {
12213: chomp($configline);
12214: my ($hostid,$loncaparev)=split(/:/,$configline);
12215: $loncaparevs{$hostid}=$loncaparev;
12216: }
12217: close($config);
12218: }
12219: }
12220: }
12221: }
12222:
12223: # ----------------------------------------------------- Read serverhostID table
12224: {
12225: sub load_serverhomeIDs {
12226: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12227: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12228: while (my $configline=<$config>) {
12229: chomp($configline);
12230: my ($name,$id)=split(/:/,$configline);
12231: $serverhomeIDs{$name}=$id;
12232: }
12233: close($config);
12234: }
12235: }
12236: }
12237: }
12238:
12239:
1.862 albertel 12240: BEGIN {
12241:
12242: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12243: unless ($readit) {
12244: {
12245: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12246: %perlvar = (%perlvar,%{$configvars});
12247: }
12248:
12249:
1.1 albertel 12250: # ------------------------------------------------------ Read spare server file
12251: {
1.448 albertel 12252: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12253:
12254: while (my $configline=<$config>) {
12255: chomp($configline);
1.284 matthew 12256: if ($configline) {
1.784 albertel 12257: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12258: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12259: push(@{ $spareid{$type} }, $host);
1.1 albertel 12260: }
12261: }
1.448 albertel 12262: close($config);
1.1 albertel 12263: }
1.11 www 12264: # ------------------------------------------------------------ Read permissions
12265: {
1.448 albertel 12266: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12267:
12268: while (my $configline=<$config>) {
1.448 albertel 12269: chomp($configline);
12270: if ($configline) {
12271: my ($role,$perm)=split(/ /,$configline);
12272: if ($perm ne '') { $pr{$role}=$perm; }
12273: }
1.11 www 12274: }
1.448 albertel 12275: close($config);
1.11 www 12276: }
12277:
12278: # -------------------------------------------- Read plain texts for permissions
12279: {
1.448 albertel 12280: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12281:
12282: while (my $configline=<$config>) {
1.448 albertel 12283: chomp($configline);
12284: if ($configline) {
1.742 raeburn 12285: my ($short,@plain)=split(/:/,$configline);
12286: %{$prp{$short}} = ();
12287: if (@plain > 0) {
12288: $prp{$short}{'std'} = $plain[0];
12289: for (my $i=1; $i<@plain; $i++) {
12290: $prp{$short}{'alt'.$i} = $plain[$i];
12291: }
12292: }
1.448 albertel 12293: }
1.135 www 12294: }
1.448 albertel 12295: close($config);
1.135 www 12296: }
12297:
12298: # ---------------------------------------------------------- Read package table
12299: {
1.448 albertel 12300: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12301:
12302: while (my $configline=<$config>) {
1.483 albertel 12303: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12304: chomp($configline);
12305: my ($short,$plain)=split(/:/,$configline);
12306: my ($pack,$name)=split(/\&/,$short);
12307: if ($plain ne '') {
12308: $packagetab{$pack.'&'.$name.'&name'}=$name;
12309: $packagetab{$short}=$plain;
12310: }
1.11 www 12311: }
1.448 albertel 12312: close($config);
1.329 matthew 12313: }
12314:
1.1172.2.27 raeburn 12315: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12316:
1.1172.2.27 raeburn 12317: &load_loncaparevs();
12318:
12319: # ------------------------------------------------------- Read serverhostID table
12320:
12321: &load_serverhomeIDs();
1.1074 raeburn 12322:
1.1172.2.27 raeburn 12323: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12324: {
12325: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12326: if (-e $file) {
12327: my $parser = HTML::LCParser->new($file);
12328: while (my $token = $parser->get_token()) {
12329: if ($token->[0] eq 'S') {
12330: my $item = $token->[1];
12331: my $name = $token->[2]{'name'};
12332: my $value = $token->[2]{'value'};
12333: if ($item ne '' && $name ne '' && $value ne '') {
12334: my $release = $parser->get_text();
12335: $release =~ s/(^\s*|\s*$ )//gx;
12336: $needsrelease{$item.':'.$name.':'.$value} = $release;
12337: }
12338: }
12339: }
12340: }
1.1073 raeburn 12341: }
12342:
1.1138 raeburn 12343: # ---------------------------------------------------------- Read managers table
12344: {
12345: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12346: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12347: while (my $configline=<$config>) {
12348: chomp($configline);
12349: next if ($configline =~ /^\#/);
12350: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12351: $managerstab{$configline} = 1;
12352: }
12353: }
12354: close($config);
12355: }
12356: }
12357: }
12358:
1.329 matthew 12359: # ------------- set up temporary directory
12360: {
1.1117 foxr 12361: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12362:
1.11 www 12363: }
12364:
1.794 albertel 12365: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12366: 'compress_threshold'=> 20_000,
12367: });
1.185 www 12368:
1.281 www 12369: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12370: $dumpcount=0;
1.958 www 12371: $locknum=0;
1.22 www 12372:
1.163 harris41 12373: &logtouch();
1.672 albertel 12374: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12375: $readit=1;
1.564 albertel 12376: {
12377: use integer;
12378: my $test=(2**32)+1;
1.568 albertel 12379: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12380: &logthis(" Detected 64bit platform ($_64bit)");
12381: }
1.195 www 12382: }
1.1 albertel 12383: }
1.179 www 12384:
1.1 albertel 12385: 1;
1.191 harris41 12386: __END__
12387:
1.243 albertel 12388: =pod
12389:
1.191 harris41 12390: =head1 NAME
12391:
1.243 albertel 12392: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12393:
12394: =head1 SYNOPSIS
12395:
1.243 albertel 12396: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12397:
12398: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12399:
1.243 albertel 12400: Common parameters:
12401:
12402: =over 4
12403:
12404: =item *
12405:
12406: $uname : an internal username (if $cname expecting a course Id specifically)
12407:
12408: =item *
12409:
12410: $udom : a domain (if $cdom expecting a course's domain specifically)
12411:
12412: =item *
12413:
12414: $symb : a resource instance identifier
12415:
12416: =item *
12417:
12418: $namespace : the name of a .db file that contains the data needed or
12419: being set.
12420:
12421: =back
12422:
1.394 bowersj2 12423: =head1 OVERVIEW
1.191 harris41 12424:
1.394 bowersj2 12425: lonnet provides subroutines which interact with the
12426: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12427: about classes, users, and resources.
1.243 albertel 12428:
12429: For many of these objects you can also use this to store data about
12430: them or modify them in various ways.
1.191 harris41 12431:
1.394 bowersj2 12432: =head2 Symbs
1.191 harris41 12433:
1.394 bowersj2 12434: To identify a specific instance of a resource, LON-CAPA uses symbols
12435: or "symbs"X<symb>. These identifiers are built from the URL of the
12436: map, the resource number of the resource in the map, and the URL of
12437: the resource itself. The latter is somewhat redundant, but might help
12438: if maps change.
12439:
12440: An example is
12441:
12442: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12443:
12444: The respective map entry is
12445:
12446: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12447: title="Problem 2">
12448: </resource>
12449:
12450: Symbs are used by the random number generator, as well as to store and
12451: restore data specific to a certain instance of for example a problem.
12452:
12453: =head2 Storing And Retrieving Data
12454:
12455: X<store()>X<cstore()>X<restore()>Three of the most important functions
12456: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12457: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12458: is is the non-critical message twin of cstore. These functions are for
12459: handlers to store a perl hash to a user's permanent data space in an
12460: easy manner, and to retrieve it again on another call. It is expected
12461: that a handler would use this once at the beginning to retrieve data,
12462: and then again once at the end to send only the new data back.
12463:
12464: The data is stored in the user's data directory on the user's
12465: homeserver under the ID of the course.
12466:
12467: The hash that is returned by restore will have all of the previous
12468: value for all of the elements of the hash.
12469:
12470: Example:
12471:
12472: #creating a hash
12473: my %hash;
12474: $hash{'foo'}='bar';
12475:
12476: #storing it
12477: &Apache::lonnet::cstore(\%hash);
12478:
12479: #changing a value
12480: $hash{'foo'}='notbar';
12481:
12482: #adding a new value
12483: $hash{'bar'}='foo';
12484: &Apache::lonnet::cstore(\%hash);
12485:
12486: #retrieving the hash
12487: my %history=&Apache::lonnet::restore();
12488:
12489: #print the hash
12490: foreach my $key (sort(keys(%history))) {
12491: print("\%history{$key} = $history{$key}");
12492: }
12493:
12494: Will print out:
1.191 harris41 12495:
1.394 bowersj2 12496: %history{1:foo} = bar
12497: %history{1:keys} = foo:timestamp
12498: %history{1:timestamp} = 990455579
12499: %history{2:bar} = foo
12500: %history{2:foo} = notbar
12501: %history{2:keys} = foo:bar:timestamp
12502: %history{2:timestamp} = 990455580
12503: %history{bar} = foo
12504: %history{foo} = notbar
12505: %history{timestamp} = 990455580
12506: %history{version} = 2
12507:
12508: Note that the special hash entries C<keys>, C<version> and
12509: C<timestamp> were added to the hash. C<version> will be equal to the
12510: total number of versions of the data that have been stored. The
12511: C<timestamp> attribute will be the UNIX time the hash was
12512: stored. C<keys> is available in every historical section to list which
12513: keys were added or changed at a specific historical revision of a
12514: hash.
12515:
12516: B<Warning>: do not store the hash that restore returns directly. This
12517: will cause a mess since it will restore the historical keys as if the
12518: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12519:
1.394 bowersj2 12520: Calling convention:
1.191 harris41 12521:
1.1172.2.27 raeburn 12522: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12523: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12524:
1.394 bowersj2 12525: For more detailed information, see lonnet specific documentation.
1.191 harris41 12526:
1.394 bowersj2 12527: =head1 RETURN MESSAGES
1.191 harris41 12528:
1.394 bowersj2 12529: =over 4
1.191 harris41 12530:
1.394 bowersj2 12531: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12532:
1.394 bowersj2 12533: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12534: when the connection is brought back up
1.191 harris41 12535:
1.394 bowersj2 12536: =item * B<con_failed>: unable to contact remote host and unable to save message
12537: for later delivery
1.191 harris41 12538:
1.967 bisitz 12539: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12540:
1.394 bowersj2 12541: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12542: that was requested
1.191 harris41 12543:
1.243 albertel 12544: =back
1.191 harris41 12545:
1.243 albertel 12546: =head1 PUBLIC SUBROUTINES
1.191 harris41 12547:
1.243 albertel 12548: =head2 Session Environment Functions
1.191 harris41 12549:
1.243 albertel 12550: =over 4
1.191 harris41 12551:
1.394 bowersj2 12552: =item *
12553: X<appenv()>
1.949 raeburn 12554: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12555: the user envirnoment file, and will be restored for each access this
1.620 albertel 12556: user makes during this session, also modifies the %env for the current
1.949 raeburn 12557: process. Optional rolesarrayref - if defined contains a reference to an array
12558: of roles which are exempt from the restriction on modifying user.role entries
12559: in the user's environment.db and in %env.
1.191 harris41 12560:
12561: =item *
1.394 bowersj2 12562: X<delenv()>
1.987 raeburn 12563: B<delenv($delthis,$regexp)>: removes all items from the session
12564: environment file that begin with $delthis. If the
12565: optional second arg - $regexp - is true, $delthis is treated as a
12566: regular expression, otherwise \Q$delthis\E is used.
12567: The values are also deleted from the current processes %env.
1.191 harris41 12568:
1.795 albertel 12569: =item * get_env_multiple($name)
12570:
12571: gets $name from the %env hash, it seemlessly handles the cases where multiple
12572: values may be defined and end up as an array ref.
12573:
12574: returns an array of values
12575:
1.243 albertel 12576: =back
12577:
12578: =head2 User Information
1.191 harris41 12579:
1.243 albertel 12580: =over 4
1.191 harris41 12581:
12582: =item *
1.394 bowersj2 12583: X<queryauthenticate()>
12584: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12585: authentication scheme
12586:
12587: =item *
1.394 bowersj2 12588: X<authenticate()>
1.1073 raeburn 12589: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12590: authenticate user from domain's lib servers (first use the current
12591: one). C<$upass> should be the users password.
1.1073 raeburn 12592: $checkdefauth is optional (value is 1 if a check should be made to
12593: authenticate user using default authentication method, and allow
12594: account creation if username does not have account in the domain).
12595: $clientcancheckhost is optional (value is 1 if checking whether the
12596: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12597:
12598: =item *
1.394 bowersj2 12599: X<homeserver()>
12600: B<homeserver($uname,$udom)>: find the server which has
12601: the user's directory and files (there must be only one), this caches
12602: the answer, and also caches if there is a borken connection.
1.191 harris41 12603:
12604: =item *
1.394 bowersj2 12605: X<idget()>
12606: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12607: (IDs are a unique resource in a domain, there must be only 1 ID per
12608: username, and only 1 username per ID in a specific domain) (returns
12609: hash: id=>name,id=>name)
1.191 harris41 12610:
12611: =item *
1.394 bowersj2 12612: X<idrget()>
12613: B<idrget($udom,@unames)>: find the IDs behind a list of
12614: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12615:
12616: =item *
1.394 bowersj2 12617: X<idput()>
12618: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12619:
12620: =item *
1.394 bowersj2 12621: X<rolesinit()>
1.1169 droeschl 12622: B<rolesinit($udom,$username)>: get user privileges.
12623: returns user role, first access and timer interval hashes
1.243 albertel 12624:
12625: =item *
1.1171 droeschl 12626: X<privileged()>
12627: B<privileged($username,$domain)>: returns a true if user has a
12628: privileged and active role (i.e. su or dc), false otherwise.
12629:
12630: =item *
1.551 albertel 12631: X<getsection()>
12632: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12633: course $cname, return section name/number or '' for "not in course"
12634: and '-1' for "no section"
12635:
12636: =item *
1.394 bowersj2 12637: X<userenvironment()>
12638: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12639: passed in @what from the requested user's environment, returns a hash
12640:
1.858 raeburn 12641: =item *
12642: X<userlog_query()>
1.859 albertel 12643: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12644: activity.log file. %filters defines filters applied when parsing the
12645: log file. These can be start or end timestamps, or the type of action
12646: - log to look for Login or Logout events, check for Checkin or
12647: Checkout, role for role selection. The response is in the form
12648: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12649: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12650:
1.243 albertel 12651: =back
12652:
12653: =head2 User Roles
12654:
12655: =over 4
12656:
12657: =item *
12658:
1.810 raeburn 12659: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12660: F: full access
12661: U,I,K: authentication modes (cxx only)
12662: '': forbidden
12663: 1: user needs to choose course
12664: 2: browse allowed
1.766 albertel 12665: A: passphrase authentication needed
1.243 albertel 12666:
12667: =item *
12668:
1.1172.2.13 raeburn 12669: constructaccess($url,$setpriv) : check for access to construction space URL
12670:
12671: See if the owner domain and name in the URL match those in the
12672: expected environment. If so, return three element list
12673: ($ownername,$ownerdomain,$ownerhome).
12674:
12675: Otherwise return the null string.
12676:
12677: If second argument 'setpriv' is true, it assigns the privileges,
12678: and returns the same three element list, unless the owner has
12679: blocked "ad hoc" Domain Coordinator access to the Author Space,
12680: in which case the null string is returned.
12681:
12682: =item *
12683:
1.243 albertel 12684: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12685: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12686: and course level
12687:
12688: =item *
12689:
1.988 raeburn 12690: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12691: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12692: $type is Course (default) or Community.
1.988 raeburn 12693: If $forcedefault evaluates to true, text returned will be default
12694: text for $type. Otherwise, if this is a course, the text returned
12695: will be a custom name for the role (if defined in the course's
12696: environment). If no custom name is defined the default is returned.
12697:
1.832 raeburn 12698: =item *
12699:
1.1172.2.23 raeburn 12700: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12701: All arguments are optional. Returns a hash of a roles, either for
12702: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12703: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12704: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12705: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12706: For each key, value is set to colon-separated start and end times for
12707: the role. If no username and domain are specified, will default to
1.934 raeburn 12708: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12709: of role statuses (active, future or previous), roles
12710: (e.g., cc,in, st etc.) and domains of the roles which can be used
12711: to restrict the list of roles reported. If no array ref is
12712: provided for types, will default to return only active roles.
1.834 albertel 12713:
1.1172.2.13 raeburn 12714: =item *
12715:
12716: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12717: user: $uname:$udom has a role in the course: $cdom_$cnum.
12718:
12719: Additional optional arguments are: $type (if role checking is to be restricted
12720: to certain user status types -- previous (expired roles), active (currently
12721: available roles) or future (roles available in the future), and
12722: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12723: have active Domain Coordinator role in course's domain or in additional
12724: domains (specified in 'Domains to check for privileged users' in course
12725: environment -- set via: Course Settings -> Classlists and staff listing).
12726:
12727: =item *
12728:
12729: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12730: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12731: $possdomains and $possroles are optional array refs -- to domains to check and
12732: roles to check. If $possdomains is not specified, a dump will be done of the
12733: users' roles.db to check for a dc or su role in any domain. This can be
12734: time consuming if &privileged is called repeatedly (e.g., when displaying a
12735: classlist), so in such cases, supplying a $possdomains array is preferred, as
12736: this then allows &privileged_by_domain() to be used, which caches the identity
12737: of privileged users, eliminating the need for repeated calls to &dump().
12738:
12739: =item *
12740:
12741: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12742: where the outer hash keys are domains specified in the $possdomains array ref,
12743: next inner hash keys are privileged roles specified in the $roles array ref,
12744: and the innermost hash contains key = value pairs for username:domain = end:start
12745: for active or future "privileged" users with that role in that domain. To avoid
12746: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12747: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12748:
1.243 albertel 12749: =back
12750:
12751: =head2 User Modification
12752:
12753: =over 4
12754:
12755: =item *
12756:
1.957 raeburn 12757: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12758: user for the level given by URL. Optional start and end dates (leave empty
12759: string or zero for "no date")
1.191 harris41 12760:
12761: =item *
12762:
1.243 albertel 12763: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12764: change a users, password, possible return values are: ok,
12765: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12766: refused
1.191 harris41 12767:
12768: =item *
12769:
1.243 albertel 12770: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12771:
12772: =item *
12773:
1.1058 raeburn 12774: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12775: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12776:
12777: will update user information (firstname,middlename,lastname,generation,
12778: permanentemail), and if forceid is true, student/employee ID also.
12779: A user's institutional affiliation(s) can also be updated.
12780: User information fields will not be overwritten with empty entries
12781: unless the field is included in the $candelete array reference.
12782: This array is included when a single user is modified via "Manage Users",
12783: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12784:
12785: =item *
12786:
1.286 matthew 12787: modifystudent
12788:
1.957 raeburn 12789: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12790: The course id is resolved based on the current user's environment.
12791: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12792: associated with a course.
12793:
1.297 matthew 12794: This call is essentially a wrapper for lonnet::modifyuser and
12795: lonnet::modify_student_enrollment
1.286 matthew 12796:
12797: Inputs:
12798:
12799: =over 4
12800:
1.957 raeburn 12801: =item B<$udom> Student's loncapa domain
1.286 matthew 12802:
1.957 raeburn 12803: =item B<$uname> Student's loncapa login name
1.286 matthew 12804:
1.964 bisitz 12805: =item B<$uid> Student/Employee ID
1.286 matthew 12806:
1.957 raeburn 12807: =item B<$umode> Student's authentication mode
1.286 matthew 12808:
1.957 raeburn 12809: =item B<$upass> Student's password
1.286 matthew 12810:
1.957 raeburn 12811: =item B<$first> Student's first name
1.286 matthew 12812:
1.957 raeburn 12813: =item B<$middle> Student's middle name
1.286 matthew 12814:
1.957 raeburn 12815: =item B<$last> Student's last name
1.286 matthew 12816:
1.957 raeburn 12817: =item B<$gene> Student's generation
1.286 matthew 12818:
1.957 raeburn 12819: =item B<$usec> Student's section in course
1.286 matthew 12820:
12821: =item B<$end> Unix time of the roles expiration
12822:
12823: =item B<$start> Unix time of the roles start date
12824:
12825: =item B<$forceid> If defined, allow $uid to be changed
12826:
12827: =item B<$desiredhome> server to use as home server for student
12828:
1.957 raeburn 12829: =item B<$email> Student's permanent e-mail address
12830:
12831: =item B<$type> Type of enrollment (auto or manual)
12832:
1.963 raeburn 12833: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12834:
12835: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12836:
1.963 raeburn 12837: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12838:
1.963 raeburn 12839: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12840:
1.1172.2.19 raeburn 12841: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12842:
12843: =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 12844:
1.286 matthew 12845: =back
1.297 matthew 12846:
12847: =item *
12848:
12849: modify_student_enrollment
12850:
1.1172.2.31 raeburn 12851: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12852: 'role.request.course' must be defined for this function to proceed.
12853:
12854: Inputs:
12855:
12856: =over 4
12857:
1.1172.2.31 raeburn 12858: =item $udom, student's domain
1.297 matthew 12859:
1.1172.2.31 raeburn 12860: =item $uname, student's name
1.297 matthew 12861:
1.1172.2.31 raeburn 12862: =item $uid, student's user id
1.297 matthew 12863:
1.1172.2.31 raeburn 12864: =item $first, student's first name
1.297 matthew 12865:
12866: =item $middle
12867:
12868: =item $last
12869:
12870: =item $gene
12871:
12872: =item $usec
12873:
12874: =item $end
12875:
12876: =item $start
12877:
1.957 raeburn 12878: =item $type
12879:
12880: =item $locktype
12881:
12882: =item $cid
12883:
12884: =item $selfenroll
12885:
12886: =item $context
12887:
1.1172.2.19 raeburn 12888: =item $credits, number of credits student will earn from this class
12889:
1.297 matthew 12890: =back
12891:
1.191 harris41 12892:
12893: =item *
12894:
1.243 albertel 12895: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12896: custom role; give a custom role to a user for the level given by URL. Specify
12897: name and domain of role author, and role name
1.191 harris41 12898:
12899: =item *
12900:
1.243 albertel 12901: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12902:
12903: =item *
12904:
1.243 albertel 12905: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12906:
12907: =back
12908:
12909: =head2 Course Infomation
12910:
12911: =over 4
1.191 harris41 12912:
12913: =item *
12914:
1.1118 foxr 12915: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12916: specified course id, including all environment settings for the
12917: course, the description of the course will be in the hash under the
12918: key 'description'
1.191 harris41 12919:
1.1118 foxr 12920: $options is an optional parameter that if supplied is a hash reference that controls
12921: what how this function works. It has the following key/values:
12922:
12923: =over 4
12924:
12925: =item freshen_cache
12926:
12927: If defined, and the environment cache for the course is valid, it is
12928: returned in the returned hash.
12929:
12930: =item one_time
12931:
12932: If defined, the last cache time is set to _now_
12933:
12934: =item user
12935:
12936: If defined, the supplied username is used instead of the current user.
12937:
12938:
12939: =back
12940:
1.191 harris41 12941: =item *
12942:
1.624 albertel 12943: resdata($name,$domain,$type,@which) : request for current parameter
12944: setting for a specific $type, where $type is either 'course' or 'user',
12945: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 12946: answers for 10 minutes.
1.243 albertel 12947:
1.877 foxr 12948: =item *
12949:
12950: get_courseresdata($courseid, $domain) : dump the entire course resource
12951: data base, returning a hash that is keyed by the resource name and has
12952: values that are the resource value. I believe that the timestamps and
12953: versions are also returned.
12954:
1.1172.2.31 raeburn 12955: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12956: supplemental content area. This routine caches the number of files for
12957: 10 minutes.
12958:
1.243 albertel 12959: =back
12960:
12961: =head2 Course Modification
12962:
12963: =over 4
1.191 harris41 12964:
12965: =item *
12966:
1.243 albertel 12967: writecoursepref($courseid,%prefs) : write preferences (environment
12968: database) for a course
1.191 harris41 12969:
12970: =item *
12971:
1.1011 raeburn 12972: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12973:
12974: =item *
12975:
1.1038 raeburn 12976: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12977:
1.1167 droeschl 12978: =item *
12979:
12980: is_course($courseid), is_course($cdom, $cnum)
12981:
12982: Accepts either a combined $courseid (in the form of domain_courseid) or the
12983: two component version $cdom, $cnum. It checks if the specified course exists.
12984:
12985: Returns:
12986: undef if the course doesn't exist, otherwise
12987: in scalar context the combined courseid.
12988: in list context the two components of the course identifier, domain and
12989: courseid.
12990:
1.243 albertel 12991: =back
12992:
12993: =head2 Resource Subroutines
12994:
12995: =over 4
1.191 harris41 12996:
12997: =item *
12998:
1.243 albertel 12999: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13000:
13001: =item *
13002:
1.243 albertel 13003: repcopy($filename) : subscribes to the requested file, and attempts to
13004: replicate from the owning library server, Might return
1.607 raeburn 13005: 'unavailable', 'not_found', 'forbidden', 'ok', or
13006: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13007: resource. Expects the local filesystem pathname
13008: (/home/httpd/html/res/....)
13009:
13010: =back
13011:
13012: =head2 Resource Information
13013:
13014: =over 4
1.191 harris41 13015:
13016: =item *
13017:
1.1172.2.28 raeburn 13018: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13019: and returns the value of a variety of different possible values,
13020: $varname should be a request string, and the other parameters can be
13021: used to specify who and what one is asking about. Ordinarily, $cid
13022: does not need to be specified, as it is retrived from
13023: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13024: within lonuserstate::loadmap() when initializing a course, before
13025: $env{'request.course.id'} has been set, so it needs to be provided
13026: in that one case.
1.243 albertel 13027:
13028: Possible values for $varname are environment.lastname (or other item
13029: from the envirnment hash), user.name (or someother aspect about the
13030: user), resource.0.maxtries (or some other part and parameter of a
13031: resource)
1.204 albertel 13032:
13033: =item *
13034:
1.243 albertel 13035: directcondval($number) : get current value of a condition; reads from a state
13036: string
1.204 albertel 13037:
13038: =item *
13039:
1.243 albertel 13040: condval($condidx) : value of condition index based on state
1.204 albertel 13041:
13042: =item *
13043:
1.243 albertel 13044: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13045: resource's metadata, $what should be either a specific key, or either
13046: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13047: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13048:
13049: this function automatically caches all requests
1.191 harris41 13050:
13051: =item *
13052:
1.243 albertel 13053: metadata_query($query,$custom,$customshow) : make a metadata query against the
13054: network of library servers; returns file handle of where SQL and regex results
13055: will be stored for query
1.191 harris41 13056:
13057: =item *
13058:
1.243 albertel 13059: symbread($filename) : return symbolic list entry (filename argument optional);
13060: returns the data handle
1.191 harris41 13061:
13062: =item *
13063:
1.1172.2.17 raeburn 13064: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13065: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13066: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13067: on failure, user must be in a course, as it assumes the existence of
13068: the course initial hash, and uses $env('request.course.id'}. The third
13069: arg is an optional reference to a scalar. If this arg is passed in the
13070: call to symbverify, it will be set to 1 if the symb has been set to be
13071: encrypted; otherwise it will be null.
1.243 albertel 13072:
1.191 harris41 13073: =item *
13074:
1.243 albertel 13075: symbclean($symb) : removes versions numbers from a symb, returns the
13076: cleaned symb
1.191 harris41 13077:
13078: =item *
13079:
1.243 albertel 13080: is_on_map($uri) : checks if the $uri is somewhere on the current
13081: course map, user must be in a course for it to work.
1.191 harris41 13082:
13083: =item *
13084:
1.243 albertel 13085: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13086:
13087: =item *
13088:
1.243 albertel 13089: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13090: a random seed, all arguments are optional, if they aren't sent it uses the
13091: environment to derive them. Note: if symb isn't sent and it can't get one
13092: from &symbread it will use the current time as its return value
1.191 harris41 13093:
13094: =item *
13095:
1.243 albertel 13096: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13097: unfakeable, receipt
1.191 harris41 13098:
13099: =item *
13100:
1.620 albertel 13101: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13102:
13103: =item *
13104:
1.243 albertel 13105: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13106:
13107: =item *
13108:
1.243 albertel 13109: 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 13110:
13111: =item *
13112:
1.243 albertel 13113: 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 13114:
13115: =item *
13116:
1.243 albertel 13117: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13118:
13119: =item *
13120:
1.243 albertel 13121: devalidate($symb) : devalidate temporary spreadsheet calculations,
13122: forcing spreadsheet to reevaluate the resource scores next time.
13123:
1.1172.2.13 raeburn 13124: =item *
13125:
13126: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13127: when viewing in course context.
13128:
13129: input: six args -- filename (decluttered), course number, course domain,
13130: url, symb (if registered) and group (if this is a
13131: group item -- e.g., bulletin board, group page etc.).
13132:
13133: output: array of five scalars --
13134: $cfile -- url for file editing if editable on current server
13135: $home -- homeserver of resource (i.e., for author if published,
13136: or course if uploaded.).
13137: $switchserver -- 1 if server switch will be needed.
13138: $forceedit -- 1 if icon/link should be to go to edit mode
13139: $forceview -- 1 if icon/link should be to go to view mode
13140:
13141: =item *
13142:
13143: is_course_upload($file,$cnum,$cdom)
13144:
13145: Used in course context to determine if current file was uploaded to
13146: the course (i.e., would be found in /userfiles/docs on the course's
13147: homeserver.
13148:
13149: input: 3 args -- filename (decluttered), course number and course domain.
13150: output: boolean -- 1 if file was uploaded.
13151:
1.243 albertel 13152: =back
13153:
13154: =head2 Storing/Retreiving Data
13155:
13156: =over 4
1.191 harris41 13157:
13158: =item *
13159:
1.243 albertel 13160: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13161: for this url; hashref needs to be given and should be a \%hashname; the
13162: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13163: be derived from the env
1.191 harris41 13164:
13165: =item *
13166:
1.243 albertel 13167: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13168: uses critical subroutine
1.191 harris41 13169:
13170: =item *
13171:
1.243 albertel 13172: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13173: all args are optional
1.191 harris41 13174:
13175: =item *
13176:
1.717 albertel 13177: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13178: dumps the complete (or key matching regexp) namespace into a hash
13179: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13180: normally &store()ed into
13181:
13182: $range should be either an integer '100' (give me the first 100
13183: matching records)
13184: or be two integers sperated by a - with no spaces
13185: '30-50' (give me the 30th through the 50th matching
13186: records)
13187:
13188:
13189: =item *
13190:
13191: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13192: replaces a &store() version of data with a replacement set of data
13193: for a particular resource in a namespace passed in the $storehash hash
13194: reference
13195:
13196: =item *
13197:
1.243 albertel 13198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13199: works very similar to store/cstore, but all data is stored in a
13200: temporary location and can be reset using tmpreset, $storehash should
13201: be a hash reference, returns nothing on success
1.191 harris41 13202:
13203: =item *
13204:
1.243 albertel 13205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13206: similar to restore, but all data is stored in a temporary location and
13207: can be reset using tmpreset. Returns a hash of values on success,
13208: error string otherwise.
1.191 harris41 13209:
13210: =item *
13211:
1.243 albertel 13212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13213: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13214:
13215: =item *
13216:
1.243 albertel 13217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13218: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13219:
13220: =item *
13221:
1.243 albertel 13222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13223: namesp ($udom and $uname are optional)
1.191 harris41 13224:
13225: =item *
13226:
1.702 albertel 13227: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13228: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13229: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13230:
1.702 albertel 13231: $range should be either an integer '100' (give me the first 100
13232: matching records)
13233: or be two integers sperated by a - with no spaces
13234: '30-50' (give me the 30th through the 50th matching
13235: records)
1.449 matthew 13236: =item *
13237:
13238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13239: $store can be a scalar, an array reference, or if the amount to be
13240: incremented is > 1, a hash reference.
13241:
13242: ($udom and $uname are optional)
1.191 harris41 13243:
13244: =item *
13245:
1.243 albertel 13246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13247: ($udom and $uname are optional)
1.191 harris41 13248:
13249: =item *
13250:
1.243 albertel 13251: cput($namespace,$storehash,$udom,$uname) : critical put
13252: ($udom and $uname are optional)
1.191 harris41 13253:
13254: =item *
13255:
1.748 albertel 13256: newput($namespace,$storehash,$udom,$uname) :
13257:
13258: Attempts to store the items in the $storehash, but only if they don't
13259: currently exist, if this succeeds you can be certain that you have
13260: successfully created a new key value pair in the $namespace db.
13261:
13262:
13263: Args:
13264: $namespace: name of database to store values to
13265: $storehash: hashref to store to the db
13266: $udom: (optional) domain of user containing the db
13267: $uname: (optional) name of user caontaining the db
13268:
13269: Returns:
13270: 'ok' -> succeeded in storing all keys of $storehash
13271: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13272: least <key> already existed in the db (other
13273: requested keys may also already exist)
1.967 bisitz 13274: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13275: 'con_lost' -> unable to contact request server
13276: 'refused' -> action was not allowed by remote machine
13277:
13278:
13279: =item *
13280:
1.243 albertel 13281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13282: reference filled in from namesp (encrypts the return communication)
13283: ($udom and $uname are optional)
1.191 harris41 13284:
13285: =item *
13286:
1.243 albertel 13287: log($udom,$name,$home,$message) : write to permanent log for user; use
13288: critical subroutine
13289:
1.806 raeburn 13290: =item *
13291:
1.860 raeburn 13292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13293: array reference filled in from namespace found in domain level on either
13294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13295:
13296: =item *
13297:
1.860 raeburn 13298: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13299: domain level either on specified domain server ($uhome) or primary domain
13300: server ($udom and $uhome are optional)
1.806 raeburn 13301:
1.943 raeburn 13302: =item *
13303:
1.1172.2.35 raeburn 13304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13305: for: authentication, language, quotas, timezone, date locale, and portal URL in
13306: the target domain.
13307:
13308: May also include additional key => value pairs for the following groups:
13309:
13310: =over
13311:
13312: =item
13313: disk quotas (MB allocated by default to portfolios and authoring spaces).
13314:
13315: =over
13316:
13317: =item defaultquota, authorquota
13318:
13319: =back
13320:
13321: =item
13322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13323: portfolio for users).
13324:
13325: =over
13326:
13327: =item
13328: aboutme, blog, webdav, portfolio
13329:
13330: =back
13331:
13332: =item
13333: requestcourses: ability to request courses, and how requests are processed.
13334:
13335: =over
13336:
13337: =item
1.1172.2.37! raeburn 13338: official, unofficial, community, textbook
1.1172.2.35 raeburn 13339:
13340: =back
13341:
13342: =item
13343: inststatus: types of institutional affiliation, and order in which they are displayed.
13344:
13345: =over
13346:
13347: =item
13348: inststatustypes, inststatusorder
13349:
13350: =back
13351:
13352: =item
13353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13354: for course's uploaded content.
13355:
13356: =over
13357:
13358: =item
1.1172.2.37! raeburn 13359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13360:
13361: =back
13362:
13363: =item
13364: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13365: on your servers.
13366:
13367: =over
13368:
13369: =item
13370: remotesessions, hostedsessions
13371:
13372: =back
13373:
13374: =back
13375:
13376: In cases where a domain coordinator has never used the "Set Domain Configuration"
13377: utility to create a configuration.db file on a domain's primary library server
13378: only the following domain defaults: auth_def, auth_arg_def, lang_def
13379: -- corresponding values are authentication type (internal, krb4, krb5,
13380: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13381: will be available. Values are retrieved from cache (if current), unless the
13382: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13383: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13384:
13385: Typical usage:
1.943 raeburn 13386:
1.1172.2.35 raeburn 13387: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13388:
1.243 albertel 13389: =back
13390:
13391: =head2 Network Status Functions
13392:
13393: =over 4
1.191 harris41 13394:
13395: =item *
13396:
1.1137 raeburn 13397: dirlist() : return directory list based on URI (first arg).
13398:
13399: Inputs: 1 required, 5 optional.
13400:
13401: =over
13402:
13403: =item
13404: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13405:
13406: =item
13407: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13408:
13409: =item
13410: $username - username of user/course to be listed. Extracted from $uri if absent.
13411:
13412: =item
13413: $getpropath - boolean: 1 if prepend path using &propath().
13414:
13415: =item
13416: $getuserdir - boolean: 1 if prepend path for "userfiles".
13417:
13418: =item
13419: $alternateRoot - path to prepend in place of path from $uri.
13420:
13421: =back
13422:
13423: Returns: Array of up to two items.
13424:
13425: =over
13426:
13427: a reference to an array of files/subdirectories
13428:
13429: =over
13430:
13431: Each element in the array of files/subdirectories is a & separated list of
13432: item name and the result of running stat on the item. If dirlist was requested
13433: for a file instead of a directory, the item name will be ''. For a directory
13434: listing, if the item is a metadata file, the element will end &N&M
13435: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13436: default copyright set (1).
13437:
13438: =back
13439:
13440: a scalar containing error condition (if encountered).
13441:
13442: =over
13443:
13444: =item
13445: no_host (no homeserver identified for $username:$domain).
13446:
13447: =item
13448: no_such_host (server contacted for listing not identified as valid host).
13449:
13450: =item
13451: con_lost (connection to remote server failed).
13452:
13453: =item
13454: refused (invalid $username:$domain received on lond side).
13455:
13456: =item
13457: no_such_dir (directory at specified path on lond side does not exist).
13458:
13459: =item
13460: empty (directory at specified path on lond side is empty).
13461:
13462: =over
13463:
13464: This is currently not encountered because the &ls3, &ls2,
13465: &ls (_handler) routines on the lond side do not filter out
13466: . and .. from a directory listing.
13467:
13468: =back
13469:
13470: =back
13471:
13472: =back
1.191 harris41 13473:
13474: =item *
13475:
1.243 albertel 13476: spareserver() : find server with least workload from spare.tab
13477:
1.986 foxr 13478:
13479: =item *
13480:
13481: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13482: if there is no corresponding loncapa host.
13483:
1.243 albertel 13484: =back
13485:
1.986 foxr 13486:
1.243 albertel 13487: =head2 Apache Request
13488:
13489: =over 4
1.191 harris41 13490:
13491: =item *
13492:
1.243 albertel 13493: ssi($url,%hash) : server side include, does a complete request cycle on url to
13494: localhost, posts hash
13495:
13496: =back
13497:
13498: =head2 Data to String to Data
13499:
13500: =over 4
1.191 harris41 13501:
13502: =item *
13503:
1.243 albertel 13504: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13505: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: hashref2str($hashref) : convert a hashref into a string complete with
13510: escaping and '=' and '&' separators, supports elements that are
13511: arrayrefs and hashrefs
1.191 harris41 13512:
13513: =item *
13514:
1.243 albertel 13515: arrayref2str($arrayref) : convert an arrayref into a string complete
13516: with escaping and '&' separators, supports elements that are arrayrefs
13517: and hashrefs
1.191 harris41 13518:
13519: =item *
13520:
1.243 albertel 13521: str2hash($string) : convert string to hash using unescaping and
13522: splitting on '=' and '&', supports elements that are arrayrefs and
13523: hashrefs
1.191 harris41 13524:
13525: =item *
13526:
1.243 albertel 13527: str2array($string) : convert string to hash using unescaping and
13528: splitting on '&', supports elements that are arrayrefs and hashrefs
13529:
13530: =back
13531:
13532: =head2 Logging Routines
13533:
13534:
13535: These routines allow one to make log messages in the lonnet.log and
13536: lonnet.perm logfiles.
1.191 harris41 13537:
1.1119 foxr 13538: =over 4
13539:
1.191 harris41 13540: =item *
13541:
1.243 albertel 13542: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13543:
13544: =item *
13545:
1.243 albertel 13546: logthis() : append message to the normal lonnet.log file, it gets
13547: preiodically rolled over and deleted.
1.191 harris41 13548:
13549: =item *
13550:
1.243 albertel 13551: logperm() : append a permanent message to lonnet.perm.log, this log
13552: file never gets deleted by any automated portion of the system, only
13553: messages of critical importance should go in here.
13554:
1.1119 foxr 13555:
1.243 albertel 13556: =back
13557:
13558: =head2 General File Helper Routines
13559:
13560: =over 4
1.191 harris41 13561:
13562: =item *
13563:
1.481 raeburn 13564: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13565: (a) files in /uploaded
13566: (i) If a local copy of the file exists -
13567: compares modification date of local copy with last-modified date for
13568: definitive version stored on home server for course. If local copy is
13569: stale, requests a new version from the home server and stores it.
13570: If the original has been removed from the home server, then local copy
13571: is unlinked.
13572: (ii) If local copy does not exist -
13573: requests the file from the home server and stores it.
13574:
13575: If $caller is 'uploadrep':
13576: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13577: for request for files originally uploaded via DOCS.
13578: - returns 'ok' if fresh local copy now available, -1 otherwise.
13579:
13580: Otherwise:
13581: This indicates a call from the content generation phase of the request.
13582: - returns the entire contents of the file or -1.
13583:
13584: (b) files in /res
13585: - returns the entire contents of a file or -1;
13586: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13587:
1.712 albertel 13588:
13589: =item *
13590:
13591: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13592: reference
13593:
13594: returns either a stat() list of data about the file or an empty list
13595: if the file doesn't exist or couldn't find out about it (connection
13596: problems or user unknown)
13597:
1.191 harris41 13598: =item *
13599:
1.243 albertel 13600: filelocation($dir,$file) : returns file system location of a file
13601: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13602: directory that relative $file lookups are to looked in ($dir of /a/dir
13603: and a file of ../bob will become /a/bob)
1.191 harris41 13604:
13605: =item *
13606:
13607: hreflocation($dir,$file) : returns file system location or a URL; same as
13608: filelocation except for hrefs
13609:
13610: =item *
13611:
13612: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13613:
1.243 albertel 13614: =back
13615:
1.608 albertel 13616: =head2 Usererfile file routines (/uploaded*)
13617:
13618: =over 4
13619:
13620: =item *
13621:
13622: userfileupload(): main rotine for putting a file in a user or course's
13623: filespace, arguments are,
13624:
1.620 albertel 13625: formname - required - this is the name of the element in $env where the
1.608 albertel 13626: filename, and the contents of the file to create/modifed exist
1.620 albertel 13627: the filename is in $env{'form.'.$formname.'.filename'} and the
13628: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13629: context - if coursedoc, store the file in the course of the active role
13630: of the current user;
13631: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13632: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13633: subdir - required - subdirectory to put the file in under ../userfiles/
13634: if undefined, it will be placed in "unknown"
13635:
13636: (This routine calls clean_filename() to remove any dangerous
13637: characters from the filename, and then calls finuserfileupload() to
13638: complete the transaction)
13639:
13640: returns either the url of the uploaded file (/uploaded/....) if successful
13641: and /adm/notfound.html if unsuccessful
13642:
13643: =item *
13644:
13645: clean_filename(): routine for cleaing a filename up for storage in
13646: userfile space, argument is:
13647:
13648: filename - proposed filename
13649:
13650: returns: the new clean filename
13651:
13652: =item *
13653:
1.1090 raeburn 13654: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13655: userspace, probably shouldn't be called directly
13656:
13657: docuname: username or courseid of destination for the file
13658: docudom: domain of user/course of destination for the file
13659: formname: same as for userfileupload()
1.1090 raeburn 13660: fname: filename (including subdirectories) for the file
13661: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13662: allfiles: reference to hash used to store objects found by parser
13663: codebase: reference to hash used for codebases of java objects found by parser
13664: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13665: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13666: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13667: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13668: context: if 'overwrite', will move the uploaded file from its temporary location to
13669: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13670: mimetype: reference to scalar to accommodate mime type determined
13671: from File::MMagic if $parser = parse.
1.608 albertel 13672:
13673: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13674: and /adm/notfound.html if unsuccessful (or an error message if context
13675: was 'overwrite').
13676:
1.608 albertel 13677:
13678: =item *
13679:
13680: renameuserfile(): renames an existing userfile to a new name
13681:
13682: Args:
13683: docuname: username or courseid of destination for the file
13684: docudom: domain of user/course of destination for the file
13685: old: current file name (including any subdirs under userfiles)
13686: new: desired file name (including any subdirs under userfiles)
13687:
13688: =item *
13689:
13690: mkdiruserfile(): creates a directory is a userfiles dir
13691:
13692: Args:
13693: docuname: username or courseid of destination for the file
13694: docudom: domain of user/course of destination for the file
13695: dir: dir to create (including any subdirs under userfiles)
13696:
13697: =item *
13698:
13699: removeuserfile(): removes a file that exists in userfiles
13700:
13701: Args:
13702: docuname: username or courseid of destination for the file
13703: docudom: domain of user/course of destination for the file
13704: fname: filname to delete (including any subdirs under userfiles)
13705:
13706: =item *
13707:
13708: removeuploadedurl(): convience function for removeuserfile()
13709:
13710: Args:
13711: url: a full /uploaded/... url to delete
13712:
1.747 albertel 13713: =item *
13714:
13715: get_portfile_permissions():
13716: Args:
13717: domain: domain of user or course contain the portfolio files
13718: user: name of user or num of course contain the portfolio files
13719: Returns:
13720: hashref of a dump of the proper file_permissions.db
13721:
13722:
13723: =item *
13724:
13725: get_access_controls():
13726:
13727: Args:
13728: current_permissions: the hash ref returned from get_portfile_permissions()
13729: group: (optional) the group you want the files associated with
13730: file: (optional) the file you want access info on
13731:
13732: Returns:
1.749 raeburn 13733: a hash (keys are file names) of hashes containing
13734: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13735: values are XML containing access control settings (see below)
1.747 albertel 13736:
13737: Internal notes:
13738:
1.749 raeburn 13739: access controls are stored in file_permissions.db as key=value pairs.
13740: key -> path to file/file_name\0uniqueID:scope_end_start
13741: where scope -> public,guest,course,group,domains or users.
13742: end -> UNIX time for end of access (0 -> no end date)
13743: start -> UNIX time for start of access
13744:
13745: value -> XML description of access control
13746: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13747: <start></start>
13748: <end></end>
13749:
13750: <password></password> for scope type = guest
13751:
13752: <domain></domain> for scope type = course or group
13753: <number></number>
13754: <roles id="">
13755: <role></role>
13756: <access></access>
13757: <section></section>
13758: <group></group>
13759: </roles>
13760:
13761: <dom></dom> for scope type = domains
13762:
13763: <users> for scope type = users
13764: <user>
13765: <uname></uname>
13766: <udom></udom>
13767: </user>
13768: </users>
13769: </scope>
13770:
13771: Access data is also aggregated for each file in an additional key=value pair:
13772: key -> path to file/file_name\0accesscontrol
13773: value -> reference to hash
13774: hash contains key = value pairs
13775: where key = uniqueID:scope_end_start
13776: value = UNIX time record was last updated
13777:
13778: Used to improve speed of look-ups of access controls for each file.
13779:
13780: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13781:
1.1172.2.13 raeburn 13782: =item *
13783:
1.749 raeburn 13784: modify_access_controls():
13785:
13786: Modifies access controls for a portfolio file
13787: Args
13788: 1. file name
13789: 2. reference to hash of required changes,
13790: 3. domain
13791: 4. username
13792: where domain,username are the domain of the portfolio owner
13793: (either a user or a course)
13794:
13795: Returns:
13796: 1. result of additions or updates ('ok' or 'error', with error message).
13797: 2. result of deletions ('ok' or 'error', with error message).
13798: 3. reference to hash of any new or updated access controls.
13799: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13800: key = integer (inbound ID)
1.1172.2.13 raeburn 13801: value = uniqueID
13802:
13803: =item *
13804:
13805: get_timebased_id():
13806:
13807: Attempts to get a unique timestamp-based suffix for use with items added to a
13808: course via the Course Editor (e.g., folders, composite pages,
13809: group bulletin boards).
13810:
13811: Args: (first three required; six others optional)
13812:
13813: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13814: docssequence, or name of group
13815:
13816: 2. keyid (alphanumeric): name of temporary locking key in hash,
13817: e.g., num, boardids
13818:
13819: 3. namespace: name of gdbm file used to store suffixes already assigned;
13820: file will be named nohist_namespace.db
13821:
13822: 4. cdom: domain of course; default is current course domain from %env
13823:
13824: 5. cnum: course number; default is current course number from %env
13825:
13826: 6. idtype: set to concat if an additional digit is to be appended to the
13827: unix timestamp to form the suffix, if the plain timestamp is already
13828: in use. Default is to not do this, but simply increment the unix
13829: timestamp by 1 until a unique key is obtained.
13830:
13831: 7. who: holder of locking key; defaults to user:domain for user.
13832:
13833: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13834: retrying); default is 3.
13835:
13836: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13837:
13838: Returns:
13839:
13840: 1. suffix obtained (numeric)
13841:
13842: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13843:
13844: 3. error: contains (localized) error message if an error occurred.
13845:
1.747 albertel 13846:
1.608 albertel 13847: =back
13848:
1.243 albertel 13849: =head2 HTTP Helper Routines
13850:
13851: =over 4
13852:
1.191 harris41 13853: =item *
13854:
13855: escape() : unpack non-word characters into CGI-compatible hex codes
13856:
13857: =item *
13858:
13859: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13860:
1.243 albertel 13861: =back
13862:
13863: =head1 PRIVATE SUBROUTINES
13864:
13865: =head2 Underlying communication routines (Shouldn't call)
13866:
13867: =over 4
13868:
13869: =item *
13870:
13871: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13872:
13873: =item *
13874:
13875: reply() : uses subreply to send a message to remote machine, logs all failures
13876:
13877: =item *
13878:
13879: critical() : passes a critical message to another server; if cannot
13880: get through then place message in connection buffer directory and
13881: returns con_delayed, if incapable of saving message, returns
13882: con_failed
13883:
13884: =item *
13885:
13886: reconlonc() : tries to reconnect lonc client processes.
13887:
13888: =back
13889:
13890: =head2 Resource Access Logging
13891:
13892: =over 4
13893:
13894: =item *
13895:
13896: flushcourselogs() : flush (save) buffer logs and access logs
13897:
13898: =item *
13899:
13900: courselog($what) : save message for course in hash
13901:
13902: =item *
13903:
13904: courseacclog($what) : save message for course using &courselog(). Perform
13905: special processing for specific resource types (problems, exams, quizzes, etc).
13906:
1.191 harris41 13907: =item *
13908:
13909: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13910: as a PerlChildExitHandler
1.243 albertel 13911:
13912: =back
13913:
13914: =head2 Other
13915:
13916: =over 4
13917:
13918: =item *
13919:
13920: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13921:
13922: =back
13923:
13924: =cut
1.877 foxr 13925:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>