Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1249
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1249 ! raeburn 4: # $Id: lonnet.pm,v 1.1248 2014/01/03 18:39:48 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.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
679: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
893: my ($try_server, $spare_server, $lowest_load) = @_;
894:
895: my $loadans = &reply('load', $try_server);
896: my $userloadans = &reply('userload',$try_server);
897:
898: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 899: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 900: }
901:
902: my $load;
903: if ($loadans =~ /\d/) {
904: if ($userloadans =~ /\d/) {
905: #both are numbers, pick the bigger one
906: $load = ($loadans > $userloadans) ? $loadans
907: : $userloadans;
1.411 albertel 908: } else {
1.784 albertel 909: $load = $loadans;
1.411 albertel 910: }
1.784 albertel 911: } else {
912: $load = $userloadans;
913: }
914:
915: if (($load =~ /\d/) && ($load < $lowest_load)) {
916: $spare_server = $try_server;
917: $lowest_load = $load;
1.370 albertel 918: }
1.784 albertel 919: return ($spare_server,$lowest_load);
1.202 matthew 920: }
1.914 albertel 921:
922: # --------------------------- ask offload servers if user already has a session
923: sub find_existing_session {
924: my ($udom,$uname) = @_;
1.1123 raeburn 925: my $spareshash = &this_host_spares($udom);
926: if (ref($spareshash) eq 'HASH') {
927: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
928: foreach my $try_server (@{ $spareshash->{'primary'} }) {
929: return $try_server if (&has_user_session($try_server, $udom, $uname));
930: }
931: }
932: if (ref($spareshash->{'default'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'default'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
1.914 albertel 937: }
938: return;
939: }
940:
941: # -------------------------------- ask if server already has a session for user
942: sub has_user_session {
943: my ($lonid,$udom,$uname) = @_;
944: my $result = &reply(join(':','userhassession',
945: map {&escape($_)} ($udom,$uname)),$lonid);
946: return 1 if ($result eq 'ok');
947:
948: return 0;
949: }
950:
1.1076 raeburn 951: # --------- determine least loaded server in a user's domain which allows login
952:
953: sub choose_server {
1.1115 raeburn 954: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 955: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 956: my %servers = &get_servers($udom);
1.1076 raeburn 957: my $lowest_load = 30000;
1.1151 raeburn 958: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 959: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 960: my $loginvia;
961: if ($checkloginvia) {
962: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 963: if ($loginvia) {
964: my ($server,$path) = split(/:/,$loginvia);
965: ($login_host, $lowest_load) =
966: &compare_server_load($server, $login_host, $lowest_load);
967: if ($login_host eq $server) {
968: $portal_path = $path;
1.1151 raeburn 969: $isredirect = 1;
1.1116 raeburn 970: }
971: } else {
972: ($login_host, $lowest_load) =
973: &compare_server_load($lonhost, $login_host, $lowest_load);
974: if ($login_host eq $lonhost) {
975: $portal_path = '';
1.1151 raeburn 976: $isredirect = '';
1.1116 raeburn 977: }
978: }
979: } else {
1.1076 raeburn 980: ($login_host, $lowest_load) =
1.1116 raeburn 981: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 982: }
983: }
984: if ($login_host ne '') {
1.1116 raeburn 985: $hostname = &hostname($login_host);
1.1076 raeburn 986: }
1.1151 raeburn 987: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 988: }
989:
1.202 matthew 990: # --------------------------------------------- Try to change a user's password
991:
992: sub changepass {
1.799 raeburn 993: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 994: $currentpass = &escape($currentpass);
995: $newpass = &escape($newpass);
1.1030 raeburn 996: my $lonhost = $perlvar{'lonHostID'};
997: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 998: $server);
999: if (! $answer) {
1000: &logthis("No reply on password change request to $server ".
1001: "by $uname in domain $udom.");
1002: } elsif ($answer =~ "^ok") {
1003: &logthis("$uname in $udom successfully changed their password ".
1004: "on $server.");
1005: } elsif ($answer =~ "^pwchange_failure") {
1006: &logthis("$uname in $udom was unable to change their password ".
1007: "on $server. The action was blocked by either lcpasswd ".
1008: "or pwchange");
1009: } elsif ($answer =~ "^non_authorized") {
1010: &logthis("$uname in $udom did not get their password correct when ".
1011: "attempting to change it on $server.");
1012: } elsif ($answer =~ "^auth_mode_error") {
1013: &logthis("$uname in $udom attempted to change their password despite ".
1014: "not being locally or internally authenticated on $server.");
1015: } elsif ($answer =~ "^unknown_user") {
1016: &logthis("$uname in $udom attempted to change their password ".
1017: "on $server but were unable to because $server is not ".
1018: "their home server.");
1019: } elsif ($answer =~ "^refused") {
1020: &logthis("$server refused to change $uname in $udom password because ".
1021: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1022: } elsif ($answer =~ "invalid_client") {
1023: &logthis("$server refused to change $uname in $udom password because ".
1024: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1025: }
1026: return $answer;
1.1 albertel 1027: }
1028:
1.169 harris41 1029: # ----------------------- Try to determine user's current authentication scheme
1030:
1031: sub queryauthenticate {
1032: my ($uname,$udom)=@_;
1.456 albertel 1033: my $uhome=&homeserver($uname,$udom);
1034: if (!$uhome) {
1035: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1036: return 'no_host';
1037: }
1038: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1039: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1040: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1041: }
1.456 albertel 1042: return $answer;
1.169 harris41 1043: }
1044:
1.1 albertel 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1046:
1.1 albertel 1047: sub authenticate {
1.1073 raeburn 1048: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1049: $upass=&escape($upass);
1050: $uname= &LONCAPA::clean_username($uname);
1.836 www 1051: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1052: my $newhome;
1.836 www 1053: if ((!$uhome) || ($uhome eq 'no_host')) {
1054: # Maybe the machine was offline and only re-appeared again recently?
1055: &reconlonc();
1056: # One more
1.952 raeburn 1057: $uhome=&homeserver($uname,$udom,1);
1058: if (($uhome eq 'no_host') && $checkdefauth) {
1059: if (defined(&domain($udom,'primary'))) {
1060: $newhome=&domain($udom,'primary');
1061: }
1062: if ($newhome ne '') {
1063: $uhome = $newhome;
1064: }
1065: }
1.836 www 1066: if ((!$uhome) || ($uhome eq 'no_host')) {
1067: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1068: return 'no_host';
1069: }
1.1 albertel 1070: }
1.1073 raeburn 1071: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1072: if ($answer eq 'authorized') {
1.952 raeburn 1073: if ($newhome) {
1074: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1075: return 'no_account_on_host';
1076: } else {
1077: &logthis("User $uname at $udom authorized by $uhome");
1078: return $uhome;
1079: }
1.471 albertel 1080: }
1081: if ($answer eq 'non_authorized') {
1082: &logthis("User $uname at $udom rejected by $uhome");
1083: return 'no_host';
1.9 www 1084: }
1.471 albertel 1085: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1086: return 'no_host';
1087: }
1088:
1.1073 raeburn 1089: sub can_host_session {
1.1074 raeburn 1090: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1091: my $canhost = 1;
1.1074 raeburn 1092: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1093: if (ref($remotesessions) eq 'HASH') {
1094: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1095: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1096: $canhost = 0;
1097: } else {
1098: $canhost = 1;
1099: }
1100: }
1101: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1102: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1103: $canhost = 1;
1104: } else {
1105: $canhost = 0;
1106: }
1107: }
1108: if ($canhost) {
1109: if ($remotesessions->{'version'} ne '') {
1110: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1111: if ($reqmajor ne '' && $reqminor ne '') {
1112: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1113: my $major = $1;
1114: my $minor = $2;
1115: if (($major < $reqmajor ) ||
1116: (($major == $reqmajor) && ($minor < $reqminor))) {
1117: $canhost = 0;
1118: }
1119: } else {
1120: $canhost = 0;
1121: }
1122: }
1123: }
1124: }
1125: }
1126: if ($canhost) {
1127: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1128: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1129: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1130: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1131: if (($uint_dom ne '') &&
1132: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1133: $canhost = 0;
1134: } else {
1135: $canhost = 1;
1136: }
1137: }
1138: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1139: if (($uint_dom ne '') &&
1140: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1141: $canhost = 1;
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: return $canhost;
1149: }
1150:
1.1083 raeburn 1151: sub spare_can_host {
1152: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1153: my $canhost=1;
1154: my @intdoms;
1155: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1156: if (ref($internet_names) eq 'ARRAY') {
1157: @intdoms = @{$internet_names};
1158: }
1159: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1160: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1161: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1162: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1163: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1164: $canhost = &can_host_session($udom,$try_server,$remoterev,
1165: $remotesessions,
1166: $defdomdefaults{'hostedsessions'});
1167: }
1168: return $canhost;
1169: }
1170:
1.1123 raeburn 1171: sub this_host_spares {
1172: my ($dom) = @_;
1.1126 raeburn 1173: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1174: my @hosts = ¤t_machine_ids();
1175: foreach my $lonhost (@hosts) {
1176: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1177: $dom_in_use = $dom;
1178: $lonhost_in_use = $lonhost;
1.1123 raeburn 1179: last;
1180: }
1181: }
1.1126 raeburn 1182: if ($dom_in_use ne '') {
1183: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1184: }
1185: if (ref($result) ne 'HASH') {
1186: $lonhost_in_use = $perlvar{'lonHostID'};
1187: $dom_in_use = &host_domain($lonhost_in_use);
1188: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1189: if (ref($result) ne 'HASH') {
1190: $result = \%spareid;
1191: }
1192: }
1193: return $result;
1194: }
1195:
1196: sub spares_for_offload {
1197: my ($dom_in_use,$lonhost_in_use) = @_;
1198: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1199: if (defined($cached)) {
1200: return $result;
1201: } else {
1.1126 raeburn 1202: my $cachetime = 60*60*24;
1203: my %domconfig =
1204: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1205: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1206: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1207: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1208: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1209: }
1210: }
1211: }
1212: }
1.1126 raeburn 1213: return;
1.1123 raeburn 1214: }
1215:
1.1129 raeburn 1216: sub get_lonbalancer_config {
1217: my ($servers) = @_;
1218: my ($currbalancer,$currtargets);
1219: if (ref($servers) eq 'HASH') {
1220: foreach my $server (keys(%{$servers})) {
1221: my %what = (
1222: spareid => 1,
1223: perlvar => 1,
1224: );
1225: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1226: if ($result eq 'ok') {
1227: if (ref($returnhash) eq 'HASH') {
1228: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1229: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1230: $currbalancer = $server;
1231: $currtargets = {};
1232: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1233: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1234: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1235: }
1236: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1237: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1238: }
1239: }
1240: last;
1241: }
1242: }
1243: }
1244: }
1245: }
1246: }
1247: return ($currbalancer,$currtargets);
1248: }
1249:
1250: sub check_loadbalancing {
1251: my ($uname,$udom) = @_;
1.1191 raeburn 1252: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1253: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1254: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1255: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1256: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1257: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1258: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1259: my $serverhomedom = &host_domain($lonhost);
1260:
1261: my $cachetime = 60*60*24;
1262:
1263: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1264: $dom_in_use = $udom;
1265: $homeintdom = 1;
1266: } else {
1267: $dom_in_use = $serverhomedom;
1268: }
1269: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1270: unless (defined($cached)) {
1271: my %domconfig =
1272: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1273: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1274: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1275: }
1276: }
1277: if (ref($result) eq 'HASH') {
1.1191 raeburn 1278: ($is_balancer,$currtargets,$currrules) =
1279: &check_balancer_result($result,@hosts);
1.1129 raeburn 1280: if ($is_balancer) {
1281: if (ref($currrules) eq 'HASH') {
1282: if ($homeintdom) {
1283: if ($uname ne '') {
1284: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1285: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1286: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1287: $rule_in_effect = $currrules->{'_LC_author'};
1288: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1289: $rule_in_effect = $currrules->{'_LC_adv'}
1290: }
1291: }
1292: if ($rule_in_effect eq '') {
1293: my %userenv = &userenvironment($udom,$uname,'inststatus');
1294: if ($userenv{'inststatus'} ne '') {
1295: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1296: my ($othertitle,$usertypes,$types) =
1297: &Apache::loncommon::sorted_inst_types($udom);
1298: if (ref($types) eq 'ARRAY') {
1299: foreach my $type (@{$types}) {
1300: if (grep(/^\Q$type\E$/,@statuses)) {
1301: if (exists($currrules->{$type})) {
1302: $rule_in_effect = $currrules->{$type};
1303: }
1304: }
1305: }
1306: }
1307: } else {
1308: if (exists($currrules->{'default'})) {
1309: $rule_in_effect = $currrules->{'default'};
1310: }
1311: }
1312: }
1313: } else {
1314: if (exists($currrules->{'default'})) {
1315: $rule_in_effect = $currrules->{'default'};
1316: }
1317: }
1318: } else {
1319: if ($currrules->{'_LC_external'} ne '') {
1320: $rule_in_effect = $currrules->{'_LC_external'};
1321: }
1322: }
1323: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1324: $uname,$udom);
1325: }
1326: }
1327: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1328: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1329: unless (defined($cached)) {
1330: my %domconfig =
1331: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1332: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1333: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1334: }
1335: }
1336: if (ref($result) eq 'HASH') {
1.1191 raeburn 1337: ($is_balancer,$currtargets,$currrules) =
1338: &check_balancer_result($result,@hosts);
1339: if ($is_balancer) {
1.1129 raeburn 1340: if (ref($currrules) eq 'HASH') {
1341: if ($currrules->{'_LC_internetdom'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_internetdom'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
1354: } else {
1355: if ($perlvar{'lonBalancer'} eq 'yes') {
1356: $is_balancer = 1;
1357: $offloadto = &this_host_spares($dom_in_use);
1358: }
1359: }
1.1176 raeburn 1360: if ($is_balancer) {
1361: my $lowest_load = 30000;
1362: if (ref($offloadto) eq 'HASH') {
1363: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1364: foreach my $try_server (@{$offloadto->{'primary'}}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1.1129 raeburn 1368: }
1.1176 raeburn 1369: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1370:
1.1176 raeburn 1371: if (!$found_server) {
1372: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1373: foreach my $try_server (@{$offloadto->{'default'}}) {
1374: ($otherserver,$lowest_load) =
1375: &compare_server_load($try_server,$otherserver,$lowest_load);
1376: }
1377: }
1378: }
1379: } elsif (ref($offloadto) eq 'ARRAY') {
1380: if (@{$offloadto} == 1) {
1381: $otherserver = $offloadto->[0];
1382: } elsif (@{$offloadto} > 1) {
1383: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1.1176 raeburn 1389: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1390: $is_balancer = 0;
1391: if ($uname ne '' && $udom ne '') {
1392: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1393:
1394: &appenv({'user.loadbalexempt' => $lonhost,
1395: 'user.loadbalcheck.time' => time});
1396: }
1.1129 raeburn 1397: }
1398: }
1399: }
1400: return ($is_balancer,$otherserver);
1401: }
1402:
1.1191 raeburn 1403: sub check_balancer_result {
1404: my ($result,@hosts) = @_;
1405: my ($is_balancer,$currtargets,$currrules);
1406: if (ref($result) eq 'HASH') {
1407: if ($result->{'lonhost'} ne '') {
1408: my $currbalancer = $result->{'lonhost'};
1409: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1410: $is_balancer = 1;
1411: $currtargets = $result->{'targets'};
1412: $currrules = $result->{'rules'};
1413: }
1414: } else {
1415: foreach my $key (keys(%{$result})) {
1416: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1417: (ref($result->{$key}) eq 'HASH')) {
1418: $is_balancer = 1;
1419: $currrules = $result->{$key}{'rules'};
1420: $currtargets = $result->{$key}{'targets'};
1421: last;
1422: }
1423: }
1424: }
1425: }
1426: return ($is_balancer,$currtargets,$currrules);
1427: }
1428:
1.1129 raeburn 1429: sub get_loadbalancer_targets {
1430: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1431: my $offloadto;
1.1175 raeburn 1432: if ($rule_in_effect eq 'none') {
1433: return [$perlvar{'lonHostID'}];
1434: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1435: $offloadto = $currtargets;
1436: } else {
1437: if ($rule_in_effect eq 'homeserver') {
1438: my $homeserver = &homeserver($uname,$udom);
1439: if ($homeserver ne 'no_host') {
1440: $offloadto = [$homeserver];
1441: }
1442: } elsif ($rule_in_effect eq 'externalbalancer') {
1443: my %domconfig =
1444: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1445: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1446: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1447: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1448: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1449: }
1450: }
1451: } else {
1.1178 raeburn 1452: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1453: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1454: if (&hostname($remotebalancer) ne '') {
1455: $offloadto = [$remotebalancer];
1456: }
1457: }
1458: } elsif (&hostname($rule_in_effect) ne '') {
1459: $offloadto = [$rule_in_effect];
1460: }
1461: }
1462: return $offloadto;
1463: }
1464:
1.1127 raeburn 1465: sub internet_dom_servers {
1466: my ($dom) = @_;
1467: my (%uniqservers,%servers);
1468: my $primaryserver = &hostname(&domain($dom,'primary'));
1469: my @machinedoms = &machine_domains($primaryserver);
1470: foreach my $mdom (@machinedoms) {
1471: my %currservers = %servers;
1472: my %server = &get_servers($mdom);
1473: %servers = (%currservers,%server);
1474: }
1475: my %by_hostname;
1476: foreach my $id (keys(%servers)) {
1477: push(@{$by_hostname{$servers{$id}}},$id);
1478: }
1479: foreach my $hostname (sort(keys(%by_hostname))) {
1480: if (@{$by_hostname{$hostname}} > 1) {
1481: my $match = 0;
1482: foreach my $id (@{$by_hostname{$hostname}}) {
1483: if (&host_domain($id) eq $dom) {
1484: $uniqservers{$id} = $hostname;
1485: $match = 1;
1486: }
1487: }
1488: unless ($match) {
1489: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1490: }
1491: } else {
1492: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1493: }
1494: }
1495: return %uniqservers;
1496: }
1497:
1.1 albertel 1498: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1499:
1.599 albertel 1500: my %homecache;
1.1 albertel 1501: sub homeserver {
1.230 stredwic 1502: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1503: my $index="$uname:$udom";
1.426 albertel 1504:
1.599 albertel 1505: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1506:
1507: my %servers = &get_servers($udom,'library');
1508: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1509: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1510: exists($badServerCache{$tryserver}));
1.841 albertel 1511:
1512: my $answer=reply("home:$udom:$uname",$tryserver);
1513: if ($answer eq 'found') {
1514: delete($badServerCache{$tryserver});
1515: return $homecache{$index}=$tryserver;
1516: } elsif ($answer eq 'no_host') {
1517: $badServerCache{$tryserver}=1;
1518: }
1.1 albertel 1519: }
1520: return 'no_host';
1.70 www 1521: }
1522:
1523: # ------------------------------------- Find the usernames behind a list of IDs
1524:
1525: sub idget {
1526: my ($udom,@ids)=@_;
1527: my %returnhash=();
1528:
1.841 albertel 1529: my %servers = &get_servers($udom,'library');
1530: foreach my $tryserver (keys(%servers)) {
1531: my $idlist=join('&',@ids);
1532: $idlist=~tr/A-Z/a-z/;
1533: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1534: my @answer=();
1535: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1536: @answer=split(/\&/,$reply);
1537: } ;
1538: my $i;
1539: for ($i=0;$i<=$#ids;$i++) {
1540: if ($answer[$i]) {
1541: $returnhash{$ids[$i]}=$answer[$i];
1542: }
1543: }
1544: }
1.70 www 1545: return %returnhash;
1546: }
1547:
1548: # ------------------------------------- Find the IDs behind a list of usernames
1549:
1550: sub idrget {
1551: my ($udom,@unames)=@_;
1552: my %returnhash=();
1.800 albertel 1553: foreach my $uname (@unames) {
1554: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1555: }
1.70 www 1556: return %returnhash;
1557: }
1558:
1559: # ------------------------------- Store away a list of names and associated IDs
1560:
1561: sub idput {
1562: my ($udom,%ids)=@_;
1563: my %servers=();
1.800 albertel 1564: foreach my $uname (keys(%ids)) {
1565: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1566: my $uhom=&homeserver($uname,$udom);
1.70 www 1567: if ($uhom ne 'no_host') {
1.800 albertel 1568: my $id=&escape($ids{$uname});
1.70 www 1569: $id=~tr/A-Z/a-z/;
1.800 albertel 1570: my $esc_unam=&escape($uname);
1.70 www 1571: if ($servers{$uhom}) {
1.800 albertel 1572: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1573: } else {
1.800 albertel 1574: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1575: }
1576: }
1.191 harris41 1577: }
1.800 albertel 1578: foreach my $server (keys(%servers)) {
1579: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1580: }
1.344 www 1581: }
1582:
1.1231 raeburn 1583: # ---------------------------------------- Delete unwanted IDs from ids.db file
1584:
1585: sub iddel {
1586: my ($udom,$idshashref,$uhome)=@_;
1587: my %result=();
1588: unless (ref($idshashref) eq 'HASH') {
1589: return %result;
1590: }
1591: my %servers=();
1592: while (my ($id,$uname) = each(%{$idshashref})) {
1593: my $uhom;
1594: if ($uhome) {
1595: $uhom = $uhome;
1596: } else {
1597: $uhom=&homeserver($uname,$udom);
1598: }
1599: if ($uhom ne 'no_host') {
1600: if ($servers{$uhom}) {
1601: $servers{$uhom}.='&'.&escape($id);
1602: } else {
1603: $servers{$uhom}=&escape($id);
1604: }
1605: }
1606: }
1607: foreach my $server (keys(%servers)) {
1608: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1609: }
1610: return %result;
1611: }
1612:
1.1023 raeburn 1613: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1614: sub dump_dom {
1.1165 droeschl 1615: my ($namespace, $udom, $regexp) = @_;
1616:
1617: $udom ||= $env{'user.domain'};
1618:
1619: return () unless $udom;
1620:
1621: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1622: }
1623:
1.1023 raeburn 1624: # ------------------------------------------ get items from domain db files
1.806 raeburn 1625:
1626: sub get_dom {
1.860 raeburn 1627: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1628: my $items='';
1629: foreach my $item (@$storearr) {
1630: $items.=&escape($item).'&';
1631: }
1632: $items=~s/\&$//;
1.860 raeburn 1633: if (!$udom) {
1634: $udom=$env{'user.domain'};
1635: if (defined(&domain($udom,'primary'))) {
1636: $uhome=&domain($udom,'primary');
1637: } else {
1.874 albertel 1638: undef($uhome);
1.860 raeburn 1639: }
1640: } else {
1641: if (!$uhome) {
1642: if (defined(&domain($udom,'primary'))) {
1643: $uhome=&domain($udom,'primary');
1644: }
1645: }
1646: }
1647: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1648: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1649: my %returnhash;
1.875 albertel 1650: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1651: return %returnhash;
1652: }
1.806 raeburn 1653: my @pairs=split(/\&/,$rep);
1654: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1655: return @pairs;
1656: }
1657: my $i=0;
1658: foreach my $item (@$storearr) {
1659: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1660: $i++;
1661: }
1662: return %returnhash;
1663: } else {
1.880 banghart 1664: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1665: }
1666: }
1667:
1668: # -------------------------------------------- put items in domain db files
1669:
1670: sub put_dom {
1.860 raeburn 1671: my ($namespace,$storehash,$udom,$uhome)=@_;
1672: if (!$udom) {
1673: $udom=$env{'user.domain'};
1674: if (defined(&domain($udom,'primary'))) {
1675: $uhome=&domain($udom,'primary');
1676: } else {
1.874 albertel 1677: undef($uhome);
1.860 raeburn 1678: }
1679: } else {
1680: if (!$uhome) {
1681: if (defined(&domain($udom,'primary'))) {
1682: $uhome=&domain($udom,'primary');
1683: }
1684: }
1685: }
1686: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1687: my $items='';
1688: foreach my $item (keys(%$storehash)) {
1689: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1690: }
1691: $items=~s/\&$//;
1692: return &reply("putdom:$udom:$namespace:$items",$uhome);
1693: } else {
1.860 raeburn 1694: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1695: }
1696: }
1697:
1.1023 raeburn 1698: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1699: sub newput_dom {
1.1023 raeburn 1700: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1701: my $result;
1702: if (!$udom) {
1703: $udom=$env{'user.domain'};
1704: }
1.1023 raeburn 1705: if ($udom) {
1706: my $uname = &get_domainconfiguser($udom);
1707: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1708: }
1709: return $result;
1710: }
1711:
1.1023 raeburn 1712: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1713: sub del_dom {
1.1023 raeburn 1714: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1715: if (ref($storearr) eq 'ARRAY') {
1716: if (!$udom) {
1717: $udom=$env{'user.domain'};
1718: }
1.1023 raeburn 1719: if ($udom) {
1720: my $uname = &get_domainconfiguser($udom);
1721: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1722: }
1723: }
1724: }
1725:
1.1023 raeburn 1726: # ----------------------------------construct domainconfig user for a domain
1727: sub get_domainconfiguser {
1728: my ($udom) = @_;
1729: return $udom.'-domainconfig';
1730: }
1731:
1.837 raeburn 1732: sub retrieve_inst_usertypes {
1733: my ($udom) = @_;
1734: my (%returnhash,@order);
1.989 raeburn 1735: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1736: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1737: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1738: %returnhash = %{$domdefs{'inststatustypes'}};
1739: @order = @{$domdefs{'inststatusorder'}};
1740: } else {
1741: if (defined(&domain($udom,'primary'))) {
1742: my $uhome=&domain($udom,'primary');
1743: my $rep=&reply("inst_usertypes:$udom",$uhome);
1744: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1745: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1746: return (\%returnhash,\@order);
1747: }
1748: my ($hashitems,$orderitems) = split(/:/,$rep);
1749: my @pairs=split(/\&/,$hashitems);
1750: foreach my $item (@pairs) {
1751: my ($key,$value)=split(/=/,$item,2);
1752: $key = &unescape($key);
1753: next if ($key =~ /^error: 2 /);
1754: $returnhash{$key}=&thaw_unescape($value);
1755: }
1756: my @esc_order = split(/\&/,$orderitems);
1757: foreach my $item (@esc_order) {
1758: push(@order,&unescape($item));
1759: }
1760: } else {
1761: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1762: }
1763: }
1764: return (\%returnhash,\@order);
1765: }
1766:
1.868 raeburn 1767: sub is_domainimage {
1768: my ($url) = @_;
1769: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1770: if (&domain($1) ne '') {
1771: return '1';
1772: }
1773: }
1774: return;
1775: }
1776:
1.899 raeburn 1777: sub inst_directory_query {
1778: my ($srch) = @_;
1779: my $udom = $srch->{'srchdomain'};
1780: my %results;
1781: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1782: my $outcome;
1.899 raeburn 1783: if ($homeserver ne '') {
1.904 albertel 1784: my $queryid=&reply("querysend:instdirsearch:".
1785: &escape($srch->{'srchby'}).':'.
1786: &escape($srch->{'srchterm'}).':'.
1787: &escape($srch->{'srchtype'}),$homeserver);
1788: my $host=&hostname($homeserver);
1789: if ($queryid !~/^\Q$host\E\_/) {
1790: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1791: return;
1792: }
1793: my $response = &get_query_reply($queryid);
1794: my $maxtries = 5;
1795: my $tries = 1;
1796: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1797: $response = &get_query_reply($queryid);
1798: $tries ++;
1799: }
1800:
1801: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1802: if ($response eq 'unavailable') {
1803: $outcome = $response;
1804: } else {
1805: $outcome = 'ok';
1806: my @matches = split(/\n/,$response);
1807: foreach my $match (@matches) {
1808: my ($key,$value) = split(/=/,$match);
1809: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1810: }
1.899 raeburn 1811: }
1812: }
1813: }
1.909 raeburn 1814: return ($outcome,%results);
1.899 raeburn 1815: }
1816:
1817: sub usersearch {
1818: my ($srch) = @_;
1819: my $dom = $srch->{'srchdomain'};
1820: my %results;
1821: my %libserv = &all_library();
1822: my $query = 'usersearch';
1823: foreach my $tryserver (keys(%libserv)) {
1824: if (&host_domain($tryserver) eq $dom) {
1825: my $host=&hostname($tryserver);
1826: my $queryid=
1.911 raeburn 1827: &reply("querysend:".&escape($query).':'.
1828: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1829: &escape($srch->{'srchtype'}).':'.
1830: &escape($srch->{'srchterm'}),$tryserver);
1831: if ($queryid !~/^\Q$host\E\_/) {
1832: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1833: next;
1.899 raeburn 1834: }
1835: my $reply = &get_query_reply($queryid);
1836: my $maxtries = 1;
1837: my $tries = 1;
1838: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1839: $reply = &get_query_reply($queryid);
1840: $tries ++;
1841: }
1842: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1843: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1844: } else {
1.911 raeburn 1845: my @matches;
1846: if ($reply =~ /\n/) {
1847: @matches = split(/\n/,$reply);
1848: } else {
1849: @matches = split(/\&/,$reply);
1850: }
1.899 raeburn 1851: foreach my $match (@matches) {
1852: my ($uname,$udom,%userhash);
1.911 raeburn 1853: foreach my $entry (split(/:/,$match)) {
1854: my ($key,$value) =
1855: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1856: $userhash{$key} = $value;
1857: if ($key eq 'username') {
1858: $uname = $value;
1859: } elsif ($key eq 'domain') {
1860: $udom = $value;
1.911 raeburn 1861: }
1.899 raeburn 1862: }
1863: $results{$uname.':'.$udom} = \%userhash;
1864: }
1865: }
1866: }
1867: }
1868: return %results;
1869: }
1870:
1.912 raeburn 1871: sub get_instuser {
1872: my ($udom,$uname,$id) = @_;
1873: my $homeserver = &domain($udom,'primary');
1874: my ($outcome,%results);
1875: if ($homeserver ne '') {
1876: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1877: &escape($id).':'.&escape($udom),$homeserver);
1878: my $host=&hostname($homeserver);
1879: if ($queryid !~/^\Q$host\E\_/) {
1880: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1881: return;
1882: }
1883: my $response = &get_query_reply($queryid);
1884: my $maxtries = 5;
1885: my $tries = 1;
1886: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1887: $response = &get_query_reply($queryid);
1888: $tries ++;
1889: }
1890: if (!&error($response) && $response ne 'refused') {
1891: if ($response eq 'unavailable') {
1892: $outcome = $response;
1893: } else {
1894: $outcome = 'ok';
1895: my @matches = split(/\n/,$response);
1896: foreach my $match (@matches) {
1897: my ($key,$value) = split(/=/,$match);
1898: $results{&unescape($key)} = &thaw_unescape($value);
1899: }
1900: }
1901: }
1902: }
1903: my %userinfo;
1904: if (ref($results{$uname}) eq 'HASH') {
1905: %userinfo = %{$results{$uname}};
1906: }
1907: return ($outcome,%userinfo);
1908: }
1909:
1910: sub inst_rulecheck {
1.923 raeburn 1911: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1912: my %returnhash;
1913: if ($udom ne '') {
1914: if (ref($rules) eq 'ARRAY') {
1915: @{$rules} = map {&escape($_);} (@{$rules});
1916: my $rulestr = join(':',@{$rules});
1917: my $homeserver=&domain($udom,'primary');
1918: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1919: my $response;
1920: if ($item eq 'username') {
1921: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1922: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1923: $homeserver));
1.923 raeburn 1924: } elsif ($item eq 'id') {
1925: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1926: ':'.&escape($id).':'.$rulestr,
1927: $homeserver));
1.945 raeburn 1928: } elsif ($item eq 'selfcreate') {
1929: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1930: &escape($udom).':'.&escape($uname).
1931: ':'.$rulestr,$homeserver));
1.923 raeburn 1932: }
1.912 raeburn 1933: if ($response ne 'refused') {
1934: my @pairs=split(/\&/,$response);
1935: foreach my $item (@pairs) {
1936: my ($key,$value)=split(/=/,$item,2);
1937: $key = &unescape($key);
1938: next if ($key =~ /^error: 2 /);
1939: $returnhash{$key}=&thaw_unescape($value);
1940: }
1941: }
1942: }
1943: }
1944: }
1945: return %returnhash;
1946: }
1947:
1948: sub inst_userrules {
1.923 raeburn 1949: my ($udom,$check) = @_;
1.912 raeburn 1950: my (%ruleshash,@ruleorder);
1951: if ($udom ne '') {
1952: my $homeserver=&domain($udom,'primary');
1953: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1954: my $response;
1955: if ($check eq 'id') {
1956: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1957: $homeserver);
1.943 raeburn 1958: } elsif ($check eq 'email') {
1959: $response=&reply('instemailrules:'.&escape($udom),
1960: $homeserver);
1.923 raeburn 1961: } else {
1962: $response=&reply('instuserrules:'.&escape($udom),
1963: $homeserver);
1964: }
1.912 raeburn 1965: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1966: ($response ne 'unknown_cmd') &&
1.912 raeburn 1967: ($response ne 'no_such_host')) {
1968: my ($hashitems,$orderitems) = split(/:/,$response);
1969: my @pairs=split(/\&/,$hashitems);
1970: foreach my $item (@pairs) {
1971: my ($key,$value)=split(/=/,$item,2);
1972: $key = &unescape($key);
1973: next if ($key =~ /^error: 2 /);
1974: $ruleshash{$key}=&thaw_unescape($value);
1975: }
1976: my @esc_order = split(/\&/,$orderitems);
1977: foreach my $item (@esc_order) {
1978: push(@ruleorder,&unescape($item));
1979: }
1980: }
1981: }
1982: }
1983: return (\%ruleshash,\@ruleorder);
1984: }
1985:
1.976 raeburn 1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1987:
1988: sub get_domain_defaults {
1.1240 raeburn 1989: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1990: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1991: my $cachetime = 60*60*24;
1.1240 raeburn 1992: unless ($ignore_cache) {
1993: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1994: if (defined($cached)) {
1995: if (ref($result) eq 'HASH') {
1996: return %{$result};
1997: }
1.943 raeburn 1998: }
1999: }
2000: my %domdefaults;
2001: my %domconfig =
1.989 raeburn 2002: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2003: 'requestcourses','inststatus',
1.1183 raeburn 2004: 'coursedefaults','usersessions',
2005: 'requestauthor'],$domain);
1.943 raeburn 2006: if (ref($domconfig{'defaults'}) eq 'HASH') {
2007: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2008: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2009: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2010: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2011: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2012: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2013: } else {
2014: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2015: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2016: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2017: }
1.976 raeburn 2018: if (ref($domconfig{'quotas'}) eq 'HASH') {
2019: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2020: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2021: } else {
2022: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2023: }
1.1177 raeburn 2024: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2025: foreach my $item (@usertools) {
2026: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2027: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2028: }
2029: }
1.1229 raeburn 2030: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2031: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2032: }
1.976 raeburn 2033: }
1.985 raeburn 2034: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2035: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2036: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2037: }
2038: }
1.1183 raeburn 2039: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2040: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2041: }
1.989 raeburn 2042: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2043: foreach my $item ('inststatustypes','inststatusorder') {
2044: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2045: }
2046: }
1.1047 raeburn 2047: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2048: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2049: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2050: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2051: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1246 raeburn 2052: $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
1.1216 raeburn 2053: }
1.1230 raeburn 2054: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2055: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2056: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
1.1246 raeburn 2057: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2058: $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
1.1230 raeburn 2059: }
1.1047 raeburn 2060: }
1.1073 raeburn 2061: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2062: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2063: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2064: }
2065: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2066: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2067: }
2068: }
1.1219 raeburn 2069: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2070: return %domdefaults;
2071: }
2072:
1.344 www 2073: # --------------------------------------------------- Assign a key to a student
2074:
2075: sub assign_access_key {
1.364 www 2076: #
2077: # a valid key looks like uname:udom#comments
2078: # comments are being appended
2079: #
1.498 www 2080: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2081: $kdom=
1.620 albertel 2082: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2083: $knum=
1.620 albertel 2084: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2085: $cdom=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2087: $cnum=
1.620 albertel 2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2089: $udom=$env{'user.name'} unless (defined($udom));
2090: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2091: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2092: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2093: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2094: # assigned to this person
2095: # - this should not happen,
1.345 www 2096: # unless something went wrong
2097: # the first time around
2098: # ready to assign
1.364 www 2099: $logentry=$1.'; '.$logentry;
1.496 www 2100: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2101: $kdom,$knum) eq 'ok') {
1.345 www 2102: # key now belongs to user
1.346 www 2103: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2104: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2105: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2106: return 'ok';
2107: } else {
2108: return
2109: 'error: Count not permanently assign key, will need to be re-entered later.';
2110: }
2111: } else {
2112: return 'error: Could not assign key, try again later.';
2113: }
1.364 www 2114: } elsif (!$existing{$ckey}) {
1.345 www 2115: # the key does not exist
2116: return 'error: The key does not exist';
2117: } else {
2118: # the key is somebody else's
2119: return 'error: The key is already in use';
2120: }
1.344 www 2121: }
2122:
1.364 www 2123: # ------------------------------------------ put an additional comment on a key
2124:
2125: sub comment_access_key {
2126: #
2127: # a valid key looks like uname:udom#comments
2128: # comments are being appended
2129: #
2130: my ($ckey,$cdom,$cnum,$logentry)=@_;
2131: $cdom=
1.620 albertel 2132: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2133: $cnum=
1.620 albertel 2134: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2135: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2136: if ($existing{$ckey}) {
2137: $existing{$ckey}.='; '.$logentry;
2138: # ready to assign
1.367 www 2139: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2140: $cdom,$cnum) eq 'ok') {
2141: return 'ok';
2142: } else {
2143: return 'error: Count not store comment.';
2144: }
2145: } else {
2146: # the key does not exist
2147: return 'error: The key does not exist';
2148: }
2149: }
2150:
1.344 www 2151: # ------------------------------------------------------ Generate a set of keys
2152:
2153: sub generate_access_keys {
1.364 www 2154: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2155: $cdom=
1.620 albertel 2156: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2157: $cnum=
1.620 albertel 2158: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2159: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2160: unless (($cdom) && ($cnum)) { return 0; }
2161: if ($number>10000) { return 0; }
2162: sleep(2); # make sure don't get same seed twice
2163: srand(time()^($$+($$<<15))); # from "Programming Perl"
2164: my $total=0;
2165: for (my $i=1;$i<=$number;$i++) {
2166: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2167: sprintf("%lx",int(100000*rand)).'-'.
2168: sprintf("%lx",int(100000*rand));
2169: $newkey=~s/1/g/g; # folks mix up 1 and l
2170: $newkey=~s/0/h/g; # and also 0 and O
2171: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2172: if ($existing{$newkey}) {
2173: $i--;
2174: } else {
1.364 www 2175: if (&put('accesskeys',
2176: { $newkey => '# generated '.localtime().
1.620 albertel 2177: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2178: '; '.$logentry },
2179: $cdom,$cnum) eq 'ok') {
1.344 www 2180: $total++;
2181: }
2182: }
2183: }
1.620 albertel 2184: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2185: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2186: return $total;
2187: }
2188:
2189: # ------------------------------------------------------- Validate an accesskey
2190:
2191: sub validate_access_key {
2192: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2193: $cdom=
1.620 albertel 2194: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2195: $cnum=
1.620 albertel 2196: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2197: $udom=$env{'user.domain'} unless (defined($udom));
2198: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2199: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2200: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2201: }
2202:
2203: # ------------------------------------- Find the section of student in a course
1.652 albertel 2204: sub devalidate_getsection_cache {
2205: my ($udom,$unam,$courseid)=@_;
2206: my $hashid="$udom:$unam:$courseid";
2207: &devalidate_cache_new('getsection',$hashid);
2208: }
1.298 matthew 2209:
1.815 albertel 2210: sub courseid_to_courseurl {
2211: my ($courseid) = @_;
2212: #already url style courseid
2213: return $courseid if ($courseid =~ m{^/});
2214:
2215: if (exists($env{'course.'.$courseid.'.num'})) {
2216: my $cnum = $env{'course.'.$courseid.'.num'};
2217: my $cdom = $env{'course.'.$courseid.'.domain'};
2218: return "/$cdom/$cnum";
2219: }
2220:
2221: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2222: if (exists($courseinfo{'num'})) {
2223: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2224: }
2225:
2226: return undef;
2227: }
2228:
1.298 matthew 2229: sub getsection {
2230: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2231: my $cachetime=1800;
1.551 albertel 2232:
2233: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2234: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2235: if (defined($cached)) { return $result; }
2236:
1.298 matthew 2237: my %Pending;
2238: my %Expired;
2239: #
2240: # Each role can either have not started yet (pending), be active,
2241: # or have expired.
2242: #
2243: # If there is an active role, we are done.
2244: #
2245: # If there is more than one role which has not started yet,
2246: # choose the one which will start sooner
2247: # If there is one role which has not started yet, return it.
2248: #
2249: # If there is more than one expired role, choose the one which ended last.
2250: # If there is a role which has expired, return it.
2251: #
1.815 albertel 2252: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2253: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2254: foreach my $key (keys(%roleshash)) {
1.479 albertel 2255: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2256: my $section=$1;
2257: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2258: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2259: my $now=time;
1.548 albertel 2260: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2261: $Expired{$end}=$section;
2262: next;
2263: }
1.548 albertel 2264: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2265: $Pending{$start}=$section;
2266: next;
2267: }
1.599 albertel 2268: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2269: }
2270: #
2271: # Presumedly there will be few matching roles from the above
2272: # loop and the sorting time will be negligible.
2273: if (scalar(keys(%Pending))) {
2274: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2275: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2276: }
2277: if (scalar(keys(%Expired))) {
2278: my @sorted = sort {$a <=> $b} keys(%Expired);
2279: my $time = pop(@sorted);
1.599 albertel 2280: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2281: }
1.599 albertel 2282: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2283: }
1.70 www 2284:
1.599 albertel 2285: sub save_cache {
2286: &purge_remembered();
1.722 albertel 2287: #&Apache::loncommon::validate_page();
1.620 albertel 2288: undef(%env);
1.780 albertel 2289: undef($env_loaded);
1.599 albertel 2290: }
1.452 albertel 2291:
1.599 albertel 2292: my $to_remember=-1;
2293: my %remembered;
2294: my %accessed;
2295: my $kicks=0;
2296: my $hits=0;
1.849 albertel 2297: sub make_key {
2298: my ($name,$id) = @_;
1.872 albertel 2299: if (length($id) > 65
2300: && length(&escape($id)) > 200) {
2301: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2302: }
1.849 albertel 2303: return &escape($name.':'.$id);
2304: }
2305:
1.599 albertel 2306: sub devalidate_cache_new {
2307: my ($name,$id,$debug) = @_;
2308: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2309: $id=&make_key($name,$id);
1.599 albertel 2310: $memcache->delete($id);
2311: delete($remembered{$id});
2312: delete($accessed{$id});
2313: }
2314:
2315: sub is_cached_new {
2316: my ($name,$id,$debug) = @_;
1.849 albertel 2317: $id=&make_key($name,$id);
1.599 albertel 2318: if (exists($remembered{$id})) {
1.1133 foxr 2319: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2320: $accessed{$id}=[&gettimeofday()];
2321: $hits++;
2322: return ($remembered{$id},1);
2323: }
2324: my $value = $memcache->get($id);
2325: if (!(defined($value))) {
2326: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2327: return (undef,undef);
1.416 albertel 2328: }
1.599 albertel 2329: if ($value eq '__undef__') {
2330: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2331: $value=undef;
2332: }
2333: &make_room($id,$value,$debug);
2334: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2335: return ($value,1);
2336: }
2337:
2338: sub do_cache_new {
2339: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2340: $id=&make_key($name,$id);
1.599 albertel 2341: my $setvalue=$value;
2342: if (!defined($setvalue)) {
2343: $setvalue='__undef__';
2344: }
1.623 albertel 2345: if (!defined($time) ) {
2346: $time=600;
2347: }
1.599 albertel 2348: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2349: my $result = $memcache->set($id,$setvalue,$time);
2350: if (! $result) {
1.872 albertel 2351: &logthis("caching of id -> $id failed");
1.910 albertel 2352: $memcache->disconnect_all();
1.872 albertel 2353: }
1.600 albertel 2354: # need to make a copy of $value
1.919 albertel 2355: &make_room($id,$value,$debug);
1.599 albertel 2356: return $value;
2357: }
2358:
2359: sub make_room {
2360: my ($id,$value,$debug)=@_;
1.919 albertel 2361:
2362: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2363: : $value;
1.599 albertel 2364: if ($to_remember<0) { return; }
2365: $accessed{$id}=[&gettimeofday()];
2366: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2367: my $to_kick;
2368: my $max_time=0;
2369: foreach my $other (keys(%accessed)) {
2370: if (&tv_interval($accessed{$other}) > $max_time) {
2371: $to_kick=$other;
2372: $max_time=&tv_interval($accessed{$other});
2373: }
2374: }
2375: delete($remembered{$to_kick});
2376: delete($accessed{$to_kick});
2377: $kicks++;
2378: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2379: return;
2380: }
2381:
1.599 albertel 2382: sub purge_remembered {
1.604 albertel 2383: #&logthis("Tossing ".scalar(keys(%remembered)));
2384: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2385: undef(%remembered);
2386: undef(%accessed);
1.428 albertel 2387: }
1.70 www 2388: # ------------------------------------- Read an entry from a user's environment
2389:
2390: sub userenvironment {
2391: my ($udom,$unam,@what)=@_;
1.976 raeburn 2392: my $items;
2393: foreach my $item (@what) {
2394: $items.=&escape($item).'&';
2395: }
2396: $items=~s/\&$//;
1.70 www 2397: my %returnhash=();
1.1009 raeburn 2398: my $uhome = &homeserver($unam,$udom);
2399: unless ($uhome eq 'no_host') {
2400: my @answer=split(/\&/,
2401: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2402: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2403: return %returnhash;
2404: }
1.1009 raeburn 2405: my $i;
2406: for ($i=0;$i<=$#what;$i++) {
2407: $returnhash{$what[$i]}=&unescape($answer[$i]);
2408: }
1.70 www 2409: }
2410: return %returnhash;
1.1 albertel 2411: }
2412:
1.617 albertel 2413: # ---------------------------------------------------------- Get a studentphoto
2414: sub studentphoto {
2415: my ($udom,$unam,$ext) = @_;
2416: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2417: if (defined($env{'request.course.id'})) {
1.708 raeburn 2418: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2419: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2420: return(&retrievestudentphoto($udom,$unam,$ext));
2421: } else {
2422: my ($result,$perm_reqd)=
1.707 albertel 2423: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2424: if ($result eq 'ok') {
2425: if (!($perm_reqd eq 'yes')) {
2426: return(&retrievestudentphoto($udom,$unam,$ext));
2427: }
2428: }
2429: }
2430: }
2431: } else {
2432: my ($result,$perm_reqd) =
1.707 albertel 2433: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2434: if ($result eq 'ok') {
2435: if (!($perm_reqd eq 'yes')) {
2436: return(&retrievestudentphoto($udom,$unam,$ext));
2437: }
2438: }
2439: }
2440: return '/adm/lonKaputt/lonlogo_broken.gif';
2441: }
2442:
2443: sub retrievestudentphoto {
2444: my ($udom,$unam,$ext,$type) = @_;
2445: my $home=&Apache::lonnet::homeserver($unam,$udom);
2446: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2447: if ($ret eq 'ok') {
2448: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2449: if ($type eq 'thumbnail') {
2450: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2451: }
2452: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2453: return $tokenurl;
2454: } else {
2455: if ($type eq 'thumbnail') {
2456: return '/adm/lonKaputt/genericstudent_tn.gif';
2457: } else {
2458: return '/adm/lonKaputt/lonlogo_broken.gif';
2459: }
1.617 albertel 2460: }
2461: }
2462:
1.263 www 2463: # -------------------------------------------------------------------- New chat
2464:
2465: sub chatsend {
1.724 raeburn 2466: my ($newentry,$anon,$group)=@_;
1.620 albertel 2467: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2468: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2469: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2470: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2471: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2472: &escape($newentry)).':'.$group,$chome);
1.292 www 2473: }
2474:
2475: # ------------------------------------------ Find current version of a resource
2476:
2477: sub getversion {
2478: my $fname=&clutter(shift);
1.1189 raeburn 2479: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2480: return ¤tversion(&filelocation('',$fname));
2481: }
2482:
2483: sub currentversion {
2484: my $fname=shift;
2485: my $author=$fname;
2486: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2487: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2488: my $home=&homeserver($uname,$udom);
1.292 www 2489: if ($home eq 'no_host') {
2490: return -1;
2491: }
1.1112 www 2492: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2493: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2494: return -1;
2495: }
1.1112 www 2496: return $answer;
1.263 www 2497: }
2498:
1.1111 www 2499: #
2500: # Return special version number of resource if set by override, empty otherwise
2501: #
2502: sub usedversion {
2503: my $fname=shift;
2504: unless ($fname) { $fname=$env{'request.uri'}; }
2505: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2506: if ($urlversion) { return $urlversion; }
2507: return '';
2508: }
2509:
1.1 albertel 2510: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2511:
1.1 albertel 2512: sub subscribe {
2513: my $fname=shift;
1.761 raeburn 2514: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2515: $fname=~s/[\n\r]//g;
1.1 albertel 2516: my $author=$fname;
2517: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2518: my ($udom,$uname)=split(/\//,$author);
2519: my $home=homeserver($uname,$udom);
1.335 albertel 2520: if ($home eq 'no_host') {
2521: return 'not_found';
1.1 albertel 2522: }
2523: my $answer=reply("sub:$fname",$home);
1.64 www 2524: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2525: $answer.=' by '.$home;
2526: }
1.1 albertel 2527: return $answer;
2528: }
2529:
1.8 www 2530: # -------------------------------------------------------------- Replicate file
2531:
2532: sub repcopy {
2533: my $filename=shift;
1.23 www 2534: $filename=~s/\/+/\//g;
1.1142 raeburn 2535: my $londocroot = $perlvar{'lonDocRoot'};
2536: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2537: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2538: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2539: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2540: return &repcopy_userfile($filename);
2541: }
1.532 albertel 2542: $filename=~s/[\n\r]//g;
1.8 www 2543: my $transname="$filename.in.transfer";
1.828 www 2544: # FIXME: this should flock
1.607 raeburn 2545: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2546: my $remoteurl=subscribe($filename);
1.64 www 2547: if ($remoteurl =~ /^con_lost by/) {
2548: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2549: return 'unavailable';
1.8 www 2550: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2551: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2552: return 'not_found';
1.64 www 2553: } elsif ($remoteurl =~ /^rejected by/) {
2554: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2555: return 'forbidden';
1.20 www 2556: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2557: return 'ok';
1.8 www 2558: } else {
1.290 www 2559: my $author=$filename;
2560: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2561: my ($udom,$uname)=split(/\//,$author);
2562: my $home=homeserver($uname,$udom);
2563: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2564: my @parts=split(/\//,$filename);
2565: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2566: if ($path ne "$londocroot/res") {
1.8 www 2567: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2568: return 'bad_request';
1.8 www 2569: }
2570: my $count;
2571: for ($count=5;$count<$#parts;$count++) {
2572: $path.="/$parts[$count]";
2573: if ((-e $path)!=1) {
2574: mkdir($path,0777);
2575: }
2576: }
2577: my $ua=new LWP::UserAgent;
2578: my $request=new HTTP::Request('GET',"$remoteurl");
2579: my $response=$ua->request($request,$transname);
2580: if ($response->is_error()) {
2581: unlink($transname);
2582: my $message=$response->status_line;
1.672 albertel 2583: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2584: ." LWP get: $message: $filename</font>");
1.607 raeburn 2585: return 'unavailable';
1.8 www 2586: } else {
1.16 www 2587: if ($remoteurl!~/\.meta$/) {
2588: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2589: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2590: if ($mresponse->is_error()) {
2591: unlink($filename.'.meta');
2592: &logthis(
1.672 albertel 2593: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2594: }
2595: }
1.8 www 2596: rename($transname,$filename);
1.607 raeburn 2597: return 'ok';
1.8 www 2598: }
1.290 www 2599: }
1.8 www 2600: }
1.330 www 2601: }
2602:
2603: # ------------------------------------------------ Get server side include body
2604: sub ssi_body {
1.381 albertel 2605: my ($filelink,%form)=@_;
1.606 matthew 2606: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2607: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2608: }
1.953 www 2609: my $output='';
2610: my $response;
1.980 raeburn 2611: if ($filelink=~/^https?\:/) {
1.954 raeburn 2612: ($output,$response)=&externalssi($filelink);
1.953 www 2613: } else {
1.1004 droeschl 2614: $filelink .= $filelink=~/\?/ ? '&' : '?';
2615: $filelink .= 'inhibitmenu=yes';
1.953 www 2616: ($output,$response)=&ssi($filelink,%form);
2617: }
1.778 albertel 2618: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2619: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2620: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2621: if (wantarray) {
2622: return ($output, $response);
2623: } else {
2624: return $output;
2625: }
1.8 www 2626: }
2627:
1.15 www 2628: # --------------------------------------------------------- Server Side Include
2629:
1.782 albertel 2630: sub absolute_url {
2631: my ($host_name) = @_;
2632: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2633: if ($host_name eq '') {
2634: $host_name = $ENV{'SERVER_NAME'};
2635: }
2636: return $protocol.$host_name;
2637: }
2638:
1.942 foxr 2639: #
2640: # Server side include.
2641: # Parameters:
2642: # fn Possibly encrypted resource name/id.
2643: # form Hash that describes how the rendering should be done
2644: # and other things.
1.944 foxr 2645: # Returns:
1.950 raeburn 2646: # Scalar context: The content of the response.
2647: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2648: #
1.15 www 2649: sub ssi {
2650:
1.944 foxr 2651: my ($fn,%form)=@_;
1.15 www 2652: my $ua=new LWP::UserAgent;
1.23 www 2653: my $request;
1.711 albertel 2654:
2655: $form{'no_update_last_known'}=1;
1.895 albertel 2656: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2657: if (%form) {
1.782 albertel 2658: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2659: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2660: } else {
1.782 albertel 2661: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2662: }
2663:
1.15 www 2664: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2665: my $response= $ua->request($request);
1.1182 foxr 2666: my $content = $response->content;
2667:
2668:
1.944 foxr 2669: if (wantarray) {
1.1173 foxr 2670: return ($content, $response);
1.944 foxr 2671: } else {
1.1173 foxr 2672: return $content;
1.942 foxr 2673: }
1.324 www 2674: }
2675:
2676: sub externalssi {
2677: my ($url)=@_;
2678: my $ua=new LWP::UserAgent;
2679: my $request=new HTTP::Request('GET',$url);
2680: my $response=$ua->request($request);
1.954 raeburn 2681: if (wantarray) {
2682: return ($response->content, $response);
2683: } else {
2684: return $response->content;
2685: }
1.15 www 2686: }
1.254 www 2687:
1.492 albertel 2688: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2689:
2690: sub allowuploaded {
2691: my ($srcurl,$url)=@_;
2692: $url=&clutter(&declutter($url));
2693: my $dir=$url;
2694: $dir=~s/\/[^\/]+$//;
2695: my %httpref=();
2696: my $httpurl=&hreflocation('',$url);
2697: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2698: &Apache::lonnet::appenv(\%httpref);
1.254 www 2699: }
1.477 raeburn 2700:
1.1193 raeburn 2701: #
2702: # Determine if the current user should be able to edit a particular resource,
2703: # when viewing in course context.
2704: # (a) When viewing resource used to determine if "Edit" item is included in
2705: # Functions.
2706: # (b) When displaying folder contents in course editor, used to determine if
2707: # "Edit" link will be displayed alongside resource.
2708: #
1.1196 raeburn 2709: # input: six args -- filename (decluttered), course number, course domain,
2710: # url, symb (if registered) and group (if this is a group
2711: # item -- e.g., bulletin board, group page etc.).
2712: # output: array of five scalars --
1.1193 raeburn 2713: # $cfile -- url for file editing if editable on current server
2714: # $home -- homeserver of resource (i.e., for author if published,
2715: # or course if uploaded.).
2716: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2717: # $forceedit -- 1 if icon/link should be to go to edit mode
2718: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2719: #
2720:
2721: sub can_edit_resource {
1.1194 raeburn 2722: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2723: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2724: #
2725: # For aboutme pages user can only edit his/her own.
2726: #
1.1199 raeburn 2727: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2728: my ($sdom,$sname) = ($1,$2);
2729: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2730: $home = $env{'user.home'};
2731: $cfile = $resurl;
2732: if ($env{'form.forceedit'}) {
2733: $forceview = 1;
2734: } else {
2735: $forceedit = 1;
2736: }
2737: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2738: } else {
2739: return;
2740: }
2741: }
2742:
2743: if ($env{'request.course.id'}) {
2744: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2745: if ($group ne '') {
2746: # if this is a group homepage or group bulletin board, check group privs
2747: my $allowed = 0;
1.1197 raeburn 2748: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2749: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2750: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2751: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2752: $allowed = 1;
2753: }
1.1197 raeburn 2754: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2755: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2756: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2757: $allowed = 1;
2758: }
2759: }
2760: if ($allowed) {
2761: $home=&homeserver($cnum,$cdom);
2762: if ($env{'form.forceedit'}) {
2763: $forceview = 1;
2764: } else {
2765: $forceedit = 1;
2766: }
2767: $cfile = $resurl;
2768: } else {
2769: return;
2770: }
2771: } else {
1.1208 raeburn 2772: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2773: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2774: return;
2775: }
2776: } elsif (!$crsedit) {
1.1194 raeburn 2777: #
2778: # No edit allowed where CC has switched to student role.
2779: #
2780: return;
2781: }
2782: }
2783: }
2784:
1.1193 raeburn 2785: if ($file ne '') {
2786: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2787: if (&is_course_upload($file,$cnum,$cdom)) {
2788: $uploaded = 1;
2789: $incourse = 1;
1.1193 raeburn 2790: if ($file =~/\.(htm|html|css|js|txt)$/) {
2791: $cfile = &hreflocation('',$file);
1.1201 raeburn 2792: if ($env{'form.forceedit'}) {
2793: $forceview = 1;
2794: } else {
2795: $forceedit = 1;
2796: }
1.1194 raeburn 2797: }
2798: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2799: $incourse = 1;
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2807: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2808: $incourse = 1;
2809: if ($env{'form.forceedit'}) {
2810: $forceview = 1;
2811: } else {
2812: $forceedit = 1;
2813: }
2814: $cfile = $resurl;
1.1199 raeburn 2815: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2816: $incourse = 1;
2817: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2818: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2819: $incourse = 1;
1.1199 raeburn 2820: if ($env{'form.forceedit'}) {
2821: $forceview = 1;
2822: } else {
2823: $forceedit = 1;
2824: }
2825: $cfile = $resurl;
1.1208 raeburn 2826: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2827: $incourse = 1;
2828: if ($env{'form.forceedit'}) {
2829: $forceview = 1;
2830: } else {
2831: $forceedit = 1;
2832: }
2833: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2834: }
2835: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2836: my $template = '/res/lib/templates/simpleproblem.problem';
2837: if (&is_on_map($template)) {
2838: $incourse = 1;
2839: $forceview = 1;
2840: $cfile = $template;
1.1193 raeburn 2841: }
1.1199 raeburn 2842: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2843: $incourse = 1;
2844: if ($env{'form.forceedit'}) {
2845: $forceview = 1;
2846: } else {
2847: $forceedit = 1;
2848: }
2849: $cfile = $resurl;
2850: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2851: $incourse = 1;
2852: $forceview = 1;
2853: if ($symb) {
2854: my ($map,$id,$res)=&decode_symb($symb);
2855: $env{'request.symb'} = $symb;
2856: $cfile = &clutter($res);
2857: } else {
2858: $cfile = $env{'form.suppurl'};
2859: $cfile =~ s{^http://}{};
2860: $cfile = '/adm/wrapper/ext/'.$cfile;
2861: }
1.1234 raeburn 2862: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2863: if ($env{'form.forceedit'}) {
2864: $forceview = 1;
2865: } else {
2866: $forceedit = 1;
2867: }
2868: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2869: }
2870: }
1.1194 raeburn 2871: if ($uploaded || $incourse) {
2872: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2873: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2874: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2875: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2876: # Check that the user has permission to edit this resource
2877: my $setpriv = 1;
2878: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2879: if (defined($cfudom)) {
2880: $home=&homeserver($cfuname,$cfudom);
2881: $cfile=$file;
2882: }
2883: }
1.1194 raeburn 2884: if (($cfile ne '') && (!$incourse || $uploaded) &&
2885: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2886: my @ids=¤t_machine_ids();
2887: unless (grep(/^\Q$home\E$/,@ids)) {
2888: $switchserver=1;
2889: }
2890: }
2891: }
1.1194 raeburn 2892: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2893: }
2894:
2895: sub is_course_upload {
2896: my ($file,$cnum,$cdom) = @_;
2897: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2898: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2899: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2900: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2901: return 1;
2902: }
2903: return;
2904: }
2905:
1.1194 raeburn 2906: sub in_course {
1.1195 raeburn 2907: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2908: if ($hideprivileged) {
2909: my $skipuser;
1.1219 raeburn 2910: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2911: my @possdoms = ($cdom);
2912: if ($coursehash{'checkforpriv'}) {
2913: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2914: }
2915: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2916: $skipuser = 1;
2917: if ($coursehash{'nothideprivileged'}) {
2918: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2919: my $user;
2920: if ($item =~ /:/) {
2921: $user = $item;
2922: } else {
2923: $user = join(':',split(/[\@]/,$item));
2924: }
2925: if ($user eq $uname.':'.$udom) {
2926: undef($skipuser);
2927: last;
2928: }
2929: }
2930: }
2931: if ($skipuser) {
2932: return 0;
2933: }
2934: }
2935: }
1.1194 raeburn 2936: $type ||= 'any';
2937: if (!defined($cdom) || !defined($cnum)) {
2938: my $cid = $env{'request.course.id'};
2939: $cdom = $env{'course.'.$cid.'.domain'};
2940: $cnum = $env{'course.'.$cid.'.num'};
2941: }
2942: my $typesref;
1.1195 raeburn 2943: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2944: $typesref = ['active','previous','future'];
2945: } elsif ($type eq 'previous' || $type eq 'future') {
2946: $typesref = [$type];
2947: }
2948: my %roles = &get_my_roles($uname,$udom,'userroles',
2949: $typesref,undef,[$cdom]);
2950: my ($tmp) = keys(%roles);
2951: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2952: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2953: if (@course_roles > 0) {
2954: return 1;
2955: }
2956: return 0;
2957: }
2958:
1.478 albertel 2959: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2960: # input: action, courseID, current domain, intended
1.637 raeburn 2961: # path to file, source of file, instruction to parse file for objects,
2962: # ref to hash for embedded objects,
2963: # ref to hash for codebase of java objects.
1.1095 raeburn 2964: # reference to scalar to accommodate mime type determined
2965: # from File::MMagic if $parser = parse.
1.637 raeburn 2966: #
1.485 raeburn 2967: # output: url to file (if action was uploaddoc),
2968: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2969: #
1.478 albertel 2970: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2971: # course.
1.477 raeburn 2972: #
1.478 albertel 2973: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2974: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2975: # course's home server.
1.477 raeburn 2976: #
1.478 albertel 2977: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2978: # be copied from $source (current location) to
2979: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2980: # and will then be copied to
2981: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2982: # course's home server.
1.485 raeburn 2983: #
1.481 raeburn 2984: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2985: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2986: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2987: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2988: # in course's home server.
1.637 raeburn 2989: #
1.477 raeburn 2990:
2991: sub process_coursefile {
1.1095 raeburn 2992: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2993: $mimetype)=@_;
1.477 raeburn 2994: my $fetchresult;
1.638 albertel 2995: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2996: if ($action eq 'propagate') {
1.638 albertel 2997: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2998: $home);
1.481 raeburn 2999: } else {
1.477 raeburn 3000: my $fpath = '';
3001: my $fname = $file;
1.478 albertel 3002: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3003: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3004: my $filepath = &build_filepath($fpath);
1.481 raeburn 3005: if ($action eq 'copy') {
3006: if ($source eq '') {
3007: $fetchresult = 'no source file';
3008: return $fetchresult;
3009: } else {
3010: my $destination = $filepath.'/'.$fname;
3011: rename($source,$destination);
3012: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3013: $home);
1.481 raeburn 3014: }
3015: } elsif ($action eq 'uploaddoc') {
3016: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3017: print $fh $env{'form.'.$source};
1.481 raeburn 3018: close($fh);
1.637 raeburn 3019: if ($parser eq 'parse') {
1.1024 raeburn 3020: my $mm = new File::MMagic;
1.1095 raeburn 3021: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3022: if ($type eq 'text/html') {
1.1024 raeburn 3023: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3024: unless ($parse_result eq 'ok') {
3025: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3026: }
1.637 raeburn 3027: }
1.1095 raeburn 3028: if (ref($mimetype)) {
3029: $$mimetype = $type;
3030: }
1.637 raeburn 3031: }
1.477 raeburn 3032: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3033: $home);
1.481 raeburn 3034: if ($fetchresult eq 'ok') {
3035: return '/uploaded/'.$fpath.'/'.$fname;
3036: } else {
3037: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3038: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3039: return '/adm/notfound.html';
3040: }
1.477 raeburn 3041: }
3042: }
1.485 raeburn 3043: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3044: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3045: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3046: }
3047: return $fetchresult;
3048: }
3049:
1.637 raeburn 3050: sub build_filepath {
3051: my ($fpath) = @_;
3052: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3053: unless ($fpath eq '') {
3054: my @parts=split('/',$fpath);
3055: foreach my $part (@parts) {
3056: $filepath.= '/'.$part;
3057: if ((-e $filepath)!=1) {
3058: mkdir($filepath,0777);
3059: }
3060: }
3061: }
3062: return $filepath;
3063: }
3064:
3065: sub store_edited_file {
1.638 albertel 3066: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3067: my $file = $primary_url;
3068: $file =~ s#^/uploaded/$docudom/$docuname/##;
3069: my $fpath = '';
3070: my $fname = $file;
3071: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3072: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3073: my $filepath = &build_filepath($fpath);
3074: open(my $fh,'>'.$filepath.'/'.$fname);
3075: print $fh $content;
3076: close($fh);
1.638 albertel 3077: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3078: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3079: $home);
1.637 raeburn 3080: if ($$fetchresult eq 'ok') {
3081: return '/uploaded/'.$fpath.'/'.$fname;
3082: } else {
1.638 albertel 3083: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3084: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3085: return '/adm/notfound.html';
3086: }
3087: }
3088:
1.531 albertel 3089: sub clean_filename {
1.831 albertel 3090: my ($fname,$args)=@_;
1.315 www 3091: # Replace Windows backslashes by forward slashes
1.257 www 3092: $fname=~s/\\/\//g;
1.831 albertel 3093: if (!$args->{'keep_path'}) {
3094: # Get rid of everything but the actual filename
3095: $fname=~s/^.*\/([^\/]+)$/$1/;
3096: }
1.315 www 3097: # Replace spaces by underscores
3098: $fname=~s/\s+/\_/g;
3099: # Replace all other weird characters by nothing
1.831 albertel 3100: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3101: # Replace all .\d. sequences with _\d. so they no longer look like version
3102: # numbers
3103: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3104: return $fname;
3105: }
1.1051 raeburn 3106: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3107: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3108: # image with the same aspect ratio as the original, but with dimensions which do
3109: # not exceed $resizewidth and $resizeheight.
3110:
1.984 neumanie 3111: sub resizeImage {
1.1051 raeburn 3112: my ($img_path,$resizewidth,$resizeheight) = @_;
3113: my $ima = Image::Magick->new;
3114: my $resized;
3115: if (-e $img_path) {
3116: $ima->Read($img_path);
3117: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3118: my $width = $ima->Get('width');
3119: my $height = $ima->Get('height');
3120: if ($width > $resizewidth) {
3121: my $factor = $width/$resizewidth;
3122: my $newheight = $height/$factor;
3123: $ima->Scale(width=>$resizewidth,height=>$newheight);
3124: $resized = 1;
3125: }
3126: }
3127: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3128: my $width = $ima->Get('width');
3129: my $height = $ima->Get('height');
3130: if ($height > $resizeheight) {
3131: my $factor = $height/$resizeheight;
3132: my $newwidth = $width/$factor;
3133: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3134: $resized = 1;
3135: }
3136: }
3137: if ($resized) {
3138: $ima->Write($img_path);
3139: }
3140: }
3141: return;
1.977 amueller 3142: }
3143:
1.608 albertel 3144: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3145: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3146: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3147: # $context - possible values: coursedoc, existingfile, overwrite,
3148: # canceloverwrite, or ''.
3149: # if 'coursedoc': upload to the current course
3150: # if 'existingfile': write file to tmp/overwrites directory
3151: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3152: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3153: # $subdir - directory in userfile to store the file into
1.858 raeburn 3154: # $parser - instruction to parse file for objects ($parser = parse)
3155: # $allfiles - reference to hash for embedded objects
3156: # $codebase - reference to hash for codebase of java objects
3157: # $desuname - username for permanent storage of uploaded file
3158: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3159: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3160: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3161: # $resizewidth - width (pixels) to which to resize uploaded image
3162: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3163: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3164: # from File::MMagic.
1.858 raeburn 3165: #
1.686 albertel 3166: # output: url of file in userspace, or error: <message>
3167: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3168:
1.531 albertel 3169: sub userfileupload {
1.1090 raeburn 3170: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3171: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3172: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3173: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3174: $fname=&clean_filename($fname);
1.1090 raeburn 3175: # See if there is anything left
1.257 www 3176: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3177: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3178: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3179: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3180: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3181: my $now = time;
1.1090 raeburn 3182: my $filepath;
1.1095 raeburn 3183: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3184: $filepath = 'tmp/helprequests/'.$now;
3185: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3186: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3187: '_'.$env{'user.domain'}.'/pending';
3188: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3189: my ($docuname,$docudom);
3190: if ($destudom) {
3191: $docudom = $destudom;
3192: } else {
3193: $docudom = $env{'user.domain'};
3194: }
3195: if ($destuname) {
3196: $docuname = $destuname;
3197: } else {
3198: $docuname = $env{'user.name'};
3199: }
3200: if (exists($env{'form.group'})) {
3201: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3202: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3203: }
3204: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3205: if ($context eq 'canceloverwrite') {
3206: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3207: if (-e $tempfile) {
3208: my @info = stat($tempfile);
3209: if ($info[9] eq $env{'form.timestamp'}) {
3210: unlink($tempfile);
3211: }
3212: }
3213: return;
1.523 raeburn 3214: }
3215: }
1.1090 raeburn 3216: # Create the directory if not present
1.741 raeburn 3217: my @parts=split(/\//,$filepath);
3218: my $fullpath = $perlvar{'lonDaemons'};
3219: for (my $i=0;$i<@parts;$i++) {
3220: $fullpath .= '/'.$parts[$i];
3221: if ((-e $fullpath)!=1) {
3222: mkdir($fullpath,0777);
3223: }
3224: }
3225: open(my $fh,'>'.$fullpath.'/'.$fname);
3226: print $fh $env{'form.'.$formname};
3227: close($fh);
1.1090 raeburn 3228: if ($context eq 'existingfile') {
3229: my @info = stat($fullpath.'/'.$fname);
3230: return ($fullpath.'/'.$fname,$info[9]);
3231: } else {
3232: return $fullpath.'/'.$fname;
3233: }
1.523 raeburn 3234: }
1.995 raeburn 3235: if ($subdir eq 'scantron') {
3236: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3237: } else {
1.995 raeburn 3238: $fname="$subdir/$fname";
3239: }
1.1090 raeburn 3240: if ($context eq 'coursedoc') {
1.638 albertel 3241: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3242: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3243: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3244: return &finishuserfileupload($docuname,$docudom,
3245: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3246: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3247: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3248: } else {
1.1218 raeburn 3249: if ($env{'form.folder'}) {
3250: $fname=$env{'form.folder'}.'/'.$fname;
3251: }
1.638 albertel 3252: return &process_coursefile('uploaddoc',$docuname,$docudom,
3253: $fname,$formname,$parser,
1.1095 raeburn 3254: $allfiles,$codebase,$mimetype);
1.481 raeburn 3255: }
1.719 banghart 3256: } elsif (defined($destuname)) {
3257: my $docuname=$destuname;
3258: my $docudom=$destudom;
1.860 raeburn 3259: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3260: $parser,$allfiles,$codebase,
1.1051 raeburn 3261: $thumbwidth,$thumbheight,
1.1095 raeburn 3262: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3263: } else {
1.638 albertel 3264: my $docuname=$env{'user.name'};
3265: my $docudom=$env{'user.domain'};
1.1220 raeburn 3266: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3267: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3268: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3269: }
1.860 raeburn 3270: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3271: $parser,$allfiles,$codebase,
1.1051 raeburn 3272: $thumbwidth,$thumbheight,
1.1095 raeburn 3273: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3274: }
1.271 www 3275: }
3276:
3277: sub finishuserfileupload {
1.860 raeburn 3278: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3279: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3280: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3281: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3282:
1.860 raeburn 3283: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3284: $file=$fname;
3285: if ($fname=~m|/|) {
3286: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3287: $path.=$fnamepath.'/';
3288: }
1.259 www 3289: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3290: my $count;
3291: for ($count=4;$count<=$#parts;$count++) {
3292: $filepath.="/$parts[$count]";
3293: if ((-e $filepath)!=1) {
3294: mkdir($filepath,0777);
3295: }
3296: }
1.984 neumanie 3297:
1.258 www 3298: # Save the file
3299: {
1.701 albertel 3300: if (!open(FH,'>'.$filepath.'/'.$file)) {
3301: &logthis('Failed to create '.$filepath.'/'.$file);
3302: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3303: return '/adm/notfound.html';
3304: }
1.1090 raeburn 3305: if ($context eq 'overwrite') {
1.1117 foxr 3306: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3307: my $target = $filepath.'/'.$file;
3308: if (-e $source) {
3309: my @info = stat($source);
3310: if ($info[9] eq $env{'form.timestamp'}) {
3311: unless (&File::Copy::move($source,$target)) {
3312: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3313: return "Moving from $source failed";
3314: }
3315: } else {
3316: return "Temporary file: $source had unexpected date/time for last modification";
3317: }
3318: } else {
3319: return "Temporary file: $source missing";
3320: }
3321: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3322: &logthis('Failed to write to '.$filepath.'/'.$file);
3323: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3324: return '/adm/notfound.html';
3325: }
1.570 albertel 3326: close(FH);
1.1051 raeburn 3327: if ($resizewidth && $resizeheight) {
3328: my $mm = new File::MMagic;
3329: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3330: if ($mime_type =~ m{^image/}) {
3331: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3332: }
1.977 amueller 3333: }
1.258 www 3334: }
1.1152 raeburn 3335: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3336: if (ref($mimetype)) {
3337: if ($$mimetype eq '') {
3338: my $mm = new File::MMagic;
3339: my $type = $mm->checktype_filename($filepath.'/'.$file);
3340: $$mimetype = $type;
3341: }
3342: }
3343: }
1.637 raeburn 3344: if ($parser eq 'parse') {
1.1152 raeburn 3345: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3346: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3347: $allfiles,$codebase);
3348: unless ($parse_result eq 'ok') {
3349: &logthis('Failed to parse '.$filepath.$file.
3350: ' for embedded media: '.$parse_result);
3351: }
1.637 raeburn 3352: }
3353: }
1.860 raeburn 3354: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3355: my $input = $filepath.'/'.$file;
3356: my $output = $filepath.'/'.'tn-'.$file;
3357: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3358: system("convert -sample $thumbsize $input $output");
3359: if (-e $filepath.'/'.'tn-'.$file) {
3360: $fetchthumb = 1;
3361: }
3362: }
1.858 raeburn 3363:
1.259 www 3364: # Notify homeserver to grep it
3365: #
1.984 neumanie 3366: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3367: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3368: if ($fetchresult eq 'ok') {
1.860 raeburn 3369: if ($fetchthumb) {
3370: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3371: if ($thumbresult ne 'ok') {
3372: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3373: $docuhome.': '.$thumbresult);
3374: }
3375: }
1.259 www 3376: #
1.258 www 3377: # Return the URL to it
1.494 albertel 3378: return '/uploaded/'.$path.$file;
1.263 www 3379: } else {
1.494 albertel 3380: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3381: ': '.$fetchresult);
1.263 www 3382: return '/adm/notfound.html';
1.858 raeburn 3383: }
1.493 albertel 3384: }
3385:
1.637 raeburn 3386: sub extract_embedded_items {
1.961 raeburn 3387: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3388: my @state = ();
1.1164 raeburn 3389: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3390: my %javafiles = (
3391: codebase => '',
3392: code => '',
3393: archive => ''
3394: );
3395: my %mediafiles = (
3396: src => '',
3397: movie => '',
3398: );
1.648 raeburn 3399: my $p;
3400: if ($content) {
3401: $p = HTML::LCParser->new($content);
3402: } else {
1.961 raeburn 3403: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3404: }
1.641 albertel 3405: while (my $t=$p->get_token()) {
1.640 albertel 3406: if ($t->[0] eq 'S') {
3407: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3408: push(@state, $tagname);
1.648 raeburn 3409: if (lc($tagname) eq 'allow') {
3410: &add_filetype($allfiles,$attr->{'src'},'src');
3411: }
1.640 albertel 3412: if (lc($tagname) eq 'img') {
3413: &add_filetype($allfiles,$attr->{'src'},'src');
3414: }
1.886 albertel 3415: if (lc($tagname) eq 'a') {
1.1222 raeburn 3416: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3417: &add_filetype($allfiles,$attr->{'href'},'href');
3418: }
1.886 albertel 3419: }
1.645 raeburn 3420: if (lc($tagname) eq 'script') {
1.1164 raeburn 3421: my $src;
1.645 raeburn 3422: if ($attr->{'archive'} =~ /\.jar$/i) {
3423: &add_filetype($allfiles,$attr->{'archive'},'archive');
3424: } else {
1.1164 raeburn 3425: if ($attr->{'src'} ne '') {
3426: $src = $attr->{'src'};
3427: &add_filetype($allfiles,$src,'src');
3428: }
3429: }
3430: my $text = $p->get_trimmed_text();
3431: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3432: my @swfargs = split(/,/,$1);
3433: foreach my $item (@swfargs) {
3434: $item =~ s/["']//g;
3435: $item =~ s/^\s+//;
3436: $item =~ s/\s+$//;
3437: }
3438: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3439: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3440: push(@{$related{$swfargs[0]}},$swfargs[2]);
3441: } else {
3442: $related{$swfargs[0]} = [$swfargs[2]];
3443: }
3444: }
1.645 raeburn 3445: }
3446: }
3447: if (lc($tagname) eq 'link') {
3448: if (lc($attr->{'rel'}) eq 'stylesheet') {
3449: &add_filetype($allfiles,$attr->{'href'},'href');
3450: }
3451: }
1.640 albertel 3452: if (lc($tagname) eq 'object' ||
3453: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3454: foreach my $item (keys(%javafiles)) {
3455: $javafiles{$item} = '';
3456: }
1.1164 raeburn 3457: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3458: $lastids{lc($tagname)} = $attr->{'id'};
3459: }
1.640 albertel 3460: }
3461: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3462: my $name = lc($attr->{'name'});
3463: foreach my $item (keys(%javafiles)) {
3464: if ($name eq $item) {
3465: $javafiles{$item} = $attr->{'value'};
3466: last;
3467: }
3468: }
1.1164 raeburn 3469: my $pathfrom;
1.640 albertel 3470: foreach my $item (keys(%mediafiles)) {
3471: if ($name eq $item) {
1.1164 raeburn 3472: $pathfrom = $attr->{'value'};
3473: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3474: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3475: last;
3476: }
3477: }
1.1164 raeburn 3478: if ($name eq 'flashvars') {
3479: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3480: }
3481: if ($pathfrom ne '') {
3482: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3483: $pathfrom);
3484: }
1.640 albertel 3485: }
3486: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3487: foreach my $item (keys(%javafiles)) {
3488: if ($attr->{$item}) {
3489: $javafiles{$item} = $attr->{$item};
3490: last;
3491: }
3492: }
3493: foreach my $item (keys(%mediafiles)) {
3494: if ($attr->{$item}) {
3495: &add_filetype($allfiles,$attr->{$item},$item);
3496: last;
3497: }
3498: }
1.1164 raeburn 3499: if (lc($tagname) eq 'embed') {
3500: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3501: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3502: $attr->{'src'});
3503: }
3504: }
1.640 albertel 3505: }
1.1243 raeburn 3506: if (lc($tagname) eq 'iframe') {
3507: my $src = $attr->{'src'} ;
3508: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3509: &add_filetype($allfiles,$src,'src');
3510: } elsif ($src =~ m{^/}) {
3511: if ($env{'request.course.id'}) {
3512: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3513: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3514: my $url = &hreflocation('',$fullpath);
3515: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3516: my $relpath = $1;
3517: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3518: &add_filetype($allfiles,$1,'src');
3519: }
3520: }
3521: }
3522: }
3523: }
1.1164 raeburn 3524: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3525: pop(@state);
1.1164 raeburn 3526: }
1.640 albertel 3527: } elsif ($t->[0] eq 'E') {
3528: my ($tagname) = ($t->[1]);
3529: if ($javafiles{'codebase'} ne '') {
3530: $javafiles{'codebase'} .= '/';
3531: }
3532: if (lc($tagname) eq 'applet' ||
3533: lc($tagname) eq 'object' ||
3534: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3535: ) {
3536: foreach my $item (keys(%javafiles)) {
3537: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3538: my $file=$javafiles{'codebase'}.$javafiles{$item};
3539: &add_filetype($allfiles,$file,$item);
3540: }
3541: }
3542: }
3543: pop @state;
3544: }
3545: }
1.1164 raeburn 3546: foreach my $id (sort(keys(%flashvars))) {
3547: if ($shockwave{$id} ne '') {
3548: my @pairs = split(/\&/,$flashvars{$id});
3549: foreach my $pair (@pairs) {
3550: my ($key,$value) = split(/\=/,$pair);
3551: if ($key eq 'thumb') {
3552: &add_filetype($allfiles,$value,$key);
3553: } elsif ($key eq 'content') {
3554: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3555: my ($ext) = ($value =~ /\.([^.]+)$/);
3556: if ($ext ne '') {
3557: &add_filetype($allfiles,$path.$value,$ext);
3558: }
3559: }
3560: }
3561: }
3562: }
1.637 raeburn 3563: return 'ok';
3564: }
3565:
1.639 albertel 3566: sub add_filetype {
3567: my ($allfiles,$file,$type)=@_;
3568: if (exists($allfiles->{$file})) {
3569: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3570: push(@{$allfiles->{$file}}, &escape($type));
3571: }
3572: } else {
3573: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3574: }
3575: }
3576:
1.1164 raeburn 3577: sub embedded_dependency {
3578: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3579: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3580: if (($identifier ne '') &&
3581: (ref($related->{$identifier}) eq 'ARRAY') &&
3582: ($pathfrom ne '')) {
3583: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3584: foreach my $dep (@{$related->{$identifier}}) {
3585: &add_filetype($allfiles,$path.$dep,'object');
3586: }
3587: }
3588: }
3589: return;
3590: }
3591:
1.493 albertel 3592: sub removeuploadedurl {
1.984 neumanie 3593: my ($url)=@_;
3594: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3595: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3596: }
3597:
3598: sub removeuserfile {
3599: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3600: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3601: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3602: if ($result eq 'ok') {
1.798 raeburn 3603: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3604: my $metafile = $fname.'.meta';
3605: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3606: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3607: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3608: my $sqlresult =
1.823 albertel 3609: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3610: 'portfolio_metadata',$group,
3611: 'delete');
1.798 raeburn 3612: }
3613: }
3614: return $result;
1.257 www 3615: }
1.15 www 3616:
1.530 albertel 3617: sub mkdiruserfile {
3618: my ($docuname,$docudom,$dir)=@_;
3619: my $home=&homeserver($docuname,$docudom);
3620: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3621: }
3622:
1.531 albertel 3623: sub renameuserfile {
3624: my ($docuname,$docudom,$old,$new)=@_;
3625: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3626: my $result = &reply("renameuserfile:$docudom:$docuname:".
3627: &escape("$old").':'.&escape("$new"),$home);
3628: if ($result eq 'ok') {
3629: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3630: my $oldmeta = $old.'.meta';
3631: my $newmeta = $new.'.meta';
3632: my $metaresult =
3633: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3634: my $url = "/uploaded/$docudom/$docuname/$old";
3635: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3636: my $sqlresult =
1.823 albertel 3637: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3638: 'portfolio_metadata',$group,
3639: 'delete');
1.798 raeburn 3640: }
3641: }
3642: return $result;
1.531 albertel 3643: }
3644:
1.14 www 3645: # ------------------------------------------------------------------------- Log
3646:
3647: sub log {
3648: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3649: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3650: }
3651:
3652: # ------------------------------------------------------------------ Course Log
1.352 www 3653: #
3654: # This routine flushes several buffers of non-mission-critical nature
3655: #
1.157 www 3656:
3657: sub flushcourselogs {
1.352 www 3658: &logthis('Flushing log buffers');
3659: #
3660: # course logs
3661: # This is a log of all transactions in a course, which can be used
3662: # for data mining purposes
3663: #
3664: # It also collects the courseid database, which lists last transaction
3665: # times and course titles for all courseids
3666: #
3667: my %courseidbuffer=();
1.921 raeburn 3668: foreach my $crsid (keys(%courselogs)) {
1.352 www 3669: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3670: &escape($courselogs{$crsid}),
3671: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3672: delete $courselogs{$crsid};
3673: } else {
3674: &logthis('Failed to flush log buffer for '.$crsid);
3675: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3676: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3677: " exceeded maximum size, deleting.</font>");
3678: delete $courselogs{$crsid};
3679: }
1.352 www 3680: }
1.920 raeburn 3681: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3682: 'description' => $coursedescrbuf{$crsid},
3683: 'inst_code' => $courseinstcodebuf{$crsid},
3684: 'type' => $coursetypebuf{$crsid},
3685: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3686: };
1.191 harris41 3687: }
1.352 www 3688: #
3689: # Write course id database (reverse lookup) to homeserver of courses
3690: # Is used in pickcourse
3691: #
1.840 albertel 3692: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3693: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3694: $courseidbuffer{$crs_home},
3695: $crs_home,'timeonly');
1.352 www 3696: }
3697: #
3698: # File accesses
3699: # Writes to the dynamic metadata of resources to get hit counts, etc.
3700: #
1.449 matthew 3701: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3702: if ($entry =~ /___count$/) {
3703: my ($dom,$name);
1.807 albertel 3704: ($dom,$name,undef)=
1.811 albertel 3705: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3706: if (! defined($dom) || $dom eq '' ||
3707: ! defined($name) || $name eq '') {
1.620 albertel 3708: my $cid = $env{'request.course.id'};
3709: $dom = $env{'request.'.$cid.'.domain'};
3710: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3711: }
1.450 matthew 3712: my $value = $accesshash{$entry};
3713: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3714: my %temphash=($url => $value);
1.449 matthew 3715: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3716: if ($result eq 'ok') {
3717: delete $accesshash{$entry};
3718: }
3719: } else {
1.811 albertel 3720: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3721: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3722: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3723: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3724: delete $accesshash{$entry};
3725: }
1.185 www 3726: }
1.191 harris41 3727: }
1.352 www 3728: #
3729: # Roles
3730: # Reverse lookup of user roles for course faculty/staff and co-authorship
3731: #
1.800 albertel 3732: foreach my $entry (keys(%userrolehash)) {
1.351 www 3733: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3734: split(/\:/,$entry);
3735: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3736: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3737: $rudom,$runame) eq 'ok') {
3738: delete $userrolehash{$entry};
3739: }
3740: }
1.662 raeburn 3741: #
3742: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3743: #
3744: my %domrolebuffer = ();
1.1000 raeburn 3745: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3746: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3747: if ($domrolebuffer{$rudom}) {
3748: $domrolebuffer{$rudom}.='&'.&escape($entry).
3749: '='.&escape($domainrolehash{$entry});
3750: } else {
3751: $domrolebuffer{$rudom}.=&escape($entry).
3752: '='.&escape($domainrolehash{$entry});
3753: }
3754: delete $domainrolehash{$entry};
3755: }
3756: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3757: my %servers = &get_servers($dom,'library');
3758: foreach my $tryserver (keys(%servers)) {
3759: unless (&reply('domroleput:'.$dom.':'.
3760: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3761: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3762: }
1.662 raeburn 3763: }
3764: }
1.186 www 3765: $dumpcount++;
1.157 www 3766: }
3767:
3768: sub courselog {
3769: my $what=shift;
1.158 www 3770: $what=time.':'.$what;
1.620 albertel 3771: unless ($env{'request.course.id'}) { return ''; }
3772: $coursedombuf{$env{'request.course.id'}}=
3773: $env{'course.'.$env{'request.course.id'}.'.domain'};
3774: $coursenumbuf{$env{'request.course.id'}}=
3775: $env{'course.'.$env{'request.course.id'}.'.num'};
3776: $coursehombuf{$env{'request.course.id'}}=
3777: $env{'course.'.$env{'request.course.id'}.'.home'};
3778: $coursedescrbuf{$env{'request.course.id'}}=
3779: $env{'course.'.$env{'request.course.id'}.'.description'};
3780: $courseinstcodebuf{$env{'request.course.id'}}=
3781: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3782: $courseownerbuf{$env{'request.course.id'}}=
3783: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3784: $coursetypebuf{$env{'request.course.id'}}=
3785: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3786: if (defined $courselogs{$env{'request.course.id'}}) {
3787: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3788: } else {
1.620 albertel 3789: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3790: }
1.620 albertel 3791: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3792: &flushcourselogs();
3793: }
1.158 www 3794: }
3795:
3796: sub courseacclog {
3797: my $fnsymb=shift;
1.620 albertel 3798: unless ($env{'request.course.id'}) { return ''; }
3799: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3800: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3801: $what.=':POST';
1.583 matthew 3802: # FIXME: Probably ought to escape things....
1.800 albertel 3803: foreach my $key (keys(%env)) {
3804: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3805: my $formitem = $1;
3806: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3807: $what.=':'.$formitem.'='.$env{$key};
3808: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3809: $what.=':'.$formitem.'='.$env{$key};
3810: }
1.158 www 3811: }
1.191 harris41 3812: }
1.583 matthew 3813: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3814: # FIXME: We should not be depending on a form parameter that someone
3815: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3816: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3817: $what.= ':POST';
3818: # FIXME: Probably ought to escape things....
3819: foreach my $element ('courseexp','crsfulltext','crsrelated',
3820: 'crsdiscuss') {
1.620 albertel 3821: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3822: }
3823: }
1.158 www 3824: }
3825: &courselog($what);
1.149 www 3826: }
3827:
1.185 www 3828: sub countacc {
3829: my $url=&declutter(shift);
1.458 matthew 3830: return if (! defined($url) || $url eq '');
1.620 albertel 3831: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3832: #
3833: # Mark that this url was used in this course
3834: #
1.620 albertel 3835: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3836: #
3837: # Increase the access count for this resource in this child process
3838: #
1.281 www 3839: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3840: $accesshash{$key}++;
1.185 www 3841: }
1.349 www 3842:
1.361 www 3843: sub linklog {
3844: my ($from,$to)=@_;
3845: $from=&declutter($from);
3846: $to=&declutter($to);
3847: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3848: $accesshash{$to.'___'.$from.'___goto'}=1;
3849: }
1.1160 www 3850:
3851: sub statslog {
3852: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3853: if ($users<2) { return; }
3854: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3855: 'course' => $env{'request.course.id'},
3856: 'sections' => '"all"',
3857: 'num_students' => $users,
3858: 'part' => $part,
3859: 'symb' => $symb,
3860: 'mean_tries' => $av_attempts,
3861: 'deg_of_diff' => $degdiff});
3862: foreach my $key (keys(%dynstore)) {
3863: $accesshash{$key}=$dynstore{$key};
3864: }
3865: }
1.361 www 3866:
1.349 www 3867: sub userrolelog {
3868: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3869: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3870: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3871: $userrolehash
3872: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3873: =$tend.':'.$tstart;
1.662 raeburn 3874: }
1.1169 droeschl 3875: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3876: $userrolehash
3877: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3878: =$tend.':'.$tstart;
3879: }
1.1169 droeschl 3880: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3881: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3882: $domainrolehash
3883: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3884: = $tend.':'.$tstart;
3885: }
1.351 www 3886: }
3887:
1.957 raeburn 3888: sub courserolelog {
3889: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3890: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3891: my $cdom = $1;
3892: my $cnum = $2;
3893: my $sec = $3;
3894: my $namespace = 'rolelog';
3895: my %storehash = (
3896: role => $trole,
3897: start => $tstart,
3898: end => $tend,
3899: selfenroll => $selfenroll,
3900: context => $context,
3901: );
3902: if ($trole eq 'gr') {
3903: $namespace = 'groupslog';
3904: $storehash{'group'} = $sec;
3905: } else {
3906: $storehash{'section'} = $sec;
3907: }
1.1188 raeburn 3908: &write_log('course',$namespace,\%storehash,$delflag,$username,
3909: $domain,$cnum,$cdom);
1.1184 raeburn 3910: if (($trole ne 'st') || ($sec ne '')) {
3911: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3912: }
3913: }
3914: return;
3915: }
3916:
1.1184 raeburn 3917: sub domainrolelog {
3918: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3919: if ($area =~ m{^/($match_domain)/$}) {
3920: my $cdom = $1;
3921: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3922: my $namespace = 'rolelog';
3923: my %storehash = (
3924: role => $trole,
3925: start => $tstart,
3926: end => $tend,
3927: context => $context,
3928: );
1.1188 raeburn 3929: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3930: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3931: }
3932: return;
3933:
3934: }
3935:
3936: sub coauthorrolelog {
3937: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3938: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3939: my $audom = $1;
3940: my $auname = $2;
3941: my $namespace = 'rolelog';
3942: my %storehash = (
3943: role => $trole,
3944: start => $tstart,
3945: end => $tend,
3946: context => $context,
3947: );
1.1188 raeburn 3948: &write_log('author',$namespace,\%storehash,$delflag,$username,
3949: $domain,$auname,$audom);
1.1184 raeburn 3950: }
3951: return;
3952: }
3953:
1.351 www 3954: sub get_course_adv_roles {
1.948 raeburn 3955: my ($cid,$codes) = @_;
1.620 albertel 3956: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3957: my %coursehash=&coursedescription($cid);
1.988 raeburn 3958: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3959: my %nothide=();
1.800 albertel 3960: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3961: if ($user !~ /:/) {
3962: $nothide{join(':',split(/[\@]/,$user))}=1;
3963: } else {
3964: $nothide{$user}=1;
3965: }
1.470 www 3966: }
1.1219 raeburn 3967: my @possdoms = ($coursehash{'domain'});
3968: if ($coursehash{'checkforpriv'}) {
3969: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3970: }
1.351 www 3971: my %returnhash=();
3972: my %dumphash=
3973: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3974: my $now=time;
1.997 raeburn 3975: my %privileged;
1.1000 raeburn 3976: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3977: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3978: if (($tstart) && ($tstart<0)) { next; }
3979: if (($tend) && ($tend<$now)) { next; }
3980: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3981: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3982: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3983: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3984: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3985: if ($role eq 'cr') { next; }
1.948 raeburn 3986: if ($codes) {
3987: if ($section) { $role .= ':'.$section; }
3988: if ($returnhash{$role}) {
3989: $returnhash{$role}.=','.$username.':'.$domain;
3990: } else {
3991: $returnhash{$role}=$username.':'.$domain;
3992: }
1.351 www 3993: } else {
1.988 raeburn 3994: my $key=&plaintext($role,$crstype);
1.973 bisitz 3995: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3996: if ($returnhash{$key}) {
3997: $returnhash{$key}.=','.$username.':'.$domain;
3998: } else {
3999: $returnhash{$key}=$username.':'.$domain;
4000: }
1.351 www 4001: }
1.948 raeburn 4002: }
1.400 www 4003: return %returnhash;
4004: }
4005:
4006: sub get_my_roles {
1.937 raeburn 4007: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4008: unless (defined($uname)) { $uname=$env{'user.name'}; }
4009: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4010: my (%dumphash,%nothide);
1.1086 raeburn 4011: if ($context eq 'userroles') {
1.1166 raeburn 4012: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4013: } else {
1.1219 raeburn 4014: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4015: if ($hidepriv) {
4016: my %coursehash=&coursedescription($udom.'_'.$uname);
4017: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4018: if ($user !~ /:/) {
4019: $nothide{join(':',split(/[\@]/,$user))} = 1;
4020: } else {
4021: $nothide{$user} = 1;
4022: }
4023: }
4024: }
1.858 raeburn 4025: }
1.400 www 4026: my %returnhash=();
4027: my $now=time;
1.999 raeburn 4028: my %privileged;
1.800 albertel 4029: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4030: my ($role,$tend,$tstart);
4031: if ($context eq 'userroles') {
1.1149 raeburn 4032: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4033: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4034: } else {
4035: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4036: }
1.400 www 4037: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4038: my $status = 'active';
1.939 raeburn 4039: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4040: $status = 'previous';
4041: }
4042: if (($tstart) && ($now<$tstart)) {
4043: $status = 'future';
4044: }
4045: if (ref($types) eq 'ARRAY') {
4046: if (!grep(/^\Q$status\E$/,@{$types})) {
4047: next;
4048: }
4049: } else {
4050: if ($status ne 'active') {
4051: next;
4052: }
4053: }
1.867 raeburn 4054: my ($rolecode,$username,$domain,$section,$area);
4055: if ($context eq 'userroles') {
1.1186 raeburn 4056: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4057: (undef,$domain,$username,$section) = split(/\//,$area);
4058: } else {
4059: ($role,$username,$domain,$section) = split(/\:/,$entry);
4060: }
1.832 raeburn 4061: if (ref($roledoms) eq 'ARRAY') {
4062: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4063: next;
4064: }
4065: }
4066: if (ref($roles) eq 'ARRAY') {
4067: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4068: if ($role =~ /^cr\//) {
4069: if (!grep(/^cr$/,@{$roles})) {
4070: next;
4071: }
1.1104 raeburn 4072: } elsif ($role =~ /^gr\//) {
4073: if (!grep(/^gr$/,@{$roles})) {
4074: next;
4075: }
1.922 raeburn 4076: } else {
4077: next;
4078: }
1.832 raeburn 4079: }
1.867 raeburn 4080: }
1.937 raeburn 4081: if ($hidepriv) {
1.1219 raeburn 4082: my @privroles = ('dc','su');
1.999 raeburn 4083: if ($context eq 'userroles') {
1.1219 raeburn 4084: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4085: } else {
1.1219 raeburn 4086: my $possdoms = [$domain];
4087: if (ref($roledoms) eq 'ARRAY') {
4088: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4089: }
1.1219 raeburn 4090: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4091: if (!$nothide{$username.':'.$domain}) {
4092: next;
4093: }
4094: }
1.937 raeburn 4095: }
4096: }
1.933 raeburn 4097: if ($withsec) {
4098: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4099: $tstart.':'.$tend;
4100: } else {
4101: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4102: }
1.832 raeburn 4103: }
1.373 www 4104: return %returnhash;
1.399 www 4105: }
4106:
4107: # ----------------------------------------------------- Frontpage Announcements
4108: #
4109: #
4110:
4111: sub postannounce {
4112: my ($server,$text)=@_;
1.844 albertel 4113: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4114: unless ($text=~/\w/) { $text=''; }
4115: return &reply('setannounce:'.&escape($text),$server);
4116: }
4117:
4118: sub getannounce {
1.448 albertel 4119:
4120: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4121: my $announcement='';
1.800 albertel 4122: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4123: close($fh);
1.399 www 4124: if ($announcement=~/\w/) {
4125: return
4126: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4127: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4128: } else {
4129: return '';
4130: }
4131: } else {
4132: return '';
4133: }
1.351 www 4134: }
1.353 www 4135:
4136: # ---------------------------------------------------------- Course ID routines
4137: # Deal with domain's nohist_courseid.db files
4138: #
4139:
4140: sub courseidput {
1.921 raeburn 4141: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4142: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4143: my $outcome;
4144: if ($caller eq 'timeonly') {
4145: my $cids = '';
4146: foreach my $item (keys(%$storehash)) {
4147: $cids.=&escape($item).'&';
4148: }
4149: $cids=~s/\&$//;
4150: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4151: $coursehome);
4152: } else {
4153: my $items = '';
4154: foreach my $item (keys(%$storehash)) {
4155: $items.= &escape($item).'='.
4156: &freeze_escape($$storehash{$item}).'&';
4157: }
4158: $items=~s/\&$//;
4159: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4160: $coursehome);
1.918 raeburn 4161: }
4162: if ($outcome eq 'unknown_cmd') {
4163: my $what;
4164: foreach my $cid (keys(%$storehash)) {
4165: $what .= &escape($cid).'=';
1.921 raeburn 4166: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4167: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4168: }
4169: $what =~ s/\:$/&/;
4170: }
4171: $what =~ s/\&$//;
4172: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4173: } else {
4174: return $outcome;
4175: }
1.353 www 4176: }
4177:
4178: sub courseiddump {
1.921 raeburn 4179: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4180: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4181: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4182: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4183: $hasuniquecode)=@_;
1.918 raeburn 4184: my $as_hash = 1;
4185: my %returnhash;
4186: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4187: my %libserv = &all_library();
4188: foreach my $tryserver (keys(%libserv)) {
4189: if ( ( $hostidflag == 1
4190: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4191: || (!defined($hostidflag)) ) {
4192:
1.918 raeburn 4193: if (($domfilter eq '') ||
4194: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4195: my $rep;
4196: if (grep { $_ eq $tryserver } current_machine_ids()) {
4197: $rep = LONCAPA::Lond::dump_course_id_handler(
4198: join(":", (&host_domain($tryserver), $sincefilter,
4199: &escape($descfilter), &escape($instcodefilter),
4200: &escape($ownerfilter), &escape($coursefilter),
4201: &escape($typefilter), &escape($regexp_ok),
4202: $as_hash, &escape($selfenrollonly),
4203: &escape($catfilter), $showhidden, $caller,
4204: &escape($cloner), &escape($cc_clone), $cloneonly,
4205: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4206: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4207: } else {
4208: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4209: $sincefilter.':'.&escape($descfilter).':'.
4210: &escape($instcodefilter).':'.&escape($ownerfilter).
4211: ':'.&escape($coursefilter).':'.&escape($typefilter).
4212: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4213: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4214: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4215: &escape($cc_clone).':'.$cloneonly.':'.
4216: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4217: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4218: $tryserver);
4219: }
4220:
1.918 raeburn 4221: my @pairs=split(/\&/,$rep);
4222: foreach my $item (@pairs) {
4223: my ($key,$value)=split(/\=/,$item,2);
4224: $key = &unescape($key);
4225: next if ($key =~ /^error: 2 /);
4226: my $result = &thaw_unescape($value);
4227: if (ref($result) eq 'HASH') {
4228: $returnhash{$key}=$result;
4229: } else {
1.921 raeburn 4230: my @responses = split(/:/,$value);
4231: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4232: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4233: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4234: }
1.1008 raeburn 4235: }
1.353 www 4236: }
4237: }
4238: }
4239: }
4240: return %returnhash;
4241: }
4242:
1.1055 raeburn 4243: sub courselastaccess {
4244: my ($cdom,$cnum,$hostidref) = @_;
4245: my %returnhash;
4246: if ($cdom && $cnum) {
4247: my $chome = &homeserver($cnum,$cdom);
4248: if ($chome ne 'no_host') {
4249: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4250: &extract_lastaccess(\%returnhash,$rep);
4251: }
4252: } else {
4253: if (!$cdom) { $cdom=''; }
4254: my %libserv = &all_library();
4255: foreach my $tryserver (keys(%libserv)) {
4256: if (ref($hostidref) eq 'ARRAY') {
4257: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4258: }
4259: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4260: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4261: &extract_lastaccess(\%returnhash,$rep);
4262: }
4263: }
4264: }
4265: return %returnhash;
4266: }
4267:
4268: sub extract_lastaccess {
4269: my ($returnhash,$rep) = @_;
4270: if (ref($returnhash) eq 'HASH') {
4271: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4272: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4273: $rep eq '') {
4274: my @pairs=split(/\&/,$rep);
4275: foreach my $item (@pairs) {
4276: my ($key,$value)=split(/\=/,$item,2);
4277: $key = &unescape($key);
4278: next if ($key =~ /^error: 2 /);
4279: $returnhash->{$key} = &thaw_unescape($value);
4280: }
4281: }
4282: }
4283: return;
4284: }
4285:
1.658 raeburn 4286: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4287:
4288: sub dcmailput {
1.685 raeburn 4289: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4290: my $status = &Apache::lonnet::critical(
1.740 www 4291: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4292: &escape($message),$server);
1.662 raeburn 4293: return $status;
4294: }
4295:
1.658 raeburn 4296: sub dcmaildump {
4297: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4298: my %returnhash=();
1.846 albertel 4299:
4300: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4301: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4302: &escape($enddate).':';
4303: my @esc_senders=map { &escape($_)} @$senders;
4304: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4305: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4306: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4307: if (($key) && ($value)) {
4308: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4309: }
4310: }
4311: }
4312: return %returnhash;
4313: }
1.662 raeburn 4314: # ---------------------------------------------------------- Domain roles
4315:
4316: sub get_domain_roles {
4317: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4318: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4319: $startdate = '.';
4320: }
1.1018 raeburn 4321: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4322: $enddate = '.';
4323: }
1.922 raeburn 4324: my $rolelist;
4325: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4326: $rolelist = join('&',@{$roles});
1.922 raeburn 4327: }
1.662 raeburn 4328: my %personnel = ();
1.841 albertel 4329:
4330: my %servers = &get_servers($dom,'library');
4331: foreach my $tryserver (keys(%servers)) {
4332: %{$personnel{$tryserver}}=();
4333: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4334: &escape($startdate).':'.
4335: &escape($enddate).':'.
4336: &escape($rolelist), $tryserver))) {
4337: my ($key,$value) = split(/\=/,$line,2);
4338: if (($key) && ($value)) {
4339: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4340: }
4341: }
1.662 raeburn 4342: }
4343: return %personnel;
4344: }
1.658 raeburn 4345:
1.1057 www 4346: # ----------------------------------------------------------- Interval timing
1.149 www 4347:
1.1153 www 4348: {
4349: # Caches needed for speedup of navmaps
4350: # We don't want to cache this for very long at all (5 seconds at most)
4351: #
4352: # The user for whom we cache
4353: my $cachedkey='';
4354: # The cached times for this user
4355: my %cachedtimes=();
4356: # When this was last done
4357: my $cachedtime=();
4358:
4359: sub load_all_first_access {
1.1154 raeburn 4360: my ($uname,$udom)=@_;
1.1156 www 4361: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4362: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4363: return;
4364: }
4365: $cachedtime=time;
4366: $cachedkey=$uname.':'.$udom;
4367: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4368: }
4369:
1.504 albertel 4370: sub get_first_access {
1.1162 raeburn 4371: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4372: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4373: if ($argsymb) { $symb=$argsymb; }
4374: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4375: if ($argmap) { $map = $argmap; }
1.926 albertel 4376: if ($type eq 'course') {
4377: $res='course';
4378: } elsif ($type eq 'map') {
1.588 albertel 4379: $res=&symbread($map);
4380: } else {
4381: $res=$symb;
4382: }
1.1153 www 4383: &load_all_first_access($uname,$udom);
4384: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4385: }
4386:
4387: sub set_first_access {
1.1162 raeburn 4388: my ($type,$interval)=@_;
1.790 albertel 4389: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4390: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4391: if ($type eq 'course') {
4392: $res='course';
4393: } elsif ($type eq 'map') {
1.588 albertel 4394: $res=&symbread($map);
4395: } else {
4396: $res=$symb;
4397: }
1.1153 www 4398: $cachedkey='';
1.1162 raeburn 4399: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4400: if (!$firstaccess) {
1.1162 raeburn 4401: my $start = time;
4402: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4403: $udom,$uname);
4404: if ($putres eq 'ok') {
4405: &put('timerinterval',{"$courseid\0$res"=>$interval},
4406: $udom,$uname);
4407: &appenv(
4408: {
4409: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4410: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4411: }
4412: );
4413: }
4414: return $putres;
1.505 albertel 4415: }
4416: return 'already_set';
1.504 albertel 4417: }
1.1153 www 4418: }
1.110 www 4419: # --------------------------------------------- Set Expire Date for Spreadsheet
4420:
4421: sub expirespread {
4422: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4423: my $cid=$env{'request.course.id'};
1.110 www 4424: if ($cid) {
4425: my $now=time;
4426: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4427: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4428: $env{'course.'.$cid.'.num'}.
1.110 www 4429: ':nohist_expirationdates:'.
4430: &escape($key).'='.$now,
1.620 albertel 4431: $env{'course.'.$cid.'.home'})
1.110 www 4432: }
4433: return 'ok';
1.14 www 4434: }
4435:
1.109 www 4436: # ----------------------------------------------------- Devalidate Spreadsheets
4437:
4438: sub devalidate {
1.325 www 4439: my ($symb,$uname,$udom)=@_;
1.620 albertel 4440: my $cid=$env{'request.course.id'};
1.109 www 4441: if ($cid) {
1.391 matthew 4442: # delete the stored spreadsheets for
4443: # - the student level sheet of this user in course's homespace
4444: # - the assessment level sheet for this resource
4445: # for this user in user's homespace
1.553 albertel 4446: # - current conditional state info
1.325 www 4447: my $key=$uname.':'.$udom.':';
1.109 www 4448: my $status=
1.299 matthew 4449: &del('nohist_calculatedsheets',
1.391 matthew 4450: [$key.'studentcalc:'],
1.620 albertel 4451: $env{'course.'.$cid.'.domain'},
4452: $env{'course.'.$cid.'.num'})
1.133 albertel 4453: .' '.
4454: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4455: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4456: unless ($status eq 'ok ok') {
4457: &logthis('Could not devalidate spreadsheet '.
1.325 www 4458: $uname.' at '.$udom.' for '.
1.109 www 4459: $symb.': '.$status);
1.133 albertel 4460: }
1.553 albertel 4461: &delenv('user.state.'.$cid);
1.109 www 4462: }
4463: }
4464:
1.265 albertel 4465: sub get_scalar {
4466: my ($string,$end) = @_;
4467: my $value;
4468: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4469: $value = $1;
4470: } elsif ($$string =~ s/^([^&]*?)&//) {
4471: $value = $1;
4472: }
4473: return &unescape($value);
4474: }
4475:
4476: sub array2str {
4477: my (@array) = @_;
4478: my $result=&arrayref2str(\@array);
4479: $result=~s/^__ARRAY_REF__//;
4480: $result=~s/__END_ARRAY_REF__$//;
4481: return $result;
4482: }
4483:
1.204 albertel 4484: sub arrayref2str {
4485: my ($arrayref) = @_;
1.265 albertel 4486: my $result='__ARRAY_REF__';
1.204 albertel 4487: foreach my $elem (@$arrayref) {
1.265 albertel 4488: if(ref($elem) eq 'ARRAY') {
4489: $result.=&arrayref2str($elem).'&';
4490: } elsif(ref($elem) eq 'HASH') {
4491: $result.=&hashref2str($elem).'&';
4492: } elsif(ref($elem)) {
4493: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4494: } else {
4495: $result.=&escape($elem).'&';
4496: }
4497: }
4498: $result=~s/\&$//;
1.265 albertel 4499: $result .= '__END_ARRAY_REF__';
1.204 albertel 4500: return $result;
4501: }
4502:
1.168 albertel 4503: sub hash2str {
1.204 albertel 4504: my (%hash) = @_;
4505: my $result=&hashref2str(\%hash);
1.265 albertel 4506: $result=~s/^__HASH_REF__//;
4507: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4508: return $result;
4509: }
4510:
4511: sub hashref2str {
4512: my ($hashref)=@_;
1.265 albertel 4513: my $result='__HASH_REF__';
1.800 albertel 4514: foreach my $key (sort(keys(%$hashref))) {
4515: if (ref($key) eq 'ARRAY') {
4516: $result.=&arrayref2str($key).'=';
4517: } elsif (ref($key) eq 'HASH') {
4518: $result.=&hashref2str($key).'=';
4519: } elsif (ref($key)) {
1.265 albertel 4520: $result.='=';
1.800 albertel 4521: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4522: } else {
1.1132 raeburn 4523: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4524: }
4525:
1.800 albertel 4526: if(ref($hashref->{$key}) eq 'ARRAY') {
4527: $result.=&arrayref2str($hashref->{$key}).'&';
4528: } elsif(ref($hashref->{$key}) eq 'HASH') {
4529: $result.=&hashref2str($hashref->{$key}).'&';
4530: } elsif(ref($hashref->{$key})) {
1.265 albertel 4531: $result.='&';
1.800 albertel 4532: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4533: } else {
1.800 albertel 4534: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4535: }
4536: }
1.168 albertel 4537: $result=~s/\&$//;
1.265 albertel 4538: $result .= '__END_HASH_REF__';
1.168 albertel 4539: return $result;
4540: }
4541:
4542: sub str2hash {
1.265 albertel 4543: my ($string)=@_;
4544: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4545: return %$hash;
4546: }
4547:
4548: sub str2hashref {
1.168 albertel 4549: my ($string) = @_;
1.265 albertel 4550:
4551: my %hash;
4552:
4553: if($string !~ /^__HASH_REF__/) {
4554: if (! ($string eq '' || !defined($string))) {
4555: $hash{'error'}='Not hash reference';
4556: }
4557: return (\%hash, $string);
4558: }
4559:
4560: $string =~ s/^__HASH_REF__//;
4561:
4562: while($string !~ /^__END_HASH_REF__/) {
4563: #key
4564: my $key='';
4565: if($string =~ /^__HASH_REF__/) {
4566: ($key, $string)=&str2hashref($string);
4567: if(defined($key->{'error'})) {
4568: $hash{'error'}='Bad data';
4569: return (\%hash, $string);
4570: }
4571: } elsif($string =~ /^__ARRAY_REF__/) {
4572: ($key, $string)=&str2arrayref($string);
4573: if($key->[0] eq 'Array reference error') {
4574: $hash{'error'}='Bad data';
4575: return (\%hash, $string);
4576: }
4577: } else {
4578: $string =~ s/^(.*?)=//;
1.267 albertel 4579: $key=&unescape($1);
1.265 albertel 4580: }
4581: $string =~ s/^=//;
4582:
4583: #value
4584: my $value='';
4585: if($string =~ /^__HASH_REF__/) {
4586: ($value, $string)=&str2hashref($string);
4587: if(defined($value->{'error'})) {
4588: $hash{'error'}='Bad data';
4589: return (\%hash, $string);
4590: }
4591: } elsif($string =~ /^__ARRAY_REF__/) {
4592: ($value, $string)=&str2arrayref($string);
4593: if($value->[0] eq 'Array reference error') {
4594: $hash{'error'}='Bad data';
4595: return (\%hash, $string);
4596: }
4597: } else {
4598: $value=&get_scalar(\$string,'__END_HASH_REF__');
4599: }
4600: $string =~ s/^&//;
4601:
4602: $hash{$key}=$value;
1.204 albertel 4603: }
1.265 albertel 4604:
4605: $string =~ s/^__END_HASH_REF__//;
4606:
4607: return (\%hash, $string);
1.204 albertel 4608: }
4609:
4610: sub str2array {
1.265 albertel 4611: my ($string)=@_;
4612: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4613: return @$array;
4614: }
4615:
4616: sub str2arrayref {
1.204 albertel 4617: my ($string) = @_;
1.265 albertel 4618: my @array;
4619:
4620: if($string !~ /^__ARRAY_REF__/) {
4621: if (! ($string eq '' || !defined($string))) {
4622: $array[0]='Array reference error';
4623: }
4624: return (\@array, $string);
4625: }
4626:
4627: $string =~ s/^__ARRAY_REF__//;
4628:
4629: while($string !~ /^__END_ARRAY_REF__/) {
4630: my $value='';
4631: if($string =~ /^__HASH_REF__/) {
4632: ($value, $string)=&str2hashref($string);
4633: if(defined($value->{'error'})) {
4634: $array[0] ='Array reference error';
4635: return (\@array, $string);
4636: }
4637: } elsif($string =~ /^__ARRAY_REF__/) {
4638: ($value, $string)=&str2arrayref($string);
4639: if($value->[0] eq 'Array reference error') {
4640: $array[0] ='Array reference error';
4641: return (\@array, $string);
4642: }
4643: } else {
4644: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4645: }
4646: $string =~ s/^&//;
4647:
4648: push(@array, $value);
1.191 harris41 4649: }
1.265 albertel 4650:
4651: $string =~ s/^__END_ARRAY_REF__//;
4652:
4653: return (\@array, $string);
1.168 albertel 4654: }
4655:
1.167 albertel 4656: # -------------------------------------------------------------------Temp Store
4657:
1.168 albertel 4658: sub tmpreset {
4659: my ($symb,$namespace,$domain,$stuname) = @_;
4660: if (!$symb) {
4661: $symb=&symbread();
1.620 albertel 4662: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4663: }
4664: $symb=escape($symb);
4665:
1.620 albertel 4666: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4667: $namespace=~s/\//\_/g;
4668: $namespace=~s/\W//g;
4669:
1.620 albertel 4670: if (!$domain) { $domain=$env{'user.domain'}; }
4671: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4672: if ($domain eq 'public' && $stuname eq 'public') {
4673: $stuname=$ENV{'REMOTE_ADDR'};
4674: }
1.1117 foxr 4675: my $path=LONCAPA::tempdir();
1.168 albertel 4676: my %hash;
4677: if (tie(%hash,'GDBM_File',
4678: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4679: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4680: foreach my $key (keys(%hash)) {
1.180 albertel 4681: if ($key=~ /:$symb/) {
1.168 albertel 4682: delete($hash{$key});
4683: }
4684: }
4685: }
4686: }
4687:
1.167 albertel 4688: sub tmpstore {
1.168 albertel 4689: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4690:
4691: if (!$symb) {
4692: $symb=&symbread();
1.620 albertel 4693: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4694: }
4695: $symb=escape($symb);
4696:
4697: if (!$namespace) {
4698: # I don't think we would ever want to store this for a course.
4699: # it seems this will only be used if we don't have a course.
1.620 albertel 4700: #$namespace=$env{'request.course.id'};
1.168 albertel 4701: #if (!$namespace) {
1.620 albertel 4702: $namespace=$env{'request.state'};
1.168 albertel 4703: #}
4704: }
4705: $namespace=~s/\//\_/g;
4706: $namespace=~s/\W//g;
1.620 albertel 4707: if (!$domain) { $domain=$env{'user.domain'}; }
4708: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4709: if ($domain eq 'public' && $stuname eq 'public') {
4710: $stuname=$ENV{'REMOTE_ADDR'};
4711: }
1.168 albertel 4712: my $now=time;
4713: my %hash;
1.1117 foxr 4714: my $path=LONCAPA::tempdir();
1.168 albertel 4715: if (tie(%hash,'GDBM_File',
4716: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4717: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4718: $hash{"version:$symb"}++;
4719: my $version=$hash{"version:$symb"};
4720: my $allkeys='';
4721: foreach my $key (keys(%$storehash)) {
4722: $allkeys.=$key.':';
1.591 albertel 4723: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4724: }
4725: $hash{"$version:$symb:timestamp"}=$now;
4726: $allkeys.='timestamp';
4727: $hash{"$version:keys:$symb"}=$allkeys;
4728: if (untie(%hash)) {
4729: return 'ok';
4730: } else {
4731: return "error:$!";
4732: }
4733: } else {
4734: return "error:$!";
4735: }
4736: }
1.167 albertel 4737:
1.168 albertel 4738: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4739:
1.168 albertel 4740: sub tmprestore {
4741: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4742:
1.168 albertel 4743: if (!$symb) {
4744: $symb=&symbread();
1.620 albertel 4745: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4746: }
4747: $symb=escape($symb);
4748:
1.620 albertel 4749: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4750:
1.620 albertel 4751: if (!$domain) { $domain=$env{'user.domain'}; }
4752: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4753: if ($domain eq 'public' && $stuname eq 'public') {
4754: $stuname=$ENV{'REMOTE_ADDR'};
4755: }
1.168 albertel 4756: my %returnhash;
4757: $namespace=~s/\//\_/g;
4758: $namespace=~s/\W//g;
4759: my %hash;
1.1117 foxr 4760: my $path=LONCAPA::tempdir();
1.168 albertel 4761: if (tie(%hash,'GDBM_File',
4762: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4763: &GDBM_READER(),0640)) {
1.168 albertel 4764: my $version=$hash{"version:$symb"};
4765: $returnhash{'version'}=$version;
4766: my $scope;
4767: for ($scope=1;$scope<=$version;$scope++) {
4768: my $vkeys=$hash{"$scope:keys:$symb"};
4769: my @keys=split(/:/,$vkeys);
4770: my $key;
4771: $returnhash{"$scope:keys"}=$vkeys;
4772: foreach $key (@keys) {
1.591 albertel 4773: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4774: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4775: }
4776: }
1.168 albertel 4777: if (!(untie(%hash))) {
4778: return "error:$!";
4779: }
4780: } else {
4781: return "error:$!";
4782: }
4783: return %returnhash;
1.167 albertel 4784: }
4785:
1.9 www 4786: # ----------------------------------------------------------------------- Store
4787:
4788: sub store {
1.124 www 4789: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4790: my $home='';
4791:
1.168 albertel 4792: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4793:
1.213 www 4794: $symb=&symbclean($symb);
1.122 albertel 4795: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4796:
1.620 albertel 4797: if (!$domain) { $domain=$env{'user.domain'}; }
4798: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4799:
4800: &devalidate($symb,$stuname,$domain);
1.109 www 4801:
4802: $symb=escape($symb);
1.187 www 4803: if (!$namespace) {
1.620 albertel 4804: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4805: return '';
4806: }
4807: }
1.620 albertel 4808: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4809:
4810: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4811: $$storehash{'host'}=$perlvar{'lonHostID'};
4812:
1.12 www 4813: my $namevalue='';
1.800 albertel 4814: foreach my $key (keys(%$storehash)) {
4815: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4816: }
1.12 www 4817: $namevalue=~s/\&$//;
1.187 www 4818: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4819: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4820: }
4821:
1.47 www 4822: # -------------------------------------------------------------- Critical Store
4823:
4824: sub cstore {
1.124 www 4825: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4826: my $home='';
4827:
1.168 albertel 4828: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4829:
1.213 www 4830: $symb=&symbclean($symb);
1.122 albertel 4831: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4832:
1.620 albertel 4833: if (!$domain) { $domain=$env{'user.domain'}; }
4834: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4835:
4836: &devalidate($symb,$stuname,$domain);
1.109 www 4837:
4838: $symb=escape($symb);
1.187 www 4839: if (!$namespace) {
1.620 albertel 4840: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4841: return '';
4842: }
4843: }
1.620 albertel 4844: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4845:
4846: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4847: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4848:
1.47 www 4849: my $namevalue='';
1.800 albertel 4850: foreach my $key (keys(%$storehash)) {
4851: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4852: }
1.47 www 4853: $namevalue=~s/\&$//;
1.187 www 4854: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4855: return critical
4856: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4857: }
4858:
1.9 www 4859: # --------------------------------------------------------------------- Restore
4860:
4861: sub restore {
1.124 www 4862: my ($symb,$namespace,$domain,$stuname) = @_;
4863: my $home='';
4864:
1.168 albertel 4865: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4866:
1.122 albertel 4867: if (!$symb) {
1.1224 raeburn 4868: return if ($namespace eq 'courserequests');
4869: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4870: } else {
1.1224 raeburn 4871: unless ($namespace eq 'courserequests') {
4872: $symb=&escape(&symbclean($symb));
4873: }
1.122 albertel 4874: }
1.188 www 4875: if (!$namespace) {
1.620 albertel 4876: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4877: return '';
4878: }
4879: }
1.620 albertel 4880: if (!$domain) { $domain=$env{'user.domain'}; }
4881: if (!$stuname) { $stuname=$env{'user.name'}; }
4882: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4883: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4884:
1.12 www 4885: my %returnhash=();
1.800 albertel 4886: foreach my $line (split(/\&/,$answer)) {
4887: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4888: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4889: }
1.75 www 4890: my $version;
4891: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4892: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4893: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4894: }
1.75 www 4895: }
1.13 www 4896: return %returnhash;
1.34 www 4897: }
4898:
4899: # ---------------------------------------------------------- Course Description
1.1118 foxr 4900: #
4901: #
1.34 www 4902:
4903: sub coursedescription {
1.731 albertel 4904: my ($courseid,$args)=@_;
1.34 www 4905: $courseid=~s/^\///;
1.49 www 4906: $courseid=~s/\_/\//g;
1.34 www 4907: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4908: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4909: my $normalid=$cdomain.'_'.$cnum;
4910: # need to always cache even if we get errors otherwise we keep
4911: # trying and trying and trying to get the course description.
4912: my %envhash=();
4913: my %returnhash=();
1.731 albertel 4914:
4915: my $expiretime=600;
4916: if ($env{'request.course.id'} eq $normalid) {
4917: $expiretime=120;
4918: }
4919:
4920: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4921: if (!$args->{'freshen_cache'}
4922: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4923: foreach my $key (keys(%env)) {
4924: next if ($key !~ /^\Q$prefix\E(.*)/);
4925: my ($setting) = $1;
4926: $returnhash{$setting} = $env{$key};
4927: }
4928: return %returnhash;
4929: }
4930:
1.1118 foxr 4931: # get the data again
4932:
1.731 albertel 4933: if (!$args->{'one_time'}) {
4934: $envhash{'course.'.$normalid.'.last_cache'}=time;
4935: }
1.811 albertel 4936:
1.34 www 4937: if ($chome ne 'no_host') {
1.302 albertel 4938: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4939: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4940: my $username = $env{'user.name'}; # Defult username
4941: if(defined $args->{'user'}) {
4942: $username = $args->{'user'};
4943: }
1.129 albertel 4944: $returnhash{'home'}= $chome;
4945: $returnhash{'domain'} = $cdomain;
4946: $returnhash{'num'} = $cnum;
1.741 raeburn 4947: if (!defined($returnhash{'type'})) {
4948: $returnhash{'type'} = 'Course';
4949: }
1.130 albertel 4950: while (my ($name,$value) = each %returnhash) {
1.53 www 4951: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4952: }
1.270 www 4953: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4954: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4955: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4956: $envhash{'course.'.$normalid.'.home'}=$chome;
4957: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4958: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4959: }
4960: }
1.731 albertel 4961: if (!$args->{'one_time'}) {
1.949 raeburn 4962: &appenv(\%envhash);
1.731 albertel 4963: }
1.302 albertel 4964: return %returnhash;
1.461 www 4965: }
4966:
1.1080 raeburn 4967: sub update_released_required {
4968: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4969: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4970: $cid = $env{'request.course.id'};
4971: $cdom = $env{'course.'.$cid.'.domain'};
4972: $cnum = $env{'course.'.$cid.'.num'};
4973: $chome = $env{'course.'.$cid.'.home'};
4974: }
4975: if ($needsrelease) {
4976: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4977: my $needsupdate;
4978: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4979: $needsupdate = 1;
4980: } else {
4981: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4982: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4983: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4984: $needsupdate = 1;
4985: }
4986: }
4987: if ($needsupdate) {
4988: my %needshash = (
4989: 'internal.releaserequired' => $needsrelease,
4990: );
4991: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4992: if ($putresult eq 'ok') {
4993: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4994: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4995: if (ref($crsinfo{$cid}) eq 'HASH') {
4996: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4997: &courseidput($cdom,\%crsinfo,$chome,'notime');
4998: }
4999: }
5000: }
5001: }
5002: return;
5003: }
5004:
1.461 www 5005: # -------------------------------------------------See if a user is privileged
5006:
5007: sub privileged {
1.1219 raeburn 5008: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5009: my $now = time;
1.1219 raeburn 5010: my $roles;
5011: if (ref($possroles) eq 'ARRAY') {
5012: $roles = $possroles;
5013: } else {
5014: $roles = ['dc','su'];
5015: }
5016: if (ref($possdomains) eq 'ARRAY') {
5017: my %privileged = &privileged_by_domain($possdomains,$roles);
5018: foreach my $dom (@{$possdomains}) {
5019: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5020: (ref($privileged{$dom}) eq 'HASH')) {
5021: foreach my $role (@{$roles}) {
5022: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5023: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5024: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5025: return 1 unless (($end && $end < $now) ||
5026: ($start && $start > $now));
5027: }
5028: }
5029: }
5030: }
5031: }
5032: } else {
5033: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5034: my $now = time;
1.1170 droeschl 5035:
1.1219 raeburn 5036: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5037: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5038: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5039: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5040: or ($tstart && $tstart > $now);
1.1170 droeschl 5041: }
1.1219 raeburn 5042: }
5043: }
5044: return 0;
5045: }
1.1170 droeschl 5046:
1.1219 raeburn 5047: sub privileged_by_domain {
5048: my ($domains,$roles) = @_;
5049: my %privileged = ();
5050: my $cachetime = 60*60*24;
5051: my $now = time;
5052: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5053: return %privileged;
5054: }
5055: foreach my $dom (@{$domains}) {
5056: next if (ref($privileged{$dom}) eq 'HASH');
5057: my $needroles;
5058: foreach my $role (@{$roles}) {
5059: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5060: if (defined($cached)) {
5061: if (ref($result) eq 'HASH') {
5062: $privileged{$dom}{$role} = $result;
5063: }
5064: } else {
5065: $needroles = 1;
5066: }
5067: }
5068: if ($needroles) {
5069: my %dompersonnel = &get_domain_roles($dom,$roles);
5070: $privileged{$dom} = {};
5071: foreach my $server (keys(%dompersonnel)) {
5072: if (ref($dompersonnel{$server}) eq 'HASH') {
5073: foreach my $item (keys(%{$dompersonnel{$server}})) {
5074: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5075: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5076: next if ($end && $end < $now);
5077: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5078: $dompersonnel{$server}{$item};
5079: }
5080: }
5081: }
5082: if (ref($privileged{$dom}) eq 'HASH') {
5083: foreach my $role (@{$roles}) {
5084: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5085: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5086: } else {
5087: my %hash = ();
5088: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5089: }
5090: }
5091: }
5092: }
5093: }
5094: return %privileged;
1.9 www 5095: }
1.1 albertel 5096:
1.103 harris41 5097: # -------------------------------------------------------- Get user privileges
1.11 www 5098:
5099: sub rolesinit {
1.1169 droeschl 5100: my ($domain, $username) = @_;
5101: my %userroles = ('user.login.time' => time);
5102: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5103:
5104: # firstaccess and timerinterval are related to timed maps/resources.
5105: # also, blocking can be triggered by an activating timer
5106: # it's saved in the user's %env.
5107: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5108: my %timerinterval = &dump('timerinterval', $domain, $username);
5109: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5110: %timerintchk, %timerintenv);
5111:
1.1162 raeburn 5112: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5113: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5114: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5115: }
1.1169 droeschl 5116:
1.1162 raeburn 5117: foreach my $key (keys(%timerinterval)) {
5118: my ($cid,$rest) = split(/\0/,$key);
5119: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5120: }
1.1169 droeschl 5121:
1.11 www 5122: my %allroles=();
1.1162 raeburn 5123: my %allgroups=();
1.11 www 5124:
1.1169 droeschl 5125: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5126: my $role = $rolesdump{$area};
5127: $area =~ s/\_\w\w$//;
5128:
5129: my ($trole, $tend, $tstart, $group_privs);
5130:
5131: if ($role =~ /^cr/) {
5132: # Custom role, defined by a user
5133: # e.g., user.role.cr/msu/smith/mynewrole
5134: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5135: $trole = $1;
5136: ($tend, $tstart) = split('_', $2);
5137: } else {
5138: $trole = $role;
5139: }
5140: } elsif ($role =~ m|^gr/|) {
5141: # Role of member in a group, defined within a course/community
5142: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5143: ($trole, $tend, $tstart) = split(/_/, $role);
5144: next if $tstart eq '-1';
5145: ($trole, $group_privs) = split(/\//, $trole);
5146: $group_privs = &unescape($group_privs);
5147: } else {
5148: # Just a normal role, defined in roles.tab
5149: ($trole, $tend, $tstart) = split(/_/,$role);
5150: }
5151:
5152: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5153: $username);
5154: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5155:
5156: # role expired or not available yet?
5157: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5158: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5159:
5160: next if $area eq '' or $trole eq '';
5161:
5162: my $spec = "$trole.$area";
5163: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5164:
5165: if ($trole =~ /^cr\//) {
5166: # Custom role, defined by a user
5167: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5168: } elsif ($trole eq 'gr') {
5169: # Role of a member in a group, defined within a course/community
5170: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5171: next;
5172: } else {
5173: # Normal role, defined in roles.tab
5174: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5175: }
5176:
5177: my $cid = $tdomain.'_'.$trest;
5178: unless ($firstaccchk{$cid}) {
5179: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5180: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5181: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5182: $coursetimerstarts{$cid}{$item};
5183: }
5184: }
5185: $firstaccchk{$cid} = 1;
5186: }
5187: unless ($timerintchk{$cid}) {
5188: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5189: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5190: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5191: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5192: }
1.12 www 5193: }
1.1169 droeschl 5194: $timerintchk{$cid} = 1;
1.191 harris41 5195: }
1.11 www 5196: }
1.1169 droeschl 5197:
5198: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5199: \%allroles, \%allgroups);
5200: $env{'user.adv'} = $userroles{'user.adv'};
5201:
1.1162 raeburn 5202: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5203: }
5204:
1.567 raeburn 5205: sub set_arearole {
1.1215 raeburn 5206: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5207: unless ($nolog) {
1.567 raeburn 5208: # log the associated role with the area
1.1215 raeburn 5209: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5210: }
1.743 albertel 5211: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5212: }
5213:
5214: sub custom_roleprivs {
5215: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5216: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5217: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5218: if (&hostname($homsvr) ne '') {
1.567 raeburn 5219: my ($rdummy,$roledef)=
5220: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5221: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5222: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5223: if (defined($syspriv)) {
1.1043 raeburn 5224: if ($trest =~ /^$match_community$/) {
5225: $syspriv =~ s/bre\&S//;
5226: }
1.567 raeburn 5227: $$allroles{'cm./'}.=':'.$syspriv;
5228: $$allroles{$spec.'./'}.=':'.$syspriv;
5229: }
5230: if ($tdomain ne '') {
5231: if (defined($dompriv)) {
5232: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5233: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5234: }
5235: if (($trest ne '') && (defined($coursepriv))) {
5236: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5237: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5238: }
5239: }
5240: }
5241: }
5242: }
5243:
1.678 raeburn 5244: sub group_roleprivs {
5245: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5246: my $access = 1;
5247: my $now = time;
5248: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5249: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5250: if ($access) {
1.811 albertel 5251: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5252: $$allgroups{$course}{$group} .=':'.$group_privs;
5253: }
5254: }
1.567 raeburn 5255:
5256: sub standard_roleprivs {
5257: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5258: if (defined($pr{$trole.':s'})) {
5259: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5260: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5261: }
5262: if ($tdomain ne '') {
5263: if (defined($pr{$trole.':d'})) {
5264: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5265: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5266: }
5267: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5268: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5269: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5270: }
5271: }
5272: }
5273:
5274: sub set_userprivs {
1.1064 raeburn 5275: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5276: my $author=0;
5277: my $adv=0;
1.678 raeburn 5278: my %grouproles = ();
5279: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5280: my @groupkeys;
1.1000 raeburn 5281: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5282: push(@groupkeys,$role);
5283: }
5284: if (ref($groups_roles) eq 'HASH') {
5285: foreach my $key (keys(%{$groups_roles})) {
5286: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5287: push(@groupkeys,$key);
5288: }
5289: }
5290: }
5291: if (@groupkeys > 0) {
5292: foreach my $role (@groupkeys) {
5293: my ($trole,$area,$sec,$extendedarea);
5294: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5295: $trole = $1;
5296: $area = $2;
5297: $sec = $3;
5298: $extendedarea = $area.$sec;
5299: if (exists($$allgroups{$area})) {
5300: foreach my $group (keys(%{$$allgroups{$area}})) {
5301: my $spec = $trole.'.'.$extendedarea;
5302: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5303: $$allgroups{$area}{$group};
1.1064 raeburn 5304: }
1.678 raeburn 5305: }
5306: }
5307: }
5308: }
5309: }
1.800 albertel 5310: foreach my $group (keys(%grouproles)) {
5311: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5312: }
1.800 albertel 5313: foreach my $role (keys(%{$allroles})) {
5314: my %thesepriv;
1.941 raeburn 5315: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5316: foreach my $item (split(/:/,$$allroles{$role})) {
5317: if ($item ne '') {
5318: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5319: if ($restrictions eq '') {
5320: $thesepriv{$privilege}='F';
5321: } elsif ($thesepriv{$privilege} ne 'F') {
5322: $thesepriv{$privilege}.=$restrictions;
5323: }
5324: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5325: }
5326: }
5327: my $thesestr='';
1.1104 raeburn 5328: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5329: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5330: }
5331: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5332: }
5333: return ($author,$adv);
5334: }
5335:
1.994 raeburn 5336: sub role_status {
1.1104 raeburn 5337: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5338: my @pwhere = ();
5339: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5340: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5341: unless (!defined($$role) || $$role eq '') {
5342: $$where=join('.',@pwhere);
5343: $$trolecode=$$role.'.'.$$where;
5344: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5345: $$tstatus='is';
1.1104 raeburn 5346: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5347: $$tstatus='future';
1.1034 raeburn 5348: if ($$tstart<$now) {
5349: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5350: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5351: my (%allroles,%allgroups,$group_privs,
5352: %groups_roles,@rolecodes);
1.1002 raeburn 5353: my %userroles = (
5354: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5355: );
1.1064 raeburn 5356: @rolecodes = ('cm');
1.1002 raeburn 5357: my $spec=$$role.'.'.$$where;
5358: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5359: if ($$role =~ /^cr\//) {
5360: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5361: push(@rolecodes,'cr');
1.1002 raeburn 5362: } elsif ($$role eq 'gr') {
1.1064 raeburn 5363: push(@rolecodes,$$role);
1.1002 raeburn 5364: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5365: $env{'user.name'});
1.1064 raeburn 5366: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5367: (undef,my $group_privs) = split(/\//,$trole);
5368: $group_privs = &unescape($group_privs);
5369: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5370: 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 5371: &get_groups_roles($tdomain,$trest,
5372: \%course_roles,\@rolecodes,
5373: \%groups_roles);
1.1002 raeburn 5374: } else {
1.1064 raeburn 5375: push(@rolecodes,$$role);
1.1002 raeburn 5376: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5377: }
1.1064 raeburn 5378: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5379: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5380: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5381: }
5382: }
1.1034 raeburn 5383: $$tstatus = 'is';
1.1002 raeburn 5384: }
1.994 raeburn 5385: }
5386: if ($$tend) {
1.1104 raeburn 5387: if ($$tend<$update) {
1.994 raeburn 5388: $$tstatus='expired';
5389: } elsif ($$tend<$now) {
5390: $$tstatus='will_not';
5391: }
5392: }
5393: }
5394: }
5395: }
5396:
1.1104 raeburn 5397: sub get_groups_roles {
5398: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5399: return unless((ref($cdom_courseroles) eq 'HASH') &&
5400: (ref($rolecodes) eq 'ARRAY') &&
5401: (ref($groups_roles) eq 'HASH'));
5402: if (keys(%{$cdom_courseroles}) > 0) {
5403: my ($cnum) = ($rest =~ /^($match_courseid)/);
5404: if ($cdom ne '' && $cnum ne '') {
5405: foreach my $key (keys(%{$cdom_courseroles})) {
5406: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5407: my $crsrole = $1;
5408: my $crssec = $2;
5409: if ($crsrole =~ /^cr/) {
5410: unless (grep(/^cr$/,@{$rolecodes})) {
5411: push(@{$rolecodes},'cr');
5412: }
5413: } else {
5414: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5415: push(@{$rolecodes},$crsrole);
5416: }
5417: }
5418: my $rolekey = "$crsrole./$cdom/$cnum";
5419: if ($crssec ne '') {
5420: $rolekey .= "/$crssec";
5421: }
5422: $rolekey .= './';
5423: $groups_roles->{$rolekey} = $rolecodes;
5424: }
5425: }
5426: }
5427: }
5428: return;
5429: }
5430:
5431: sub delete_env_groupprivs {
5432: my ($where,$courseroles,$possroles) = @_;
5433: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5434: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5435: unless (ref($courseroles->{$udom}) eq 'HASH') {
5436: %{$courseroles->{$udom}} =
5437: &get_my_roles('','','userroles',['active'],
5438: $possroles,[$udom],1);
5439: }
5440: if (ref($courseroles->{$udom}) eq 'HASH') {
5441: foreach my $item (keys(%{$courseroles->{$udom}})) {
5442: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5443: my $area = '/'.$cdom.'/'.$cnum;
5444: my $privkey = "user.priv.$crsrole.$area";
5445: if ($crssec ne '') {
5446: $privkey .= '/'.$crssec;
5447: }
5448: $privkey .= ".$area/$group";
5449: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5450: }
5451: }
5452: return;
5453: }
5454:
1.994 raeburn 5455: sub check_adhoc_privs {
1.1104 raeburn 5456: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5457: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5458: my $setprivs;
1.994 raeburn 5459: if ($env{$cckey}) {
5460: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5461: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5462: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5463: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5464: $setprivs = 1;
1.994 raeburn 5465: }
5466: } else {
1.1088 raeburn 5467: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5468: $setprivs = 1;
1.994 raeburn 5469: }
1.1185 raeburn 5470: return $setprivs;
1.994 raeburn 5471: }
5472:
5473: sub set_adhoc_privileges {
5474: # role can be cc or ca
1.1088 raeburn 5475: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5476: my $area = '/'.$dcdom.'/'.$pickedcourse;
5477: my $spec = $role.'.'.$area;
5478: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5479: $env{'user.name'},1);
1.994 raeburn 5480: my %ccrole = ();
5481: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5482: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5483: &appenv(\%userroles,[$role,'cm']);
5484: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5485: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5486: &appenv( {'request.role' => $spec,
5487: 'request.role.domain' => $dcdom,
5488: 'request.course.sec' => ''
5489: }
5490: );
5491: my $tadv=0;
5492: if (&allowed('adv') eq 'F') { $tadv=1; }
5493: &appenv({'request.role.adv' => $tadv});
5494: }
1.994 raeburn 5495: }
5496:
1.12 www 5497: # --------------------------------------------------------------- get interface
5498:
5499: sub get {
1.131 albertel 5500: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5501: my $items='';
1.800 albertel 5502: foreach my $item (@$storearr) {
5503: $items.=&escape($item).'&';
1.191 harris41 5504: }
1.12 www 5505: $items=~s/\&$//;
1.620 albertel 5506: if (!$udomain) { $udomain=$env{'user.domain'}; }
5507: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5508: my $uhome=&homeserver($uname,$udomain);
5509:
1.133 albertel 5510: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5511: my @pairs=split(/\&/,$rep);
1.273 albertel 5512: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5513: return @pairs;
5514: }
1.15 www 5515: my %returnhash=();
1.42 www 5516: my $i=0;
1.800 albertel 5517: foreach my $item (@$storearr) {
5518: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5519: $i++;
1.191 harris41 5520: }
1.15 www 5521: return %returnhash;
1.27 www 5522: }
5523:
5524: # --------------------------------------------------------------- del interface
5525:
5526: sub del {
1.133 albertel 5527: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5528: my $items='';
1.800 albertel 5529: foreach my $item (@$storearr) {
5530: $items.=&escape($item).'&';
1.191 harris41 5531: }
1.984 neumanie 5532:
1.27 www 5533: $items=~s/\&$//;
1.620 albertel 5534: if (!$udomain) { $udomain=$env{'user.domain'}; }
5535: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5536: my $uhome=&homeserver($uname,$udomain);
5537: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5538: }
5539:
5540: # -------------------------------------------------------------- dump interface
5541:
1.1180 droeschl 5542: sub unserialize {
5543: my ($rep, $escapedkeys) = @_;
5544:
5545: return {} if $rep =~ /^error/;
5546:
5547: my %returnhash=();
5548: foreach my $item (split /\&/, $rep) {
5549: my ($key, $value) = split(/=/, $item, 2);
5550: $key = unescape($key) unless $escapedkeys;
5551: next if $key =~ /^error: 2 /;
5552: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5553: }
5554: #return %returnhash;
5555: return \%returnhash;
5556: }
5557:
5558: # see Lond::dump_with_regexp
5559: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5560: sub dump {
1.1180 droeschl 5561: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5562: if (!$udomain) { $udomain=$env{'user.domain'}; }
5563: if (!$uname) { $uname=$env{'user.name'}; }
5564: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5565:
1.1180 droeschl 5566: my $reply;
5567: if (grep { $_ eq $uhome } current_machine_ids()) {
5568: # user is hosted on this machine
5569: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5570: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5571: return %{unserialize($reply, $escapedkeys)};
5572: }
1.755 albertel 5573: if ($regexp) {
5574: $regexp=&escape($regexp);
5575: } else {
5576: $regexp='.';
5577: }
1.1166 raeburn 5578: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5579: my @pairs=split(/\&/,$rep);
5580: my %returnhash=();
1.1098 foxr 5581: if (!($rep =~ /^error/ )) {
5582: foreach my $item (@pairs) {
5583: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5584: $key = unescape($key) unless $escapedkeys;
5585: #$key = &unescape($key);
1.1098 foxr 5586: next if ($key =~ /^error: 2 /);
5587: $returnhash{$key}=&thaw_unescape($value);
5588: }
1.755 albertel 5589: }
5590: return %returnhash;
1.407 www 5591: }
5592:
1.1098 foxr 5593:
1.717 albertel 5594: # --------------------------------------------------------- dumpstore interface
5595:
5596: sub dumpstore {
5597: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5598: # same as dump but keys must be escaped. They may contain colon separated
5599: # lists of values that may themself contain colons (e.g. symbs).
5600: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5601: }
5602:
1.407 www 5603: # -------------------------------------------------------------- keys interface
5604:
5605: sub getkeys {
5606: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5607: if (!$udomain) { $udomain=$env{'user.domain'}; }
5608: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5609: my $uhome=&homeserver($uname,$udomain);
5610: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5611: my @keyarray=();
1.800 albertel 5612: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5613: next if ($key =~ /^error: 2 /);
1.800 albertel 5614: push(@keyarray,&unescape($key));
1.407 www 5615: }
5616: return @keyarray;
1.318 matthew 5617: }
5618:
1.319 matthew 5619: # --------------------------------------------------------------- currentdump
5620: sub currentdump {
1.328 matthew 5621: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5622: $courseid = $env{'request.course.id'} if (! defined($courseid));
5623: $sdom = $env{'user.domain'} if (! defined($sdom));
5624: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5625: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5626: my $rep;
5627:
5628: if (grep { $_ eq $uhome } current_machine_ids()) {
5629: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5630: $courseid)));
5631: } else {
5632: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5633: }
5634:
1.318 matthew 5635: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5636: #
1.318 matthew 5637: my %returnhash=();
1.319 matthew 5638: #
5639: if ($rep eq "unknown_cmd") {
5640: # an old lond will not know currentdump
5641: # Do a dump and make it look like a currentdump
1.822 albertel 5642: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5643: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5644: my %hash = @tmp;
5645: @tmp=();
1.424 matthew 5646: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5647: } else {
5648: my @pairs=split(/\&/,$rep);
1.800 albertel 5649: foreach my $pair (@pairs) {
5650: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5651: my ($symb,$param) = split(/:/,$key);
5652: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5653: &thaw_unescape($value);
1.319 matthew 5654: }
1.191 harris41 5655: }
1.12 www 5656: return %returnhash;
1.424 matthew 5657: }
5658:
5659: sub convert_dump_to_currentdump{
5660: my %hash = %{shift()};
5661: my %returnhash;
5662: # Code ripped from lond, essentially. The only difference
5663: # here is the unescaping done by lonnet::dump(). Conceivably
5664: # we might run in to problems with parameter names =~ /^v\./
5665: while (my ($key,$value) = each(%hash)) {
5666: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5667: $symb = &unescape($symb);
5668: $param = &unescape($param);
1.424 matthew 5669: next if ($v eq 'version' || $symb eq 'keys');
5670: next if (exists($returnhash{$symb}) &&
5671: exists($returnhash{$symb}->{$param}) &&
5672: $returnhash{$symb}->{'v.'.$param} > $v);
5673: $returnhash{$symb}->{$param}=$value;
5674: $returnhash{$symb}->{'v.'.$param}=$v;
5675: }
5676: #
5677: # Remove all of the keys in the hashes which keep track of
5678: # the version of the parameter.
5679: while (my ($symb,$param_hash) = each(%returnhash)) {
5680: # use a foreach because we are going to delete from the hash.
5681: foreach my $key (keys(%$param_hash)) {
5682: delete($param_hash->{$key}) if ($key =~ /^v\./);
5683: }
5684: }
5685: return \%returnhash;
1.12 www 5686: }
5687:
1.627 albertel 5688: # ------------------------------------------------------ critical inc interface
5689:
5690: sub cinc {
5691: return &inc(@_,'critical');
5692: }
5693:
1.449 matthew 5694: # --------------------------------------------------------------- inc interface
5695:
5696: sub inc {
1.627 albertel 5697: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5698: if (!$udomain) { $udomain=$env{'user.domain'}; }
5699: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5700: my $uhome=&homeserver($uname,$udomain);
5701: my $items='';
5702: if (! ref($store)) {
5703: # got a single value, so use that instead
5704: $items = &escape($store).'=&';
5705: } elsif (ref($store) eq 'SCALAR') {
5706: $items = &escape($$store).'=&';
5707: } elsif (ref($store) eq 'ARRAY') {
5708: $items = join('=&',map {&escape($_);} @{$store});
5709: } elsif (ref($store) eq 'HASH') {
5710: while (my($key,$value) = each(%{$store})) {
5711: $items.= &escape($key).'='.&escape($value).'&';
5712: }
5713: }
5714: $items=~s/\&$//;
1.627 albertel 5715: if ($critical) {
5716: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5717: } else {
5718: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5719: }
1.449 matthew 5720: }
5721:
1.12 www 5722: # --------------------------------------------------------------- put interface
5723:
5724: sub put {
1.134 albertel 5725: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5726: if (!$udomain) { $udomain=$env{'user.domain'}; }
5727: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5728: my $uhome=&homeserver($uname,$udomain);
1.12 www 5729: my $items='';
1.800 albertel 5730: foreach my $item (keys(%$storehash)) {
5731: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5732: }
1.12 www 5733: $items=~s/\&$//;
1.134 albertel 5734: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5735: }
5736:
1.631 albertel 5737: # ------------------------------------------------------------ newput interface
5738:
5739: sub newput {
5740: my ($namespace,$storehash,$udomain,$uname)=@_;
5741: if (!$udomain) { $udomain=$env{'user.domain'}; }
5742: if (!$uname) { $uname=$env{'user.name'}; }
5743: my $uhome=&homeserver($uname,$udomain);
5744: my $items='';
5745: foreach my $key (keys(%$storehash)) {
5746: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5747: }
5748: $items=~s/\&$//;
5749: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5750: }
5751:
5752: # --------------------------------------------------------- putstore interface
5753:
1.524 raeburn 5754: sub putstore {
1.715 albertel 5755: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5756: if (!$udomain) { $udomain=$env{'user.domain'}; }
5757: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5758: my $uhome=&homeserver($uname,$udomain);
5759: my $items='';
1.715 albertel 5760: foreach my $key (keys(%$storehash)) {
5761: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5762: }
1.715 albertel 5763: $items=~s/\&$//;
1.716 albertel 5764: my $esc_symb=&escape($symb);
5765: my $esc_v=&escape($version);
1.715 albertel 5766: my $reply =
1.716 albertel 5767: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5768: $uhome);
5769: if ($reply eq 'unknown_cmd') {
1.716 albertel 5770: # gfall back to way things use to be done
1.715 albertel 5771: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5772: $uname);
1.524 raeburn 5773: }
1.715 albertel 5774: return $reply;
5775: }
5776:
5777: sub old_putstore {
1.716 albertel 5778: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5779: if (!$udomain) { $udomain=$env{'user.domain'}; }
5780: if (!$uname) { $uname=$env{'user.name'}; }
5781: my $uhome=&homeserver($uname,$udomain);
5782: my %newstorehash;
1.800 albertel 5783: foreach my $item (keys(%$storehash)) {
5784: my $key = $version.':'.&escape($symb).':'.$item;
5785: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5786: }
5787: my $items='';
5788: my %allitems = ();
1.800 albertel 5789: foreach my $item (keys(%newstorehash)) {
5790: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5791: my $key = $1.':keys:'.$2;
5792: $allitems{$key} .= $3.':';
5793: }
1.800 albertel 5794: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5795: }
1.800 albertel 5796: foreach my $item (keys(%allitems)) {
5797: $allitems{$item} =~ s/\:$//;
5798: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5799: }
5800: $items=~s/\&$//;
5801: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5802: }
5803:
1.47 www 5804: # ------------------------------------------------------ critical put interface
5805:
5806: sub cput {
1.134 albertel 5807: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5808: if (!$udomain) { $udomain=$env{'user.domain'}; }
5809: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5810: my $uhome=&homeserver($uname,$udomain);
1.47 www 5811: my $items='';
1.800 albertel 5812: foreach my $item (keys(%$storehash)) {
5813: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5814: }
1.47 www 5815: $items=~s/\&$//;
1.134 albertel 5816: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5817: }
5818:
5819: # -------------------------------------------------------------- eget interface
5820:
5821: sub eget {
1.133 albertel 5822: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5823: my $items='';
1.800 albertel 5824: foreach my $item (@$storearr) {
5825: $items.=&escape($item).'&';
1.191 harris41 5826: }
1.12 www 5827: $items=~s/\&$//;
1.620 albertel 5828: if (!$udomain) { $udomain=$env{'user.domain'}; }
5829: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5830: my $uhome=&homeserver($uname,$udomain);
5831: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5832: my @pairs=split(/\&/,$rep);
5833: my %returnhash=();
1.42 www 5834: my $i=0;
1.800 albertel 5835: foreach my $item (@$storearr) {
5836: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5837: $i++;
1.191 harris41 5838: }
1.12 www 5839: return %returnhash;
5840: }
5841:
1.667 albertel 5842: # ------------------------------------------------------------ tmpput interface
5843: sub tmpput {
1.802 raeburn 5844: my ($storehash,$server,$context)=@_;
1.667 albertel 5845: my $items='';
1.800 albertel 5846: foreach my $item (keys(%$storehash)) {
5847: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5848: }
5849: $items=~s/\&$//;
1.802 raeburn 5850: if (defined($context)) {
5851: $items .= ':'.&escape($context);
5852: }
1.667 albertel 5853: return &reply("tmpput:$items",$server);
5854: }
5855:
5856: # ------------------------------------------------------------ tmpget interface
5857: sub tmpget {
1.688 albertel 5858: my ($token,$server)=@_;
5859: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5860: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5861: my %returnhash;
5862: foreach my $item (split(/\&/,$rep)) {
5863: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5864: next if ($key =~ /^error: 2 /);
1.667 albertel 5865: $returnhash{&unescape($key)}=&thaw_unescape($value);
5866: }
5867: return %returnhash;
5868: }
5869:
1.1113 raeburn 5870: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5871: sub tmpdel {
5872: my ($token,$server)=@_;
5873: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5874: return &reply("tmpdel:$token",$server);
5875: }
5876:
1.1198 raeburn 5877: # ------------------------------------------------------------ get_timebased_id
5878:
5879: sub get_timebased_id {
5880: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5881: $maxtries) = @_;
5882: my ($newid,$error,$dellock);
5883: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5884: return ('','ok','invalid call to get suffix');
5885: }
5886:
5887: # set defaults for any optional args for which values were not supplied
5888: if ($who eq '') {
5889: $who = $env{'user.name'}.':'.$env{'user.domain'};
5890: }
5891: if (!$locktries) {
5892: $locktries = 3;
5893: }
5894: if (!$maxtries) {
5895: $maxtries = 10;
5896: }
5897:
5898: if (($cdom eq '') || ($cnum eq '')) {
5899: if ($env{'request.course.id'}) {
5900: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5901: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5902: }
5903: if (($cdom eq '') || ($cnum eq '')) {
5904: return ('','ok','call to get suffix not in course context');
5905: }
5906: }
5907:
5908: # construct locking item
5909: my $lockhash = {
5910: $prefix."\0".'locked_'.$keyid => $who,
5911: };
5912: my $tries = 0;
5913:
5914: # attempt to get lock on nohist_$namespace file
5915: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5916: while (($gotlock ne 'ok') && $tries <$locktries) {
5917: $tries ++;
5918: sleep 1;
5919: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5920: }
5921:
5922: # attempt to get unique identifier, based on current timestamp
5923: if ($gotlock eq 'ok') {
5924: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5925: my $id = time;
5926: $newid = $id;
5927: my $idtries = 0;
5928: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5929: if ($idtype eq 'concat') {
5930: $newid = $id.$idtries;
5931: } else {
5932: $newid ++;
5933: }
5934: $idtries ++;
5935: }
5936: if (!exists($inuse{$prefix."\0".$newid})) {
5937: my %new_item = (
5938: $prefix."\0".$newid => $who,
5939: );
5940: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5941: $cdom,$cnum);
5942: if ($putresult ne 'ok') {
5943: undef($newid);
5944: $error = 'error saving new item: '.$putresult;
5945: }
5946: } else {
5947: $error = ('error: no unique suffix available for the new item ');
5948: }
5949: # remove lock
5950: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5951: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5952: } else {
5953: $error = "error: could not obtain lockfile\n";
5954: $dellock = 'ok';
5955: }
5956: return ($newid,$dellock,$error);
5957: }
5958:
1.765 albertel 5959: # -------------------------------------------------- portfolio access checking
5960:
5961: sub portfolio_access {
1.766 albertel 5962: my ($requrl) = @_;
1.765 albertel 5963: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5964: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5965: if ($result) {
5966: my %setters;
5967: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5968: my ($startblock,$endblock) =
5969: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5970: if ($startblock && $endblock) {
5971: return 'B';
5972: }
5973: } else {
5974: my ($startblock,$endblock) =
5975: &Apache::loncommon::blockcheck(\%setters,'port');
5976: if ($startblock && $endblock) {
5977: return 'B';
5978: }
5979: }
5980: }
1.765 albertel 5981: if ($result eq 'ok') {
1.766 albertel 5982: return 'F';
1.765 albertel 5983: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5984: return 'A';
1.765 albertel 5985: }
1.766 albertel 5986: return '';
1.765 albertel 5987: }
5988:
5989: sub get_portfolio_access {
1.767 albertel 5990: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5991:
5992: if (!ref($access_hash)) {
5993: my $current_perms = &get_portfile_permissions($udom,$unum);
5994: my %access_controls = &get_access_controls($current_perms,$group,
5995: $file_name);
5996: $access_hash = $access_controls{$file_name};
5997: }
5998:
1.765 albertel 5999: my ($public,$guest,@domains,@users,@courses,@groups);
6000: my $now = time;
6001: if (ref($access_hash) eq 'HASH') {
6002: foreach my $key (keys(%{$access_hash})) {
6003: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6004: if ($start > $now) {
6005: next;
6006: }
6007: if ($end && $end<$now) {
6008: next;
6009: }
6010: if ($scope eq 'public') {
6011: $public = $key;
6012: last;
6013: } elsif ($scope eq 'guest') {
6014: $guest = $key;
6015: } elsif ($scope eq 'domains') {
6016: push(@domains,$key);
6017: } elsif ($scope eq 'users') {
6018: push(@users,$key);
6019: } elsif ($scope eq 'course') {
6020: push(@courses,$key);
6021: } elsif ($scope eq 'group') {
6022: push(@groups,$key);
6023: }
6024: }
6025: if ($public) {
6026: return 'ok';
6027: }
6028: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6029: if ($guest) {
6030: return $guest;
6031: }
6032: } else {
6033: if (@domains > 0) {
6034: foreach my $domkey (@domains) {
6035: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6036: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6037: return 'ok';
6038: }
6039: }
6040: }
6041: }
6042: if (@users > 0) {
6043: foreach my $userkey (@users) {
1.865 raeburn 6044: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6045: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6046: if (ref($item) eq 'HASH') {
6047: if (($item->{'uname'} eq $env{'user.name'}) &&
6048: ($item->{'udom'} eq $env{'user.domain'})) {
6049: return 'ok';
6050: }
6051: }
6052: }
6053: }
1.765 albertel 6054: }
6055: }
6056: my %roleshash;
6057: my @courses_and_groups = @courses;
6058: push(@courses_and_groups,@groups);
6059: if (@courses_and_groups > 0) {
6060: my (%allgroups,%allroles);
6061: my ($start,$end,$role,$sec,$group);
6062: foreach my $envkey (%env) {
1.1060 raeburn 6063: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6064: my $cid = $2.'_'.$3;
6065: if ($1 eq 'gr') {
6066: $group = $4;
6067: $allgroups{$cid}{$group} = $env{$envkey};
6068: } else {
6069: if ($4 eq '') {
6070: $sec = 'none';
6071: } else {
6072: $sec = $4;
6073: }
6074: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6075: }
1.811 albertel 6076: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6077: my $cid = $2.'_'.$3;
6078: if ($4 eq '') {
6079: $sec = 'none';
6080: } else {
6081: $sec = $4;
6082: }
6083: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6084: }
6085: }
6086: if (keys(%allroles) == 0) {
6087: return;
6088: }
6089: foreach my $key (@courses_and_groups) {
6090: my %content = %{$$access_hash{$key}};
6091: my $cnum = $content{'number'};
6092: my $cdom = $content{'domain'};
6093: my $cid = $cdom.'_'.$cnum;
6094: if (!exists($allroles{$cid})) {
6095: next;
6096: }
6097: foreach my $role_id (keys(%{$content{'roles'}})) {
6098: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6099: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6100: my @status = @{$content{'roles'}{$role_id}{'access'}};
6101: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6102: foreach my $role (keys(%{$allroles{$cid}})) {
6103: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6104: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6105: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6106: if (grep/^all$/,@sections) {
6107: return 'ok';
6108: } else {
6109: if (grep/^$sec$/,@sections) {
6110: return 'ok';
6111: }
6112: }
6113: }
6114: }
6115: if (keys(%{$allgroups{$cid}}) == 0) {
6116: if (grep/^none$/,@groups) {
6117: return 'ok';
6118: }
6119: } else {
6120: if (grep/^all$/,@groups) {
6121: return 'ok';
6122: }
6123: foreach my $group (keys(%{$allgroups{$cid}})) {
6124: if (grep/^$group$/,@groups) {
6125: return 'ok';
6126: }
6127: }
6128: }
6129: }
6130: }
6131: }
6132: }
6133: }
6134: if ($guest) {
6135: return $guest;
6136: }
6137: }
6138: }
6139: return;
6140: }
6141:
6142: sub course_group_datechecker {
6143: my ($dates,$now,$status) = @_;
6144: my ($start,$end) = split(/\./,$dates);
6145: if (!$start && !$end) {
6146: return 'ok';
6147: }
6148: if (grep/^active$/,@{$status}) {
6149: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6150: return 'ok';
6151: }
6152: }
6153: if (grep/^previous$/,@{$status}) {
6154: if ($end > $now ) {
6155: return 'ok';
6156: }
6157: }
6158: if (grep/^future$/,@{$status}) {
6159: if ($start > $now) {
6160: return 'ok';
6161: }
6162: }
6163: return;
6164: }
6165:
6166: sub parse_portfolio_url {
6167: my ($url) = @_;
6168:
6169: my ($type,$udom,$unum,$group,$file_name);
6170:
1.823 albertel 6171: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6172: $type = 1;
6173: $udom = $1;
6174: $unum = $2;
6175: $file_name = $3;
1.823 albertel 6176: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6177: $type = 2;
6178: $udom = $1;
6179: $unum = $2;
6180: $group = $3;
6181: $file_name = $3.'/'.$4;
6182: }
6183: if (wantarray) {
6184: return ($type,$udom,$unum,$file_name,$group);
6185: }
6186: return $type;
6187: }
6188:
6189: sub is_portfolio_url {
6190: my ($url) = @_;
6191: return scalar(&parse_portfolio_url($url));
6192: }
6193:
1.798 raeburn 6194: sub is_portfolio_file {
6195: my ($file) = @_;
1.820 raeburn 6196: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6197: return 1;
6198: }
6199: return;
6200: }
6201:
1.976 raeburn 6202: sub usertools_access {
1.1084 raeburn 6203: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6204: my ($access,%tools);
6205: if ($context eq '') {
6206: $context = 'tools';
6207: }
6208: if ($context eq 'requestcourses') {
6209: %tools = (
6210: official => 1,
6211: unofficial => 1,
1.1006 raeburn 6212: community => 1,
1.1246 raeburn 6213: textbook => 1,
1.985 raeburn 6214: );
1.1183 raeburn 6215: } elsif ($context eq 'requestauthor') {
6216: %tools = (
6217: requestauthor => 1,
6218: );
1.985 raeburn 6219: } else {
6220: %tools = (
6221: aboutme => 1,
6222: blog => 1,
1.1177 raeburn 6223: webdav => 1,
1.985 raeburn 6224: portfolio => 1,
6225: );
6226: }
1.976 raeburn 6227: return if (!defined($tools{$tool}));
6228:
1.1242 raeburn 6229: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6230: $udom = $env{'user.domain'};
6231: $uname = $env{'user.name'};
6232: }
6233:
1.978 raeburn 6234: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6235: if ($action ne 'reload') {
1.985 raeburn 6236: if ($context eq 'requestcourses') {
6237: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6238: } elsif ($context eq 'requestauthor') {
6239: return $env{'environment.canrequest.author'};
1.985 raeburn 6240: } else {
6241: return $env{'environment.availabletools.'.$tool};
6242: }
6243: }
1.976 raeburn 6244: }
6245:
1.1183 raeburn 6246: my ($toolstatus,$inststatus,$envkey);
6247: if ($context eq 'requestauthor') {
6248: $envkey = $context;
6249: } else {
6250: $envkey = $context.'.'.$tool;
6251: }
1.976 raeburn 6252:
1.985 raeburn 6253: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6254: ($action ne 'reload')) {
1.1183 raeburn 6255: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6256: $inststatus = $env{'environment.inststatus'};
6257: } else {
1.1084 raeburn 6258: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6259: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6260: $inststatus = $userenvref->{'inststatus'};
6261: } else {
1.1183 raeburn 6262: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6263: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6264: $inststatus = $userenv{'inststatus'};
6265: }
1.976 raeburn 6266: }
6267:
6268: if ($toolstatus ne '') {
6269: if ($toolstatus) {
6270: $access = 1;
6271: } else {
6272: $access = 0;
6273: }
6274: return $access;
6275: }
6276:
1.1084 raeburn 6277: my ($is_adv,%domdef);
6278: if (ref($is_advref) eq 'HASH') {
6279: $is_adv = $is_advref->{'is_adv'};
6280: } else {
6281: $is_adv = &is_advanced_user($udom,$uname);
6282: }
6283: if (ref($domdefref) eq 'HASH') {
6284: %domdef = %{$domdefref};
6285: } else {
6286: %domdef = &get_domain_defaults($udom);
6287: }
1.976 raeburn 6288: if (ref($domdef{$tool}) eq 'HASH') {
6289: if ($is_adv) {
6290: if ($domdef{$tool}{'_LC_adv'} ne '') {
6291: if ($domdef{$tool}{'_LC_adv'}) {
6292: $access = 1;
6293: } else {
6294: $access = 0;
6295: }
6296: return $access;
6297: }
6298: }
6299: if ($inststatus ne '') {
6300: my ($hasaccess,$hasnoaccess);
6301: foreach my $affiliation (split(/:/,$inststatus)) {
6302: if ($domdef{$tool}{$affiliation} ne '') {
6303: if ($domdef{$tool}{$affiliation}) {
6304: $hasaccess = 1;
6305: } else {
6306: $hasnoaccess = 1;
6307: }
6308: }
6309: }
6310: if ($hasaccess || $hasnoaccess) {
6311: if ($hasaccess) {
6312: $access = 1;
6313: } elsif ($hasnoaccess) {
6314: $access = 0;
6315: }
6316: return $access;
6317: }
6318: } else {
6319: if ($domdef{$tool}{'default'} ne '') {
6320: if ($domdef{$tool}{'default'}) {
6321: $access = 1;
6322: } elsif ($domdef{$tool}{'default'} == 0) {
6323: $access = 0;
6324: }
6325: return $access;
6326: }
6327: }
6328: } else {
1.1177 raeburn 6329: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6330: $access = 1;
6331: } else {
6332: $access = 0;
6333: }
1.976 raeburn 6334: return $access;
6335: }
6336: }
6337:
1.1050 raeburn 6338: sub is_course_owner {
6339: my ($cdom,$cnum,$udom,$uname) = @_;
6340: if (($udom eq '') || ($uname eq '')) {
6341: $udom = $env{'user.domain'};
6342: $uname = $env{'user.name'};
6343: }
6344: unless (($udom eq '') || ($uname eq '')) {
6345: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6346: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6347: return 1;
6348: } else {
6349: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6350: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6351: return 1;
6352: }
6353: }
6354: }
6355: }
6356: return;
6357: }
6358:
1.976 raeburn 6359: sub is_advanced_user {
6360: my ($udom,$uname) = @_;
1.1085 raeburn 6361: if ($udom ne '' && $uname ne '') {
6362: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6363: if (wantarray) {
6364: return ($env{'user.adv'},$env{'user.author'});
6365: } else {
6366: return $env{'user.adv'};
6367: }
1.1085 raeburn 6368: }
6369: }
1.976 raeburn 6370: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6371: my %allroles;
1.1128 raeburn 6372: my ($is_adv,$is_author);
1.976 raeburn 6373: foreach my $role (keys(%roleshash)) {
6374: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6375: my $area = '/'.$tdomain.'/'.$trest;
6376: if ($sec ne '') {
6377: $area .= '/'.$sec;
6378: }
6379: if (($area ne '') && ($trole ne '')) {
6380: my $spec=$trole.'.'.$area;
6381: if ($trole =~ /^cr\//) {
6382: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6383: } elsif ($trole ne 'gr') {
6384: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6385: }
1.1128 raeburn 6386: if ($trole eq 'au') {
6387: $is_author = 1;
6388: }
1.976 raeburn 6389: }
6390: }
6391: foreach my $role (keys(%allroles)) {
6392: last if ($is_adv);
6393: foreach my $item (split(/:/,$allroles{$role})) {
6394: if ($item ne '') {
6395: my ($privilege,$restrictions)=split(/&/,$item);
6396: if ($privilege eq 'adv') {
6397: $is_adv = 1;
6398: last;
6399: }
6400: }
6401: }
6402: }
1.1128 raeburn 6403: if (wantarray) {
6404: return ($is_adv,$is_author);
6405: }
1.976 raeburn 6406: return $is_adv;
6407: }
1.798 raeburn 6408:
1.1035 raeburn 6409: sub check_can_request {
1.1036 raeburn 6410: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6411: my $canreq = 0;
6412: my ($types,$typename) = &Apache::loncommon::course_types();
6413: my @options = ('approval','validate','autolimit');
6414: my $optregex = join('|',@options);
6415: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6416: foreach my $type (@{$types}) {
6417: if (&usertools_access($env{'user.name'},
6418: $env{'user.domain'},
6419: $type,undef,'requestcourses')) {
6420: $canreq ++;
1.1036 raeburn 6421: if (ref($request_domains) eq 'HASH') {
6422: push(@{$request_domains->{$type}},$env{'user.domain'});
6423: }
1.1035 raeburn 6424: if ($dom eq $env{'user.domain'}) {
6425: $can_request->{$type} = 1;
6426: }
6427: }
6428: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6429: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6430: if (@curr > 0) {
1.1036 raeburn 6431: foreach my $item (@curr) {
6432: if (ref($request_domains) eq 'HASH') {
6433: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6434: if ($otherdom ne '') {
6435: if (ref($request_domains->{$type}) eq 'ARRAY') {
6436: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6437: push(@{$request_domains->{$type}},$otherdom);
6438: }
6439: } else {
6440: push(@{$request_domains->{$type}},$otherdom);
6441: }
6442: }
6443: }
6444: }
6445: unless($dom eq $env{'user.domain'}) {
6446: $canreq ++;
1.1035 raeburn 6447: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6448: $can_request->{$type} = 1;
6449: }
6450: }
6451: }
6452: }
6453: }
6454: }
6455: return $canreq;
6456: }
6457:
1.341 www 6458: # ---------------------------------------------- Custom access rule evaluation
6459:
6460: sub customaccess {
6461: my ($priv,$uri)=@_;
1.807 albertel 6462: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6463: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6464: $udom = &LONCAPA::clean_domain($udom);
6465: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6466: my $access=0;
1.800 albertel 6467: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6468: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6469: if ($type eq 'user') {
6470: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6471: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6472: if ($tdom) {
6473: if ($tdom ne $env{'user.domain'}) { next; }
6474: }
1.896 albertel 6475: if ($tuname) {
6476: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6477: }
6478: $access=($effect eq 'allow');
6479: last;
6480: }
6481: } else {
6482: if ($role) {
6483: if ($role ne $urole) { next; }
6484: }
6485: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6486: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6487: if ($tdom) {
6488: if ($tdom ne $udom) { next; }
6489: }
6490: if ($tcrs) {
6491: if ($tcrs ne $ucrs) { next; }
6492: }
6493: if ($tsec) {
6494: if ($tsec ne $usec) { next; }
6495: }
6496: $access=($effect eq 'allow');
6497: last;
6498: }
6499: if ($realm eq '' && $role eq '') {
6500: $access=($effect eq 'allow');
6501: }
1.402 bowersj2 6502: }
1.341 www 6503: }
6504: return $access;
6505: }
6506:
1.103 harris41 6507: # ------------------------------------------------- Check for a user privilege
1.12 www 6508:
6509: sub allowed {
1.810 raeburn 6510: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6511: my $ver_orguri=$uri;
1.439 www 6512: $uri=&deversion($uri);
1.152 www 6513: my $orguri=$uri;
1.52 www 6514: $uri=&declutter($uri);
1.809 raeburn 6515:
1.810 raeburn 6516: if ($priv eq 'evb') {
6517: # Evade communication block restrictions for specified role in a course
6518: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6519: return $1;
6520: } else {
6521: return;
6522: }
6523: }
6524:
1.620 albertel 6525: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6526: # Free bre access to adm and meta resources
1.775 albertel 6527: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6528: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6529: && ($priv eq 'bre')) {
1.14 www 6530: return 'F';
1.159 www 6531: }
6532:
1.545 banghart 6533: # Free bre access to user's own portfolio contents
1.714 raeburn 6534: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6535: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6536: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6537: my %setters;
6538: my ($startblock,$endblock) =
6539: &Apache::loncommon::blockcheck(\%setters,'port');
6540: if ($startblock && $endblock) {
6541: return 'B';
6542: } else {
6543: return 'F';
6544: }
1.545 banghart 6545: }
6546:
1.762 raeburn 6547: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6548: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6549: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6550: if (exists($env{'request.course.id'})) {
6551: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6552: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6553: if (($domain eq $cdom) && ($name eq $cnum)) {
6554: my $courseprivid=$env{'request.course.id'};
6555: $courseprivid=~s/\_/\//;
6556: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6557: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6558: return $1;
1.762 raeburn 6559: } else {
6560: if ($env{'request.course.sec'}) {
6561: $courseprivid.='/'.$env{'request.course.sec'};
6562: }
6563: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6564: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6565: return $2;
6566: }
1.714 raeburn 6567: }
6568: }
6569: }
6570: }
6571:
1.159 www 6572: # Free bre to public access
6573:
6574: if ($priv eq 'bre') {
1.238 www 6575: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6576: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6577: return 'F';
6578: }
1.238 www 6579: if ($copyright eq 'priv') {
6580: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6581: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6582: return '';
6583: }
6584: }
6585: if ($copyright eq 'domain') {
6586: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6587: unless (($env{'user.domain'} eq $1) ||
6588: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6589: return '';
6590: }
1.262 matthew 6591: }
1.620 albertel 6592: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6593: # Library role, so allow browsing of resources in this domain.
6594: return 'F';
1.238 www 6595: }
1.341 www 6596: if ($copyright eq 'custom') {
6597: unless (&customaccess($priv,$uri)) { return ''; }
6598: }
1.14 www 6599: }
1.264 matthew 6600: # Domain coordinator is trying to create a course
1.620 albertel 6601: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6602: # uri is the requested domain in this case.
6603: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6604: # a role of dc for the domain in question.
1.620 albertel 6605: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6606: }
1.29 www 6607:
1.52 www 6608: my $thisallowed='';
6609: my $statecond=0;
6610: my $courseprivid='';
6611:
1.1039 raeburn 6612: my $ownaccess;
1.1043 raeburn 6613: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6614: if (($priv eq 'bro') && ($env{'user.author'})) {
6615: if ($uri eq '') {
6616: $ownaccess = 1;
6617: } else {
6618: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6619: my $udom = $env{'user.domain'};
6620: my $uname = $env{'user.name'};
6621: if ($uri =~ m{^\Q$udom\E/?$}) {
6622: $ownaccess = 1;
1.1040 raeburn 6623: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6624: unless ($uri =~ m{\.\./}) {
6625: $ownaccess = 1;
6626: }
6627: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6628: my $now = time;
6629: if ($uri =~ m{^([^/]+)/?$}) {
6630: my $adom = $1;
6631: foreach my $key (keys(%env)) {
1.1042 raeburn 6632: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6633: my ($start,$end) = split('.',$env{$key});
6634: if (($now >= $start) && (!$end || $end < $now)) {
6635: $ownaccess = 1;
6636: last;
6637: }
6638: }
6639: }
6640: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6641: my $adom = $1;
6642: my $aname = $2;
1.1042 raeburn 6643: foreach my $role ('ca','aa') {
6644: if ($env{"user.role.$role./$adom/$aname"}) {
6645: my ($start,$end) =
6646: split('.',$env{"user.role.$role./$adom/$aname"});
6647: if (($now >= $start) && (!$end || $end < $now)) {
6648: $ownaccess = 1;
6649: last;
6650: }
1.1039 raeburn 6651: }
6652: }
6653: }
6654: }
6655: }
6656: }
6657: }
6658:
1.52 www 6659: # Course
6660:
1.620 albertel 6661: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6662: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6663: $thisallowed.=$1;
6664: }
1.52 www 6665: }
1.29 www 6666:
1.52 www 6667: # Domain
6668:
1.620 albertel 6669: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6670: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6671: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6672: $thisallowed.=$1;
6673: }
1.12 www 6674: }
1.52 www 6675:
1.1141 raeburn 6676: # User who is not author or co-author might still be able to edit
6677: # resource of an author in the domain (e.g., if Domain Coordinator).
6678: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6679: (&allowed('mdc',$env{'request.course.id'}))) {
6680: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6681: $thisallowed.=$1;
6682: }
6683: }
6684:
1.52 www 6685: # Course: uri itself is a course
1.66 www 6686: my $courseuri=$uri;
6687: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6688: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6689:
1.620 albertel 6690: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6691: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6692: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6693: $thisallowed.=$1;
6694: }
1.12 www 6695: }
1.29 www 6696:
1.665 albertel 6697: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6698: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6699: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6700: $thisallowed='';
1.671 raeburn 6701: my ($match)=&is_on_map($uri);
6702: if ($match) {
6703: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6704: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6705: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6706: if (@blockers > 0) {
6707: $thisallowed = 'B';
6708: } else {
6709: $thisallowed.=$1;
6710: }
1.671 raeburn 6711: }
6712: } else {
1.705 albertel 6713: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6714: if ($refuri) {
6715: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6716: $thisallowed='F';
1.671 raeburn 6717: } else {
6718: $refuri=&declutter($refuri);
6719: my ($match) = &is_on_map($refuri);
6720: if ($match) {
1.1162 raeburn 6721: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6722: if (@blockers > 0) {
6723: $thisallowed = 'B';
6724: } else {
6725: $thisallowed='F';
6726: }
1.671 raeburn 6727: }
1.669 raeburn 6728: }
1.671 raeburn 6729: }
6730: }
1.314 www 6731: }
1.492 albertel 6732:
1.766 albertel 6733: if ($priv eq 'bre'
6734: && $thisallowed ne 'F'
6735: && $thisallowed ne '2'
6736: && &is_portfolio_url($uri)) {
6737: $thisallowed = &portfolio_access($uri);
6738: }
6739:
1.52 www 6740: # Full access at system, domain or course-wide level? Exit.
1.29 www 6741: if ($thisallowed=~/F/) {
6742: return 'F';
6743: }
6744:
1.52 www 6745: # If this is generating or modifying users, exit with special codes
1.29 www 6746:
1.643 www 6747: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6748: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6749: my ($audom,$auname)=split('/',$uri);
1.643 www 6750: # no author name given, so this just checks on the general right to make a co-author in this domain
6751: unless ($auname) { return $thisallowed; }
6752: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6753: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6754: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6755: ($audom ne $env{'request.role.domain'}))) { return ''; }
6756: }
1.52 www 6757: return $thisallowed;
6758: }
6759: #
1.103 harris41 6760: # Gathered so far: system, domain and course wide privileges
1.52 www 6761: #
6762: # Course: See if uri or referer is an individual resource that is part of
6763: # the course
6764:
1.620 albertel 6765: if ($env{'request.course.id'}) {
1.232 www 6766:
1.620 albertel 6767: $courseprivid=$env{'request.course.id'};
6768: if ($env{'request.course.sec'}) {
6769: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6770: }
6771: $courseprivid=~s/\_/\//;
6772: my $checkreferer=1;
1.232 www 6773: my ($match,$cond)=&is_on_map($uri);
6774: if ($match) {
6775: $statecond=$cond;
1.620 albertel 6776: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6777: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6778: my $value = $1;
6779: if ($priv eq 'bre') {
6780: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6781: if (@blockers > 0) {
6782: $thisallowed = 'B';
6783: } else {
6784: $thisallowed.=$value;
6785: }
6786: } else {
6787: $thisallowed.=$value;
6788: }
1.52 www 6789: $checkreferer=0;
6790: }
1.29 www 6791: }
1.83 www 6792:
1.148 www 6793: if ($checkreferer) {
1.620 albertel 6794: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6795: unless ($refuri) {
1.800 albertel 6796: foreach my $key (keys(%env)) {
6797: if ($key=~/^httpref\..*\*/) {
6798: my $pattern=$key;
1.156 www 6799: $pattern=~s/^httpref\.\/res\///;
1.148 www 6800: $pattern=~s/\*/\[\^\/\]\+/g;
6801: $pattern=~s/\//\\\//g;
1.152 www 6802: if ($orguri=~/$pattern/) {
1.800 albertel 6803: $refuri=$env{$key};
1.148 www 6804: }
6805: }
1.191 harris41 6806: }
1.148 www 6807: }
1.232 www 6808:
1.148 www 6809: if ($refuri) {
1.152 www 6810: $refuri=&declutter($refuri);
1.232 www 6811: my ($match,$cond)=&is_on_map($refuri);
6812: if ($match) {
6813: my $refstatecond=$cond;
1.620 albertel 6814: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6815: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6816: my $value = $1;
6817: if ($priv eq 'bre') {
6818: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6819: if (@blockers > 0) {
6820: $thisallowed = 'B';
6821: } else {
6822: $thisallowed.=$value;
6823: }
6824: } else {
6825: $thisallowed.=$value;
6826: }
1.53 www 6827: $uri=$refuri;
6828: $statecond=$refstatecond;
1.52 www 6829: }
6830: }
1.148 www 6831: }
1.29 www 6832: }
1.52 www 6833: }
1.29 www 6834:
1.52 www 6835: #
1.103 harris41 6836: # Gathered now: all privileges that could apply, and condition number
1.52 www 6837: #
6838: #
6839: # Full or no access?
6840: #
1.29 www 6841:
1.52 www 6842: if ($thisallowed=~/F/) {
6843: return 'F';
6844: }
1.29 www 6845:
1.52 www 6846: unless ($thisallowed) {
6847: return '';
6848: }
1.29 www 6849:
1.52 www 6850: # Restrictions exist, deal with them
6851: #
6852: # C:according to course preferences
6853: # R:according to resource settings
6854: # L:unless locked
6855: # X:according to user session state
6856: #
6857:
6858: # Possibly locked functionality, check all courses
1.54 www 6859: # Locks might take effect only after 10 minutes cache expiration for other
6860: # courses, and 2 minutes for current course
1.52 www 6861:
6862: my $envkey;
6863: if ($thisallowed=~/L/) {
1.1000 raeburn 6864: foreach $envkey (keys(%env)) {
1.54 www 6865: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6866: my $courseid=$2;
6867: my $roleid=$1.'.'.$2;
1.92 www 6868: $courseid=~s/^\///;
1.54 www 6869: my $expiretime=600;
1.620 albertel 6870: if ($env{'request.role'} eq $roleid) {
1.54 www 6871: $expiretime=120;
6872: }
6873: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6874: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6875: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6876: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6877: }
1.620 albertel 6878: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6879: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6880: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6881: &log($env{'user.domain'},$env{'user.name'},
6882: $env{'user.home'},
1.57 www 6883: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6884: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6885: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6886: return '';
6887: }
6888: }
1.620 albertel 6889: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6890: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6891: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6892: &log($env{'user.domain'},$env{'user.name'},
6893: $env{'user.home'},
1.57 www 6894: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6895: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6896: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6897: return '';
6898: }
6899: }
6900: }
1.29 www 6901: }
1.52 www 6902: }
6903:
6904: #
6905: # Rest of the restrictions depend on selected course
6906: #
6907:
1.620 albertel 6908: unless ($env{'request.course.id'}) {
1.766 albertel 6909: if ($thisallowed eq 'A') {
6910: return 'A';
1.814 raeburn 6911: } elsif ($thisallowed eq 'B') {
6912: return 'B';
1.766 albertel 6913: } else {
6914: return '1';
6915: }
1.52 www 6916: }
1.29 www 6917:
1.52 www 6918: #
6919: # Now user is definitely in a course
6920: #
1.53 www 6921:
6922:
6923: # Course preferences
6924:
6925: if ($thisallowed=~/C/) {
1.620 albertel 6926: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6927: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6928: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6929: =~/\Q$rolecode\E/) {
1.1103 raeburn 6930: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6931: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6932: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6933: $env{'request.course.id'});
6934: }
1.237 www 6935: return '';
6936: }
6937:
1.620 albertel 6938: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6939: =~/\Q$unamedom\E/) {
1.1103 raeburn 6940: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6941: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6942: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6943: $env{'request.course.id'});
6944: }
1.54 www 6945: return '';
6946: }
1.53 www 6947: }
6948:
6949: # Resource preferences
6950:
6951: if ($thisallowed=~/R/) {
1.620 albertel 6952: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6953: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6954: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6955: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6956: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6957: }
6958: return '';
1.54 www 6959: }
1.53 www 6960: }
1.30 www 6961:
1.246 www 6962: # Restricted by state or randomout?
1.30 www 6963:
1.52 www 6964: if ($thisallowed=~/X/) {
1.620 albertel 6965: if ($env{'acc.randomout'}) {
1.579 albertel 6966: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6967: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6968: return '';
6969: }
1.247 www 6970: }
6971: if (&condval($statecond)) {
1.52 www 6972: return '2';
6973: } else {
6974: return '';
6975: }
6976: }
1.30 www 6977:
1.766 albertel 6978: if ($thisallowed eq 'A') {
6979: return 'A';
1.814 raeburn 6980: } elsif ($thisallowed eq 'B') {
6981: return 'B';
1.766 albertel 6982: }
1.52 www 6983: return 'F';
1.232 www 6984: }
1.1162 raeburn 6985:
1.1192 raeburn 6986: # ------------------------------------------- Check construction space access
6987:
6988: sub constructaccess {
6989: my ($url,$setpriv)=@_;
6990:
6991: # We do not allow editing of previous versions of files
6992: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6993:
6994: # Get username and domain from URL
6995: my ($ownername,$ownerdomain,$ownerhome);
6996:
6997: ($ownerdomain,$ownername) =
6998: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6999:
7000: # The URL does not really point to any authorspace, forget it
7001: unless (($ownername) && ($ownerdomain)) { return ''; }
7002:
7003: # Now we need to see if the user has access to the authorspace of
7004: # $ownername at $ownerdomain
7005:
7006: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7007: # Real author for this?
7008: $ownerhome = $env{'user.home'};
7009: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7010: return ($ownername,$ownerdomain,$ownerhome);
7011: }
7012: } else {
7013: # Co-author for this?
7014: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7015: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7016: $ownerhome = &homeserver($ownername,$ownerdomain);
7017: return ($ownername,$ownerdomain,$ownerhome);
7018: }
7019: }
7020:
7021: # We don't have any access right now. If we are not possibly going to do anything about this,
7022: # we might as well leave
7023: unless ($setpriv) { return ''; }
7024:
7025: # Backdoor access?
7026: my $allowed=&allowed('eco',$ownerdomain);
7027: # Nope
7028: unless ($allowed) { return ''; }
7029: # Looks like we may have access, but could be locked by the owner of the construction space
7030: if ($allowed eq 'U') {
7031: my %blocked=&get('environment',['domcoord.author'],
7032: $ownerdomain,$ownername);
7033: # Is blocked by owner
7034: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7035: }
7036: if (($allowed eq 'F') || ($allowed eq 'U')) {
7037: # Grant temporary access
7038: my $then=$env{'user.login.time'};
1.1209 raeburn 7039: my $update=$env{'user.update.time'};
1.1192 raeburn 7040: if (!$update) { $update = $then; }
7041: my $refresh=$env{'user.refresh.time'};
7042: if (!$refresh) { $refresh = $update; }
7043: my $now = time;
7044: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7045: $now,'ca','constructaccess');
7046: $ownerhome = &homeserver($ownername,$ownerdomain);
7047: return($ownername,$ownerdomain,$ownerhome);
7048: }
7049: # No business here
7050: return '';
7051: }
7052:
1.1162 raeburn 7053: sub get_comm_blocks {
7054: my ($cdom,$cnum) = @_;
7055: if ($cdom eq '' || $cnum eq '') {
7056: return unless ($env{'request.course.id'});
7057: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7058: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7059: }
7060: my %commblocks;
7061: my $hashid=$cdom.'_'.$cnum;
7062: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7063: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7064: %commblocks = %{$blocksref};
7065: } else {
7066: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7067: my $cachetime = 600;
7068: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7069: }
7070: return %commblocks;
7071: }
7072:
7073: sub has_comm_blocking {
7074: my ($priv,$symb,$uri,$blocks) = @_;
7075: return unless ($env{'request.course.id'});
7076: return unless ($priv eq 'bre');
7077: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7078: my %commblocks;
7079: if (ref($blocks) eq 'HASH') {
7080: %commblocks = %{$blocks};
7081: } else {
7082: %commblocks = &get_comm_blocks();
7083: }
7084: return unless (keys(%commblocks) > 0);
7085: if (!$symb) { $symb=&symbread($uri,1); }
7086: my ($map,$resid,undef)=&decode_symb($symb);
7087: my %tocheck = (
7088: maps => $map,
7089: resources => $symb,
7090: );
7091: my @blockers;
7092: my $now = time;
1.1163 raeburn 7093: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7094: foreach my $block (keys(%commblocks)) {
7095: if ($block =~ /^(\d+)____(\d+)$/) {
7096: my ($start,$end) = ($1,$2);
7097: if ($start <= $now && $end >= $now) {
7098: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7099: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7100: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7101: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7102: unless (grep(/^\Q$block\E$/,@blockers)) {
7103: push(@blockers,$block);
7104: }
7105: }
7106: }
7107: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7108: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7109: unless (grep(/^\Q$block\E$/,@blockers)) {
7110: push(@blockers,$block);
7111: }
7112: }
7113: }
7114: }
7115: }
7116: }
7117: } elsif ($block =~ /^firstaccess____(.+)$/) {
7118: my $item = $1;
1.1163 raeburn 7119: my @to_test;
1.1162 raeburn 7120: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7121: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7122: my $check_interval;
7123: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7124: my @interval;
7125: my $type = 'map';
7126: if ($item eq 'course') {
7127: $type = 'course';
7128: @interval=&EXT("resource.0.interval");
7129: } else {
7130: if ($item =~ /___\d+___/) {
7131: $type = 'resource';
7132: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7133: if (ref($navmap)) {
7134: my $res = $navmap->getBySymb($item);
7135: push(@to_test,$res);
7136: }
1.1162 raeburn 7137: } else {
7138: my $mapsymb = &symbread($item,1);
7139: if ($mapsymb) {
7140: if (ref($navmap)) {
7141: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7142: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7143: foreach my $res (@to_test) {
1.1162 raeburn 7144: my $symb = $res->symb();
7145: next if ($symb eq $mapsymb);
7146: if ($symb ne '') {
7147: @interval=&EXT("resource.0.interval",$symb);
7148: last;
7149: }
7150: }
7151: }
7152: }
7153: }
7154: }
7155: if ($interval[0] =~ /\d+/) {
7156: my $first_access;
7157: if ($type eq 'resource') {
7158: $first_access=&get_first_access($interval[1],$item);
7159: } elsif ($type eq 'map') {
7160: $first_access=&get_first_access($interval[1],undef,$item);
7161: } else {
7162: $first_access=&get_first_access($interval[1]);
7163: }
7164: if ($first_access) {
7165: my $timesup = $first_access+$interval[0];
7166: if ($timesup > $now) {
1.1163 raeburn 7167: foreach my $res (@to_test) {
7168: if ($res->is_problem()) {
7169: if ($res->completable()) {
7170: unless (grep(/^\Q$block\E$/,@blockers)) {
7171: push(@blockers,$block);
7172: }
7173: last;
7174: }
7175: }
1.1162 raeburn 7176: }
7177: }
7178: }
7179: }
7180: }
7181: }
7182: }
7183: }
7184: }
7185: return @blockers;
7186: }
7187:
7188: sub check_docs_block {
7189: my ($docsblock,$tocheck) =@_;
7190: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7191: return;
7192: }
7193: if (ref($docsblock->{'maps'}) eq 'HASH') {
7194: if ($tocheck->{'maps'}) {
7195: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7196: return 1;
7197: }
7198: }
7199: }
7200: if (ref($docsblock->{'resources'}) eq 'HASH') {
7201: if ($tocheck->{'resources'}) {
7202: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7203: return 1;
7204: }
7205: }
7206: }
7207: return;
7208: }
7209:
1.1133 foxr 7210: #
7211: # Removes the versino from a URI and
7212: # splits it in to its filename and path to the filename.
7213: # Seems like File::Basename could have done this more clearly.
7214: # Parameters:
7215: # $uri - input URI
7216: # Returns:
7217: # Two element list consisting of
7218: # $pathname - the URI up to and excluding the trailing /
7219: # $filename - The part of the URI following the last /
7220: # NOTE:
7221: # Another realization of this is simply:
7222: # use File::Basename;
7223: # ...
7224: # $uri = shift;
7225: # $filename = basename($uri);
7226: # $path = dirname($uri);
7227: # return ($filename, $path);
7228: #
7229: # The implementation below is probably faster however.
7230: #
1.710 albertel 7231: sub split_uri_for_cond {
7232: my $uri=&deversion(&declutter(shift));
7233: my @uriparts=split(/\//,$uri);
7234: my $filename=pop(@uriparts);
7235: my $pathname=join('/',@uriparts);
7236: return ($pathname,$filename);
7237: }
1.232 www 7238: # --------------------------------------------------- Is a resource on the map?
7239:
7240: sub is_on_map {
1.710 albertel 7241: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7242: #Trying to find the conditional for the file
1.620 albertel 7243: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7244: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7245: if ($match) {
1.289 bowersj2 7246: return (1,$1);
7247: } else {
1.434 www 7248: return (0,0);
1.289 bowersj2 7249: }
1.12 www 7250: }
7251:
1.427 www 7252: # --------------------------------------------------------- Get symb from alias
7253:
7254: sub get_symb_from_alias {
7255: my $symb=shift;
7256: my ($map,$resid,$url)=&decode_symb($symb);
7257: # Already is a symb
7258: if ($url) { return $symb; }
7259: # Must be an alias
7260: my $aliassymb='';
7261: my %bighash;
1.620 albertel 7262: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7263: &GDBM_READER(),0640)) {
7264: my $rid=$bighash{'mapalias_'.$symb};
7265: if ($rid) {
7266: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7267: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7268: $resid,$bighash{'src_'.$rid});
1.427 www 7269: }
7270: untie %bighash;
7271: }
7272: return $aliassymb;
7273: }
7274:
1.12 www 7275: # ----------------------------------------------------------------- Define Role
7276:
7277: sub definerole {
7278: if (allowed('mcr','/')) {
7279: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7280: foreach my $role (split(':',$sysrole)) {
7281: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7282: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7283: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7284: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7285: return "refused:s:$crole&$cqual";
7286: }
7287: }
1.191 harris41 7288: }
1.800 albertel 7289: foreach my $role (split(':',$domrole)) {
7290: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7291: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7292: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7293: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7294: return "refused:d:$crole&$cqual";
7295: }
7296: }
1.191 harris41 7297: }
1.800 albertel 7298: foreach my $role (split(':',$courole)) {
7299: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7300: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7301: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7302: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7303: return "refused:c:$crole&$cqual";
7304: }
7305: }
1.191 harris41 7306: }
1.620 albertel 7307: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7308: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7309: "rolesdef_$rolename=".
7310: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7311: return reply($command,$env{'user.home'});
1.12 www 7312: } else {
7313: return 'refused';
7314: }
1.105 harris41 7315: }
7316:
7317: # ---------------- Make a metadata query against the network of library servers
7318:
7319: sub metadata_query {
1.1237 raeburn 7320: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7321: my %rhash;
1.845 albertel 7322: my %libserv = &all_library();
1.244 matthew 7323: my @server_list = (defined($server_array) ? @$server_array
7324: : keys(%libserv) );
7325: for my $server (@server_list) {
1.1237 raeburn 7326: my $domains = '';
7327: if (ref($domains_hash) eq 'HASH') {
7328: $domains = $domains_hash->{$server};
7329: }
1.118 harris41 7330: unless ($custom or $customshow) {
1.1237 raeburn 7331: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7332: $rhash{$server}=$reply;
7333: }
7334: else {
7335: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7336: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7337: $server);
7338: $rhash{$server}=$reply;
7339: }
1.112 harris41 7340: }
1.118 harris41 7341: return \%rhash;
1.240 www 7342: }
7343:
7344: # ----------------------------------------- Send log queries and wait for reply
7345:
7346: sub log_query {
7347: my ($uname,$udom,$query,%filters)=@_;
7348: my $uhome=&homeserver($uname,$udom);
7349: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7350: my $uhost=&hostname($uhome);
1.800 albertel 7351: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7352: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7353: $uhome);
1.479 albertel 7354: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7355: return get_query_reply($queryid);
7356: }
7357:
1.818 raeburn 7358: # -------------------------- Update MySQL table for portfolio file
7359:
7360: sub update_portfolio_table {
1.821 raeburn 7361: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7362: if ($group ne '') {
7363: $file_name =~s /^\Q$group\E//;
7364: }
1.818 raeburn 7365: my $homeserver = &homeserver($uname,$udom);
7366: my $queryid=
1.821 raeburn 7367: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7368: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7369: my $reply = &get_query_reply($queryid);
7370: return $reply;
7371: }
7372:
1.899 raeburn 7373: # -------------------------- Update MySQL allusers table
7374:
7375: sub update_allusers_table {
7376: my ($uname,$udom,$names) = @_;
7377: my $homeserver = &homeserver($uname,$udom);
7378: my $queryid=
7379: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7380: 'lastname='.&escape($names->{'lastname'}).'%%'.
7381: 'firstname='.&escape($names->{'firstname'}).'%%'.
7382: 'middlename='.&escape($names->{'middlename'}).'%%'.
7383: 'generation='.&escape($names->{'generation'}).'%%'.
7384: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7385: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7386: return;
1.899 raeburn 7387: }
7388:
1.508 raeburn 7389: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7390:
7391: sub fetch_enrollment_query {
1.511 raeburn 7392: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7393: my $homeserver;
1.547 raeburn 7394: my $maxtries = 1;
1.508 raeburn 7395: if ($context eq 'automated') {
7396: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7397: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7398: } else {
7399: $homeserver = &homeserver($cnum,$dom);
7400: }
1.838 albertel 7401: my $host=&hostname($homeserver);
1.506 raeburn 7402: my $cmd = '';
1.1000 raeburn 7403: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7404: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7405: }
7406: $cmd =~ s/%%$//;
7407: $cmd = &escape($cmd);
7408: my $query = 'fetchenrollment';
1.620 albertel 7409: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7410: unless ($queryid=~/^\Q$host\E\_/) {
7411: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7412: return 'error: '.$queryid;
7413: }
1.506 raeburn 7414: my $reply = &get_query_reply($queryid);
1.547 raeburn 7415: my $tries = 1;
7416: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7417: $reply = &get_query_reply($queryid);
7418: $tries ++;
7419: }
1.526 raeburn 7420: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7421: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7422: } else {
1.901 albertel 7423: my @responses = split(/:/,$reply);
1.515 raeburn 7424: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7425: foreach my $line (@responses) {
7426: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7427: $$replyref{$key} = $value;
7428: }
7429: } else {
1.1117 foxr 7430: my $pathname = LONCAPA::tempdir();
1.800 albertel 7431: foreach my $line (@responses) {
7432: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7433: $$replyref{$key} = $value;
7434: if ($value > 0) {
1.800 albertel 7435: foreach my $item (@{$$affiliatesref{$key}}) {
7436: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7437: my $destname = $pathname.'/'.$filename;
7438: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7439: if ($xml_classlist =~ /^error/) {
7440: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7441: } else {
1.506 raeburn 7442: if ( open(FILE,">$destname") ) {
7443: print FILE &unescape($xml_classlist);
7444: close(FILE);
1.526 raeburn 7445: } else {
7446: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7447: }
7448: }
7449: }
7450: }
7451: }
7452: }
7453: return 'ok';
7454: }
7455: return 'error';
7456: }
7457:
1.242 www 7458: sub get_query_reply {
7459: my $queryid=shift;
1.1117 foxr 7460: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7461: my $reply='';
7462: for (1..100) {
7463: sleep 2;
7464: if (-e $replyfile.'.end') {
1.448 albertel 7465: if (open(my $fh,$replyfile)) {
1.904 albertel 7466: $reply = join('',<$fh>);
7467: close($fh);
1.240 www 7468: } else { return 'error: reply_file_error'; }
1.242 www 7469: return &unescape($reply);
7470: }
1.240 www 7471: }
1.242 www 7472: return 'timeout:'.$queryid;
1.240 www 7473: }
7474:
7475: sub courselog_query {
1.241 www 7476: #
7477: # possible filters:
7478: # url: url or symb
7479: # username
7480: # domain
7481: # action: view, submit, grade
7482: # start: timestamp
7483: # end: timestamp
7484: #
1.240 www 7485: my (%filters)=@_;
1.620 albertel 7486: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7487: if ($filters{'url'}) {
7488: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7489: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7490: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7491: }
1.620 albertel 7492: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7493: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7494: return &log_query($cname,$cdom,'courselog',%filters);
7495: }
7496:
7497: sub userlog_query {
1.858 raeburn 7498: #
7499: # possible filters:
7500: # action: log check role
7501: # start: timestamp
7502: # end: timestamp
7503: #
1.240 www 7504: my ($uname,$udom,%filters)=@_;
7505: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7506: }
7507:
1.506 raeburn 7508: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7509:
7510: sub auto_run {
1.508 raeburn 7511: my ($cnum,$cdom) = @_;
1.876 raeburn 7512: my $response = 0;
7513: my $settings;
7514: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7515: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7516: $settings = $domconfig{'autoenroll'};
7517: if ($settings->{'run'} eq '1') {
7518: $response = 1;
7519: }
7520: } else {
1.934 raeburn 7521: my $homeserver;
7522: if (&is_course($cdom,$cnum)) {
7523: $homeserver = &homeserver($cnum,$cdom);
7524: } else {
7525: $homeserver = &domain($cdom,'primary');
7526: }
7527: if ($homeserver ne 'no_host') {
7528: $response = &reply('autorun:'.$cdom,$homeserver);
7529: }
1.876 raeburn 7530: }
1.506 raeburn 7531: return $response;
7532: }
1.776 albertel 7533:
1.506 raeburn 7534: sub auto_get_sections {
1.508 raeburn 7535: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7536: my $homeserver;
7537: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7538: $homeserver = &homeserver($cnum,$cdom);
7539: }
7540: if (!defined($homeserver)) {
7541: if ($cdom =~ /^$match_domain$/) {
7542: $homeserver = &domain($cdom,'primary');
7543: }
7544: }
7545: my @secs;
7546: if (defined($homeserver)) {
7547: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7548: unless ($response eq 'refused') {
7549: @secs = split(/:/,$response);
7550: }
1.506 raeburn 7551: }
7552: return @secs;
7553: }
1.776 albertel 7554:
1.506 raeburn 7555: sub auto_new_course {
1.1099 raeburn 7556: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7557: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7558: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7559: return $response;
7560: }
1.776 albertel 7561:
1.506 raeburn 7562: sub auto_validate_courseID {
1.508 raeburn 7563: my ($cnum,$cdom,$inst_course_id) = @_;
7564: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7565: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7566: return $response;
7567: }
1.776 albertel 7568:
1.1007 raeburn 7569: sub auto_validate_instcode {
1.1020 raeburn 7570: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7571: my ($homeserver,$response);
7572: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7573: $homeserver = &homeserver($cnum,$cdom);
7574: }
7575: if (!defined($homeserver)) {
7576: if ($cdom =~ /^$match_domain$/) {
7577: $homeserver = &domain($cdom,'primary');
7578: }
7579: }
1.1065 raeburn 7580: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7581: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7582: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7583: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7584: }
7585:
1.506 raeburn 7586: sub auto_create_password {
1.873 raeburn 7587: my ($cnum,$cdom,$authparam,$udom) = @_;
7588: my ($homeserver,$response);
1.506 raeburn 7589: my $create_passwd = 0;
7590: my $authchk = '';
1.873 raeburn 7591: if ($udom =~ /^$match_domain$/) {
7592: $homeserver = &domain($udom,'primary');
7593: }
7594: if ($homeserver eq '') {
7595: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7596: $homeserver = &homeserver($cnum,$cdom);
7597: }
7598: }
7599: if ($homeserver eq '') {
7600: $authchk = 'nodomain';
1.506 raeburn 7601: } else {
1.873 raeburn 7602: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7603: if ($response eq 'refused') {
7604: $authchk = 'refused';
7605: } else {
1.901 albertel 7606: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7607: }
1.506 raeburn 7608: }
7609: return ($authparam,$create_passwd,$authchk);
7610: }
7611:
1.706 raeburn 7612: sub auto_photo_permission {
7613: my ($cnum,$cdom,$students) = @_;
7614: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7615: my ($outcome,$perm_reqd,$conditions) =
7616: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7617: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7618: return (undef,undef);
7619: }
1.706 raeburn 7620: return ($outcome,$perm_reqd,$conditions);
7621: }
7622:
7623: sub auto_checkphotos {
7624: my ($uname,$udom,$pid) = @_;
7625: my $homeserver = &homeserver($uname,$udom);
7626: my ($result,$resulttype);
7627: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7628: &escape($uname).':'.&escape($pid),
7629: $homeserver));
1.709 albertel 7630: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7631: return (undef,undef);
7632: }
1.706 raeburn 7633: if ($outcome) {
7634: ($result,$resulttype) = split(/:/,$outcome);
7635: }
7636: return ($result,$resulttype);
7637: }
7638:
7639: sub auto_photochoice {
7640: my ($cnum,$cdom) = @_;
7641: my $homeserver = &homeserver($cnum,$cdom);
7642: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7643: &escape($cdom),
7644: $homeserver)));
1.709 albertel 7645: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7646: return (undef,undef);
7647: }
1.706 raeburn 7648: return ($update,$comment);
7649: }
7650:
7651: sub auto_photoupdate {
7652: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7653: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7654: my $host=&hostname($homeserver);
1.706 raeburn 7655: my $cmd = '';
7656: my $maxtries = 1;
1.800 albertel 7657: foreach my $affiliate (keys(%{$affiliatesref})) {
7658: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7659: }
7660: $cmd =~ s/%%$//;
7661: $cmd = &escape($cmd);
7662: my $query = 'institutionalphotos';
7663: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7664: unless ($queryid=~/^\Q$host\E\_/) {
7665: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7666: return 'error: '.$queryid;
7667: }
7668: my $reply = &get_query_reply($queryid);
7669: my $tries = 1;
7670: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7671: $reply = &get_query_reply($queryid);
7672: $tries ++;
7673: }
7674: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7675: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7676: } else {
7677: my @responses = split(/:/,$reply);
7678: my $outcome = shift(@responses);
7679: foreach my $item (@responses) {
7680: my ($key,$value) = split(/=/,$item);
7681: $$photo{$key} = $value;
7682: }
7683: return $outcome;
7684: }
7685: return 'error';
7686: }
7687:
1.521 raeburn 7688: sub auto_instcode_format {
1.793 albertel 7689: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7690: $cat_order) = @_;
1.521 raeburn 7691: my $courses = '';
1.772 raeburn 7692: my @homeservers;
1.521 raeburn 7693: if ($caller eq 'global') {
1.841 albertel 7694: my %servers = &get_servers($codedom,'library');
7695: foreach my $tryserver (keys(%servers)) {
7696: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7697: push(@homeservers,$tryserver);
7698: }
1.584 raeburn 7699: }
1.1022 raeburn 7700: } elsif ($caller eq 'requests') {
7701: if ($codedom =~ /^$match_domain$/) {
7702: my $chome = &domain($codedom,'primary');
7703: unless ($chome eq 'no_host') {
7704: push(@homeservers,$chome);
7705: }
7706: }
1.521 raeburn 7707: } else {
1.772 raeburn 7708: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7709: }
1.793 albertel 7710: foreach my $code (keys(%{$instcodes})) {
7711: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7712: }
7713: chop($courses);
1.772 raeburn 7714: my $ok_response = 0;
7715: my $response;
7716: while (@homeservers > 0 && $ok_response == 0) {
7717: my $server = shift(@homeservers);
7718: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7719: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7720: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7721: split(/:/,$response);
1.772 raeburn 7722: %{$codes} = (%{$codes},&str2hash($codes_str));
7723: push(@{$codetitles},&str2array($codetitles_str));
7724: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7725: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7726: $ok_response = 1;
7727: }
7728: }
7729: if ($ok_response) {
1.521 raeburn 7730: return 'ok';
1.772 raeburn 7731: } else {
7732: return $response;
1.521 raeburn 7733: }
7734: }
7735:
1.792 raeburn 7736: sub auto_instcode_defaults {
7737: my ($domain,$returnhash,$code_order) = @_;
7738: my @homeservers;
1.841 albertel 7739:
7740: my %servers = &get_servers($domain,'library');
7741: foreach my $tryserver (keys(%servers)) {
7742: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7743: push(@homeservers,$tryserver);
7744: }
1.792 raeburn 7745: }
1.841 albertel 7746:
1.792 raeburn 7747: my $response;
1.841 albertel 7748: foreach my $server (@homeservers) {
1.792 raeburn 7749: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7750: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7751:
7752: foreach my $pair (split(/\&/,$response)) {
7753: my ($name,$value)=split(/\=/,$pair);
7754: if ($name eq 'code_order') {
7755: @{$code_order} = split(/\&/,&unescape($value));
7756: } else {
7757: $returnhash->{&unescape($name)}=&unescape($value);
7758: }
7759: }
7760: return 'ok';
1.792 raeburn 7761: }
1.841 albertel 7762:
7763: return $response;
1.1003 raeburn 7764: }
7765:
7766: sub auto_possible_instcodes {
1.1007 raeburn 7767: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7768: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7769: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7770: return;
7771: }
1.1003 raeburn 7772: my (@homeservers,$uhome);
7773: if (defined(&domain($domain,'primary'))) {
7774: $uhome=&domain($domain,'primary');
7775: push(@homeservers,&domain($domain,'primary'));
7776: } else {
7777: my %servers = &get_servers($domain,'library');
7778: foreach my $tryserver (keys(%servers)) {
7779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7780: push(@homeservers,$tryserver);
7781: }
7782: }
7783: }
7784: my $response;
7785: foreach my $server (@homeservers) {
7786: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7788: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7789: split(':',$response);
7790: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7791: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7792: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7793: my ($name,$value)=split('=',$item);
7794: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7795: }
7796: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7797: my ($name,$value)=split('=',$item);
7798: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7799: }
7800: return 'ok';
7801: }
7802: return $response;
7803: }
1.792 raeburn 7804:
1.1010 raeburn 7805: sub auto_courserequest_checks {
7806: my ($dom) = @_;
1.1020 raeburn 7807: my ($homeserver,%validations);
7808: if ($dom =~ /^$match_domain$/) {
7809: $homeserver = &domain($dom,'primary');
7810: }
7811: unless ($homeserver eq 'no_host') {
7812: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7813: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7814: my @items = split(/&/,$response);
7815: foreach my $item (@items) {
7816: my ($key,$value) = split('=',$item);
7817: $validations{&unescape($key)} = &thaw_unescape($value);
7818: }
7819: }
7820: }
1.1010 raeburn 7821: return %validations;
7822: }
7823:
1.1020 raeburn 7824: sub auto_courserequest_validation {
7825: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7826: my ($homeserver,$response);
7827: if ($dom =~ /^$match_domain$/) {
7828: $homeserver = &domain($dom,'primary');
7829: }
7830: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7831:
1.1020 raeburn 7832: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7833: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7834: ':'.&escape($instcode).':'.&escape($instseclist),
7835: $homeserver));
7836: }
7837: return $response;
7838: }
7839:
1.777 albertel 7840: sub auto_validate_class_sec {
1.918 raeburn 7841: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7842: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7843: my $ownerlist;
7844: if (ref($owners) eq 'ARRAY') {
7845: $ownerlist = join(',',@{$owners});
7846: } else {
7847: $ownerlist = $owners;
7848: }
1.773 raeburn 7849: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7850: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7851: return $response;
7852: }
7853:
1.1248 raeburn 7854: sub auto_crsreq_update {
7855: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7856: $code,$inbound) = @_;
7857: my ($homeserver,%crsreqresponse);
7858: if ($cdom =~ /^$match_domain$/) {
7859: $homeserver = &domain($cdom,'primary');
7860: }
7861: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7862: my $info;
7863: if (ref($inbound) eq 'HASH') {
7864: $info = &freeze_escape($inbound);
7865: }
7866: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7867: ':'.&escape($action).':'.&escape($ownername).':'.
7868: &escape($ownerdomain).':'.&escape($fullname).':'.
7869: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7870: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7871: my @items = split(/&/,$response);
7872: foreach my $item (@items) {
7873: my ($key,$value) = split('=',$item);
7874: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7875: }
7876: }
7877: }
7878: return \%crsreqresponse;
7879: }
7880:
1.679 raeburn 7881: # ------------------------------------------------------- Course Group routines
7882:
7883: sub get_coursegroups {
1.809 raeburn 7884: my ($cdom,$cnum,$group,$namespace) = @_;
7885: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7886: }
7887:
1.679 raeburn 7888: sub modify_coursegroup {
7889: my ($cdom,$cnum,$groupsettings) = @_;
7890: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7891: }
7892:
1.809 raeburn 7893: sub toggle_coursegroup_status {
7894: my ($cdom,$cnum,$group,$action) = @_;
7895: my ($from_namespace,$to_namespace);
7896: if ($action eq 'delete') {
7897: $from_namespace = 'coursegroups';
7898: $to_namespace = 'deleted_groups';
7899: } else {
7900: $from_namespace = 'deleted_groups';
7901: $to_namespace = 'coursegroups';
7902: }
7903: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7904: if (my $tmp = &error(%curr_group)) {
7905: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7906: return ('read error',$tmp);
7907: } else {
7908: my %savedsettings = %curr_group;
1.809 raeburn 7909: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7910: my $deloutcome;
7911: if ($result eq 'ok') {
1.809 raeburn 7912: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7913: } else {
7914: return ('write error',$result);
7915: }
7916: if ($deloutcome eq 'ok') {
7917: return 'ok';
7918: } else {
7919: return ('delete error',$deloutcome);
7920: }
7921: }
7922: }
7923:
1.679 raeburn 7924: sub modify_group_roles {
1.957 raeburn 7925: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7926: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7927: my $role = 'gr/'.&escape($userprivs);
7928: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7929: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7930: if ($result eq 'ok') {
7931: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7932: }
1.679 raeburn 7933: return $result;
7934: }
7935:
7936: sub modify_coursegroup_membership {
7937: my ($cdom,$cnum,$membership) = @_;
7938: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7939: return $result;
7940: }
7941:
1.682 raeburn 7942: sub get_active_groups {
7943: my ($udom,$uname,$cdom,$cnum) = @_;
7944: my $now = time;
7945: my %groups = ();
7946: foreach my $key (keys(%env)) {
1.811 albertel 7947: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7948: my ($start,$end) = split(/\./,$env{$key});
7949: if (($end!=0) && ($end<$now)) { next; }
7950: if (($start!=0) && ($start>$now)) { next; }
7951: if ($1 eq $cdom && $2 eq $cnum) {
7952: $groups{$3} = $env{$key} ;
7953: }
7954: }
7955: }
7956: return %groups;
7957: }
7958:
1.683 raeburn 7959: sub get_group_membership {
7960: my ($cdom,$cnum,$group) = @_;
7961: return(&dump('groupmembership',$cdom,$cnum,$group));
7962: }
7963:
7964: sub get_users_groups {
7965: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7966: my @usersgroups;
1.683 raeburn 7967: my $cachetime=1800;
7968:
7969: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7970: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7971: if (defined($cached)) {
1.734 albertel 7972: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7973: } else {
7974: $grouplist = '';
1.816 raeburn 7975: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7976: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7977: my $access_end = $env{'course.'.$courseid.
7978: '.default_enrollment_end_date'};
7979: my $now = time;
7980: foreach my $key (keys(%roleshash)) {
7981: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7982: my $group = $1;
7983: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7984: my $start = $2;
7985: my $end = $1;
7986: if ($start == -1) { next; } # deleted from group
7987: if (($start!=0) && ($start>$now)) { next; }
7988: if (($end!=0) && ($end<$now)) {
7989: if ($access_end && $access_end < $now) {
7990: if ($access_end - $end < 86400) {
7991: push(@usersgroups,$group);
1.733 raeburn 7992: }
7993: }
1.817 raeburn 7994: next;
1.733 raeburn 7995: }
1.817 raeburn 7996: push(@usersgroups,$group);
1.683 raeburn 7997: }
7998: }
7999: }
1.817 raeburn 8000: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8001: $grouplist = join(':',@usersgroups);
8002: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8003: }
1.733 raeburn 8004: return @usersgroups;
1.683 raeburn 8005: }
8006:
8007: sub devalidate_getgroups_cache {
8008: my ($udom,$uname,$cdom,$cnum)=@_;
8009: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8010:
1.683 raeburn 8011: my $hashid="$udom:$uname:$courseid";
8012: &devalidate_cache_new('getgroups',$hashid);
8013: }
8014:
1.12 www 8015: # ------------------------------------------------------------------ Plain Text
8016:
8017: sub plaintext {
1.988 raeburn 8018: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8019: if ($short =~ m{^cr/}) {
1.758 albertel 8020: return (split('/',$short))[-1];
8021: }
1.742 raeburn 8022: if (!defined($cid)) {
8023: $cid = $env{'request.course.id'};
8024: }
8025: my %rolenames = (
1.1008 raeburn 8026: Course => 'std',
8027: Community => 'alt1',
1.742 raeburn 8028: );
1.1037 raeburn 8029: if ($cid ne '') {
8030: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8031: unless ($forcedefault) {
8032: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8033: &Apache::lonlocal::mt_escape(\$roletext);
8034: return &Apache::lonlocal::mt($roletext);
8035: }
8036: }
8037: }
8038: if ((defined($type)) && (defined($rolenames{$type})) &&
8039: (defined($rolenames{$type})) &&
8040: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8041: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8042: } elsif ($cid ne '') {
8043: my $crstype = $env{'course.'.$cid.'.type'};
8044: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8045: (defined($prp{$short}{$rolenames{$crstype}}))) {
8046: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8047: }
1.742 raeburn 8048: }
1.1037 raeburn 8049: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8050: }
8051:
8052: # ----------------------------------------------------------------- Assign Role
8053:
8054: sub assignrole {
1.957 raeburn 8055: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8056: $context)=@_;
1.21 www 8057: my $mrole;
8058: if ($role =~ /^cr\//) {
1.393 www 8059: my $cwosec=$url;
1.811 albertel 8060: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8061: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8062: my $refused = 1;
8063: if ($context eq 'requestcourses') {
8064: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8065: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8066: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8067: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8068: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8069: if ($crsenv{'internal.courseowner'} eq
8070: $env{'user.name'}.':'.$env{'user.domain'}) {
8071: $refused = '';
8072: }
8073: }
8074: }
8075: }
8076: }
8077: if ($refused) {
8078: &logthis('Refused custom assignrole: '.
8079: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8080: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8081: return 'refused';
8082: }
1.104 www 8083: }
1.21 www 8084: $mrole='cr';
1.678 raeburn 8085: } elsif ($role =~ /^gr\//) {
8086: my $cwogrp=$url;
1.811 albertel 8087: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8088: unless (&allowed('mdg',$cwogrp)) {
8089: &logthis('Refused group assignrole: '.
8090: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8091: $env{'user.name'}.' at '.$env{'user.domain'});
8092: return 'refused';
8093: }
8094: $mrole='gr';
1.21 www 8095: } else {
1.82 www 8096: my $cwosec=$url;
1.811 albertel 8097: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8098: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8099: my $refused;
8100: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8101: if (!(&allowed('c'.$role,$url))) {
8102: $refused = 1;
8103: }
8104: } else {
8105: $refused = 1;
8106: }
1.947 raeburn 8107: if ($refused) {
1.1045 raeburn 8108: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8109: if (!$selfenroll && $context eq 'course') {
8110: my %crsenv;
8111: if ($role eq 'cc' || $role eq 'co') {
8112: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8113: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8114: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8115: if ($crsenv{'internal.courseowner'} eq
8116: $env{'user.name'}.':'.$env{'user.domain'}) {
8117: $refused = '';
8118: }
8119: }
8120: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8121: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8122: if ($crsenv{'internal.courseowner'} eq
8123: $env{'user.name'}.':'.$env{'user.domain'}) {
8124: $refused = '';
8125: }
8126: }
8127: }
8128: }
8129: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8130: $refused = '';
1.1017 raeburn 8131: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8132: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8133: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8134: my $wrongcc;
8135: if ($cnum =~ /^$match_community$/) {
8136: $wrongcc = 1 if ($role eq 'cc');
8137: } else {
8138: $wrongcc = 1 if ($role eq 'co');
8139: }
8140: unless ($wrongcc) {
8141: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8142: if ($crsenv{'internal.courseowner'} eq
8143: $env{'user.name'}.':'.$env{'user.domain'}) {
8144: $refused = '';
8145: }
1.1017 raeburn 8146: }
8147: }
1.1183 raeburn 8148: } elsif ($context eq 'requestauthor') {
8149: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8150: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8151: if ($env{'environment.requestauthor'} eq 'automatic') {
8152: $refused = '';
8153: } else {
8154: my %domdefaults = &get_domain_defaults($udom);
8155: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8156: my $checkbystatus;
8157: if ($env{'user.adv'}) {
8158: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8159: if ($disposition eq 'automatic') {
8160: $refused = '';
8161: } elsif ($disposition eq '') {
8162: $checkbystatus = 1;
8163: }
8164: } else {
8165: $checkbystatus = 1;
8166: }
8167: if ($checkbystatus) {
8168: if ($env{'environment.inststatus'}) {
8169: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8170: foreach my $type (@inststatuses) {
8171: if (($type ne '') &&
8172: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8173: $refused = '';
8174: }
8175: }
8176: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8177: $refused = '';
8178: }
8179: }
8180: }
8181: }
8182: }
1.1017 raeburn 8183: }
8184: if ($refused) {
1.947 raeburn 8185: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8186: ' '.$role.' '.$end.' '.$start.' by '.
8187: $env{'user.name'}.' at '.$env{'user.domain'});
8188: return 'refused';
8189: }
1.932 raeburn 8190: }
1.1131 raeburn 8191: } elsif ($role eq 'au') {
8192: if ($url ne '/'.$udom.'/') {
8193: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8194: ' to assign author role for '.$uname.':'.$udom.
8195: ' in domain: '.$url.' refused (wrong domain).');
8196: return 'refused';
8197: }
1.104 www 8198: }
1.21 www 8199: $mrole=$role;
8200: }
1.620 albertel 8201: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8202: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8203: if ($end) { $command.='_'.$end; }
1.21 www 8204: if ($start) {
8205: if ($end) {
1.81 www 8206: $command.='_'.$start;
1.21 www 8207: } else {
1.81 www 8208: $command.='_0_'.$start;
1.21 www 8209: }
8210: }
1.739 raeburn 8211: my $origstart = $start;
8212: my $origend = $end;
1.957 raeburn 8213: my $delflag;
1.357 www 8214: # actually delete
8215: if ($deleteflag) {
1.373 www 8216: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8217: # modify command to delete the role
1.620 albertel 8218: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8219: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8220: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8221: # set start and finish to negative values for userrolelog
8222: $start=-1;
8223: $end=-1;
1.957 raeburn 8224: $delflag = 1;
1.357 www 8225: }
8226: }
8227: # send command
1.349 www 8228: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8229: # log new user role if status is ok
1.349 www 8230: if ($answer eq 'ok') {
1.663 raeburn 8231: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8232: if (($role eq 'cc') || ($role eq 'in') ||
8233: ($role eq 'ep') || ($role eq 'ad') ||
8234: ($role eq 'ta') || ($role eq 'st') ||
8235: ($role=~/^cr/) || ($role eq 'gr') ||
8236: ($role eq 'co')) {
1.1200 raeburn 8237: # for course roles, perform group memberships changes triggered by role change.
8238: unless ($role =~ /^gr/) {
8239: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8240: $origstart,$selfenroll,$context);
8241: }
1.1184 raeburn 8242: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8243: $selfenroll,$context);
8244: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8245: ($role eq 'au') || ($role eq 'dc')) {
8246: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8247: $context);
8248: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8249: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8250: $context);
8251: }
1.1053 raeburn 8252: if ($role eq 'cc') {
8253: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8254: }
1.349 www 8255: }
8256: return $answer;
1.169 harris41 8257: }
8258:
1.1053 raeburn 8259: sub autoupdate_coowners {
8260: my ($url,$end,$start,$uname,$udom) = @_;
8261: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8262: if (($cdom ne '') && ($cnum ne '')) {
8263: my $now = time;
8264: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8265: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8266: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8267: my $instcode = $coursehash{'internal.coursecode'};
8268: if ($instcode ne '') {
1.1056 raeburn 8269: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8270: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8271: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8272: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8273: if ($result eq 'valid') {
8274: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8275: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8276: push(@newcoowners,$coowner);
8277: }
8278: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8279: push(@newcoowners,$uname.':'.$udom);
8280: }
8281: @newcoowners = sort(@newcoowners);
8282: } else {
8283: push(@newcoowners,$uname.':'.$udom);
8284: }
8285: } else {
8286: if ($coursehash{'internal.co-owners'}) {
8287: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8288: unless ($coowner eq $uname.':'.$udom) {
8289: push(@newcoowners,$coowner);
8290: }
8291: }
8292: unless (@newcoowners > 0) {
8293: $delcoowners = 1;
8294: $coowners = '';
8295: }
8296: }
8297: }
8298: if (@newcoowners || $delcoowners) {
8299: &store_coowners($cdom,$cnum,$coursehash{'home'},
8300: $delcoowners,@newcoowners);
8301: }
8302: }
8303: }
8304: }
8305: }
8306: }
8307: }
8308:
8309: sub store_coowners {
8310: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8311: my $cid = $cdom.'_'.$cnum;
8312: my ($coowners,$delresult,$putresult);
8313: if (@newcoowners) {
8314: $coowners = join(',',@newcoowners);
8315: my %coownershash = (
8316: 'internal.co-owners' => $coowners,
8317: );
8318: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8319: if ($putresult eq 'ok') {
8320: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8321: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8322: }
8323: }
8324: }
8325: if ($delcoowners) {
8326: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8327: if ($delresult eq 'ok') {
8328: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8329: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8330: }
8331: }
8332: }
8333: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8334: my %crsinfo =
8335: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8336: if (ref($crsinfo{$cid}) eq 'HASH') {
8337: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8338: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8339: }
8340: }
8341: }
8342:
1.169 harris41 8343: # -------------------------------------------------- Modify user authentication
1.197 www 8344: # Overrides without validation
8345:
1.169 harris41 8346: sub modifyuserauth {
8347: my ($udom,$uname,$umode,$upass)=@_;
8348: my $uhome=&homeserver($uname,$udom);
1.197 www 8349: unless (&allowed('mau',$udom)) { return 'refused'; }
8350: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8351: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8352: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8353: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8354: &escape($upass),$uhome);
1.620 albertel 8355: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8356: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8357: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8358: &log($udom,,$uname,$uhome,
1.620 albertel 8359: 'Authentication changed by '.$env{'user.domain'}.', '.
8360: $env{'user.name'}.', '.$umode.
1.197 www 8361: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8362: unless ($reply eq 'ok') {
1.197 www 8363: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8364: return 'error: '.$reply;
8365: }
1.170 harris41 8366: return 'ok';
1.80 www 8367: }
8368:
1.81 www 8369: # --------------------------------------------------------------- Modify a user
1.80 www 8370:
1.81 www 8371: sub modifyuser {
1.206 matthew 8372: my ($udom, $uname, $uid,
8373: $umode, $upass, $first,
8374: $middle, $last, $gene,
1.1058 raeburn 8375: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8376: $udom= &LONCAPA::clean_domain($udom);
8377: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8378: my $showcandelete = 'none';
8379: if (ref($candelete) eq 'ARRAY') {
8380: if (@{$candelete} > 0) {
8381: $showcandelete = join(', ',@{$candelete});
8382: }
8383: }
1.81 www 8384: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8385: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8386: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8387: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8388: ' desiredhome not specified').
1.620 albertel 8389: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8390: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8391: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8392: my $newuser;
8393: if ($uhome eq 'no_host') {
8394: $newuser = 1;
8395: }
1.80 www 8396: # ----------------------------------------------------------------- Create User
1.406 albertel 8397: if (($uhome eq 'no_host') &&
8398: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8399: my $unhome='';
1.844 albertel 8400: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8401: $unhome = $desiredhome;
1.620 albertel 8402: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8403: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8404: } else { # load balancing routine for determining $unhome
1.81 www 8405: my $loadm=10000000;
1.841 albertel 8406: my %servers = &get_servers($udom,'library');
8407: foreach my $tryserver (keys(%servers)) {
8408: my $answer=reply('load',$tryserver);
8409: if (($answer=~/\d+/) && ($answer<$loadm)) {
8410: $loadm=$answer;
8411: $unhome=$tryserver;
8412: }
1.80 www 8413: }
8414: }
8415: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8416: return 'error: unable to find a home server for '.$uname.
8417: ' in domain '.$udom;
1.80 www 8418: }
8419: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8420: &escape($upass),$unhome);
8421: unless ($reply eq 'ok') {
8422: return 'error: '.$reply;
8423: }
1.230 stredwic 8424: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8425: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8426: return 'error: unable verify users home machine.';
1.80 www 8427: }
1.209 matthew 8428: } # End of creation of new user
1.80 www 8429: # ---------------------------------------------------------------------- Add ID
8430: if ($uid) {
8431: $uid=~tr/A-Z/a-z/;
8432: my %uidhash=&idrget($udom,$uname);
1.196 www 8433: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8434: && (!$forceid)) {
1.80 www 8435: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8436: return 'error: user id "'.$uid.'" does not match '.
8437: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8438: }
8439: } else {
8440: &idput($udom,($uname => $uid));
8441: }
8442: }
8443: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8444: my @tmp=&get('environment',
1.899 raeburn 8445: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8446: 'permanentemail','inststatus'],
1.134 albertel 8447: $udom,$uname);
1.1075 raeburn 8448: my (%names,%oldnames);
1.313 matthew 8449: if ($tmp[0] =~ m/^error:.*/) {
8450: %names=();
8451: } else {
8452: %names = @tmp;
1.1075 raeburn 8453: %oldnames = %names;
1.313 matthew 8454: }
1.388 www 8455: #
1.1058 raeburn 8456: # If name, email and/or uid are blank (e.g., because an uploaded file
8457: # of users did not contain them), do not overwrite existing values
8458: # unless field is in $candelete array ref.
8459: #
8460:
8461: my @fields = ('firstname','middlename','lastname','generation',
8462: 'permanentemail','id');
8463: my %newvalues;
8464: if (ref($candelete) eq 'ARRAY') {
8465: foreach my $field (@fields) {
8466: if (grep(/^\Q$field\E$/,@{$candelete})) {
8467: if ($field eq 'firstname') {
8468: $names{$field} = $first;
8469: } elsif ($field eq 'middlename') {
8470: $names{$field} = $middle;
8471: } elsif ($field eq 'lastname') {
8472: $names{$field} = $last;
8473: } elsif ($field eq 'generation') {
8474: $names{$field} = $gene;
8475: } elsif ($field eq 'permanentemail') {
8476: $names{$field} = $email;
8477: } elsif ($field eq 'id') {
8478: $names{$field} = $uid;
8479: }
8480: }
8481: }
8482: }
1.388 www 8483: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8484: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8485: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8486: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8487: if ($email) {
8488: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8489: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8490: }
1.899 raeburn 8491: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8492: if (defined($inststatus)) {
8493: $names{'inststatus'} = '';
8494: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8495: if (ref($usertypes) eq 'HASH') {
8496: my @okstatuses;
8497: foreach my $item (split(/:/,$inststatus)) {
8498: if (defined($usertypes->{$item})) {
8499: push(@okstatuses,$item);
8500: }
8501: }
8502: if (@okstatuses) {
8503: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8504: }
8505: }
8506: }
1.1075 raeburn 8507: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8508: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8509: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8510: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8511: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8512: } else {
8513: $logmsg .= ' during self creation';
8514: }
1.1075 raeburn 8515: my $changed;
8516: if ($newuser) {
8517: $changed = 1;
8518: } else {
8519: foreach my $field (@fields) {
8520: if ($names{$field} ne $oldnames{$field}) {
8521: $changed = 1;
8522: last;
8523: }
8524: }
8525: }
8526: unless ($changed) {
8527: $logmsg = 'No changes in user information needed for: '.$logmsg;
8528: &logthis($logmsg);
8529: return 'ok';
8530: }
8531: my $reply = &put('environment', \%names, $udom,$uname);
8532: if ($reply ne 'ok') {
8533: return 'error: '.$reply;
8534: }
1.1087 raeburn 8535: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8536: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8537: }
1.1075 raeburn 8538: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8539: &devalidate_cache_new('namescache',$uname.':'.$udom);
8540: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8541: &logthis($logmsg);
1.134 albertel 8542: return 'ok';
1.80 www 8543: }
8544:
1.81 www 8545: # -------------------------------------------------------------- Modify student
1.80 www 8546:
1.81 www 8547: sub modifystudent {
8548: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8549: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8550: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8551: if (!$cid) {
1.620 albertel 8552: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8553: return 'not_in_class';
8554: }
1.80 www 8555: }
8556: # --------------------------------------------------------------- Make the user
1.81 www 8557: my $reply=&modifyuser
1.209 matthew 8558: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8559: $desiredhome,$email,$inststatus);
1.80 www 8560: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8561: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8562: # student's environment
1.297 matthew 8563: $uid = undef if (!$forceid);
1.455 albertel 8564: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8565: $gene,$usec,$end,$start,$type,$locktype,
8566: $cid,$selfenroll,$context,$credits);
1.297 matthew 8567: return $reply;
8568: }
8569:
8570: sub modify_student_enrollment {
1.1216 raeburn 8571: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8572: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8573: my ($cdom,$cnum,$chome);
8574: if (!$cid) {
1.620 albertel 8575: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8576: return 'not_in_class';
8577: }
1.620 albertel 8578: $cdom=$env{'course.'.$cid.'.domain'};
8579: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8580: } else {
8581: ($cdom,$cnum)=split(/_/,$cid);
8582: }
1.620 albertel 8583: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8584: if (!$chome) {
1.457 raeburn 8585: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8586: }
1.455 albertel 8587: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8588: # Make sure the user exists
1.81 www 8589: my $uhome=&homeserver($uname,$udom);
8590: if (($uhome eq '') || ($uhome eq 'no_host')) {
8591: return 'error: no such user';
8592: }
1.297 matthew 8593: # Get student data if we were not given enough information
8594: if (!defined($first) || $first eq '' ||
8595: !defined($last) || $last eq '' ||
8596: !defined($uid) || $uid eq '' ||
8597: !defined($middle) || $middle eq '' ||
8598: !defined($gene) || $gene eq '') {
1.294 matthew 8599: # They did not supply us with enough data to enroll the student, so
8600: # we need to pick up more information.
1.297 matthew 8601: my %tmp = &get('environment',
1.294 matthew 8602: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8603: ,$udom,$uname);
8604:
1.800 albertel 8605: #foreach my $key (keys(%tmp)) {
8606: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8607: #}
1.294 matthew 8608: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8609: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8610: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8611: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8612: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8613: }
1.556 albertel 8614: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8615: my $user = "$uname:$udom";
8616: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8617: my $reply=cput('classlist',
1.1148 raeburn 8618: {$user =>
1.1216 raeburn 8619: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8620: $cdom,$cnum);
1.1148 raeburn 8621: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8622: &devalidate_getsection_cache($udom,$uname,$cid);
8623: } else {
1.81 www 8624: return 'error: '.$reply;
8625: }
1.297 matthew 8626: # Add student role to user
1.83 www 8627: my $uurl='/'.$cid;
1.81 www 8628: $uurl=~s/\_/\//g;
8629: if ($usec) {
8630: $uurl.='/'.$usec;
8631: }
1.1148 raeburn 8632: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8633: $selfenroll,$context);
8634: if ($result ne 'ok') {
8635: if ($old_entry{$user} ne '') {
8636: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8637: } else {
8638: $reply = &del('classlist',[$user],$cdom,$cnum);
8639: }
8640: }
8641: return $result;
1.21 www 8642: }
8643:
1.556 albertel 8644: sub format_name {
8645: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8646: my $name;
8647: if ($first ne 'lastname') {
8648: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8649: } else {
8650: if ($lastname=~/\S/) {
8651: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8652: $name=~s/\s+,/,/;
8653: } else {
8654: $name.= $firstname.' '.$middlename.' '.$generation;
8655: }
8656: }
8657: $name=~s/^\s+//;
8658: $name=~s/\s+$//;
8659: $name=~s/\s+/ /g;
8660: return $name;
8661: }
8662:
1.84 www 8663: # ------------------------------------------------- Write to course preferences
8664:
8665: sub writecoursepref {
8666: my ($courseid,%prefs)=@_;
8667: $courseid=~s/^\///;
8668: $courseid=~s/\_/\//g;
8669: my ($cdomain,$cnum)=split(/\//,$courseid);
8670: my $chome=homeserver($cnum,$cdomain);
8671: if (($chome eq '') || ($chome eq 'no_host')) {
8672: return 'error: no such course';
8673: }
8674: my $cstring='';
1.800 albertel 8675: foreach my $pref (keys(%prefs)) {
8676: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8677: }
1.84 www 8678: $cstring=~s/\&$//;
8679: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8680: }
8681:
8682: # ---------------------------------------------------------- Make/modify course
8683:
8684: sub createcourse {
1.741 raeburn 8685: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8686: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8687: $url=&declutter($url);
8688: my $cid='';
1.1028 raeburn 8689: if ($context eq 'requestcourses') {
8690: my $can_create = 0;
8691: my ($ownername,$ownerdom) = split(':',$course_owner);
8692: if ($udom eq $ownerdom) {
8693: if (&usertools_access($ownername,$ownerdom,$category,undef,
8694: $context)) {
8695: $can_create = 1;
8696: }
8697: } else {
8698: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8699: $category);
8700: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8701: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8702: if (@curr > 0) {
8703: my @options = qw(approval validate autolimit);
8704: my $optregex = join('|',@options);
8705: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8706: $can_create = 1;
8707: }
8708: }
8709: }
8710: }
8711: if ($can_create) {
8712: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8713: unless (&allowed('ccc',$udom)) {
8714: return 'refused';
8715: }
1.1017 raeburn 8716: }
8717: } else {
8718: return 'refused';
8719: }
1.1028 raeburn 8720: } elsif (!&allowed('ccc',$udom)) {
8721: return 'refused';
1.84 www 8722: }
1.1011 raeburn 8723: # --------------------------------------------------------------- Get Unique ID
8724: my $uname;
8725: if ($cnum =~ /^$match_courseid$/) {
8726: my $chome=&homeserver($cnum,$udom,'true');
8727: if (($chome eq '') || ($chome eq 'no_host')) {
8728: $uname = $cnum;
8729: } else {
1.1038 raeburn 8730: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8731: }
8732: } else {
1.1038 raeburn 8733: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8734: }
8735: return $uname if ($uname =~ /^error/);
8736: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8737: if (!defined($course_server)) {
8738: if (defined(&domain($udom,'primary'))) {
8739: $course_server = &domain($udom,'primary');
8740: } else {
8741: $course_server = $env{'user.home'};
8742: }
8743: }
8744: my %host_servers =
8745: &Apache::lonnet::get_servers($udom,'library');
8746: unless ($host_servers{$course_server}) {
8747: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8748: }
1.84 www 8749: # ------------------------------------------------------------- Make the course
8750: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8751: $course_server);
1.84 www 8752: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8753: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8754: if (($uhome eq '') || ($uhome eq 'no_host')) {
8755: return 'error: no such course';
8756: }
1.271 www 8757: # ----------------------------------------------------------------- Course made
1.516 raeburn 8758: # log existence
1.1029 raeburn 8759: my $now = time;
1.918 raeburn 8760: my $newcourse = {
8761: $udom.'_'.$uname => {
1.921 raeburn 8762: description => $description,
8763: inst_code => $inst_code,
8764: owner => $course_owner,
8765: type => $crstype,
1.1029 raeburn 8766: creator => $env{'user.name'}.':'.
8767: $env{'user.domain'},
8768: created => $now,
8769: context => $context,
1.918 raeburn 8770: },
8771: };
1.921 raeburn 8772: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8773: # set toplevel url
1.271 www 8774: my $topurl=$url;
8775: unless ($nonstandard) {
8776: # ------------------------------------------ For standard courses, make top url
8777: my $mapurl=&clutter($url);
1.278 www 8778: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8779: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8780: <map>
8781: <resource id="1" type="start"></resource>
8782: <resource id="2" src="$mapurl"></resource>
8783: <resource id="3" type="finish"></resource>
8784: <link index="1" from="1" to="2"></link>
8785: <link index="2" from="2" to="3"></link>
8786: </map>
8787: ENDINITMAP
8788: $topurl=&declutter(
1.638 albertel 8789: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8790: );
8791: }
8792: # ----------------------------------------------------------- Write preferences
1.84 www 8793: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8794: ('description' => $description,
8795: 'url' => $topurl,
8796: 'internal.creator' => $env{'user.name'}.':'.
8797: $env{'user.domain'},
8798: 'internal.created' => $now,
8799: 'internal.creationcontext' => $context)
8800: );
1.84 www 8801: return '/'.$udom.'/'.$uname;
8802: }
8803:
1.1011 raeburn 8804: # ------------------------------------------------------------------- Create ID
8805: sub generate_coursenum {
1.1038 raeburn 8806: my ($udom,$crstype) = @_;
1.1011 raeburn 8807: my $domdesc = &domain($udom);
8808: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8809: my $first;
8810: if ($crstype eq 'Community') {
8811: $first = '0';
8812: } else {
8813: $first = int(1+rand(9));
8814: }
8815: my $uname=$first.
1.1011 raeburn 8816: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8817: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8818: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8819: # ----------------------------------------------- Make sure that does not exist
8820: my $uhome=&homeserver($uname,$udom,'true');
8821: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8822: if ($crstype eq 'Community') {
8823: $first = '0';
8824: } else {
8825: $first = int(1+rand(9));
8826: }
8827: $uname=$first.
1.1011 raeburn 8828: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8829: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8830: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8831: $uhome=&homeserver($uname,$udom,'true');
8832: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8833: return 'error: unable to generate unique course-ID';
8834: }
8835: }
8836: return $uname;
8837: }
8838:
1.813 albertel 8839: sub is_course {
1.1167 droeschl 8840: my ($cdom, $cnum) = scalar(@_) == 1 ?
8841: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8842:
8843: return unless $cdom and $cnum;
8844:
8845: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8846: '.');
8847:
1.1219 raeburn 8848: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8849: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8850: }
8851:
1.1015 raeburn 8852: sub store_userdata {
8853: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8854: my $result;
1.1016 raeburn 8855: if ($datakey ne '') {
1.1013 raeburn 8856: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8857: if ($udom eq '' || $uname eq '') {
8858: $udom = $env{'user.domain'};
8859: $uname = $env{'user.name'};
8860: }
8861: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8862: if (($uhome eq '') || ($uhome eq 'no_host')) {
8863: $result = 'error: no_host';
8864: } else {
8865: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8866: $storehash->{'host'} = $perlvar{'lonHostID'};
8867:
8868: my $namevalue='';
8869: foreach my $key (keys(%{$storehash})) {
8870: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8871: }
8872: $namevalue=~s/\&$//;
1.1224 raeburn 8873: unless ($namespace eq 'courserequests') {
8874: $datakey = &escape($datakey);
8875: }
1.1105 raeburn 8876: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8877: $namevalue,$uhome);
1.1013 raeburn 8878: }
8879: } else {
8880: $result = 'error: data to store was not a hash reference';
8881: }
8882: } else {
8883: $result= 'error: invalid requestkey';
8884: }
8885: return $result;
8886: }
8887:
1.21 www 8888: # ---------------------------------------------------------- Assign Custom Role
8889:
8890: sub assigncustomrole {
1.957 raeburn 8891: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8892: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8893: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8894: }
8895:
8896: # ----------------------------------------------------------------- Revoke Role
8897:
8898: sub revokerole {
1.957 raeburn 8899: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8900: my $now=time;
1.965 raeburn 8901: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8902: }
8903:
8904: # ---------------------------------------------------------- Revoke Custom Role
8905:
8906: sub revokecustomrole {
1.957 raeburn 8907: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8908: my $now=time;
1.357 www 8909: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8910: $deleteflag,$selfenroll,$context);
1.17 www 8911: }
8912:
1.533 banghart 8913: # ------------------------------------------------------------ Disk usage
1.535 albertel 8914: sub diskusage {
1.955 raeburn 8915: my ($udom,$uname,$directorypath,$getpropath)=@_;
8916: $directorypath =~ s/\/$//;
8917: my $listing=&reply('du2:'.&escape($directorypath).':'
8918: .&escape($getpropath).':'.&escape($uname).':'
8919: .&escape($udom),homeserver($uname,$udom));
8920: if ($listing eq 'unknown_cmd') {
8921: if ($getpropath) {
8922: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8923: }
8924: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8925: }
1.514 albertel 8926: return $listing;
1.512 banghart 8927: }
8928:
1.566 banghart 8929: sub is_locked {
1.1096 raeburn 8930: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8931: my @check;
8932: my $is_locked;
1.1093 raeburn 8933: push (@check,$file_name);
1.613 albertel 8934: my %locked = &get('file_permissions',\@check,
1.620 albertel 8935: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8936: my ($tmp)=keys(%locked);
8937: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8938:
1.566 banghart 8939: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8940: $is_locked = 'false';
8941: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8942: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8943: $is_locked = 'true';
1.1096 raeburn 8944: if (ref($which) eq 'ARRAY') {
8945: push(@{$which},$entry);
8946: } else {
8947: last;
8948: }
1.745 raeburn 8949: }
8950: }
1.566 banghart 8951: } else {
8952: $is_locked = 'false';
8953: }
1.1093 raeburn 8954: return $is_locked;
1.566 banghart 8955: }
8956:
1.759 albertel 8957: sub declutter_portfile {
8958: my ($file) = @_;
1.833 albertel 8959: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8960: return $file;
8961: }
8962:
1.559 banghart 8963: # ------------------------------------------------------------- Mark as Read Only
8964:
8965: sub mark_as_readonly {
8966: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8967: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8968: my ($tmp)=keys(%current_permissions);
8969: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8970: foreach my $file (@{$files}) {
1.759 albertel 8971: $file = &declutter_portfile($file);
1.561 banghart 8972: push(@{$current_permissions{$file}},$what);
1.559 banghart 8973: }
1.613 albertel 8974: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8975: return;
8976: }
8977:
1.572 banghart 8978: # ------------------------------------------------------------Save Selected Files
8979:
8980: sub save_selected_files {
8981: my ($user, $path, @files) = @_;
8982: my $filename = $user."savedfiles";
1.573 banghart 8983: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8984: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8985: foreach my $file (@files) {
1.620 albertel 8986: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8987: }
8988: foreach my $file (@other_files) {
1.574 banghart 8989: print (OUT $file."\n");
1.572 banghart 8990: }
1.574 banghart 8991: close (OUT);
1.572 banghart 8992: return 'ok';
8993: }
8994:
1.574 banghart 8995: sub clear_selected_files {
8996: my ($user) = @_;
8997: my $filename = $user."savedfiles";
1.1117 foxr 8998: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8999: print (OUT undef);
9000: close (OUT);
9001: return ("ok");
9002: }
9003:
1.572 banghart 9004: sub files_in_path {
9005: my ($user, $path) = @_;
9006: my $filename = $user."savedfiles";
9007: my %return_files;
1.1117 foxr 9008: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9009: while (my $line_in = <IN>) {
1.574 banghart 9010: chomp ($line_in);
9011: my @paths_and_file = split (m!/!, $line_in);
9012: my $file_part = pop (@paths_and_file);
9013: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9014: $path_part.='/';
9015: my $path_and_file = $path_part.$file_part;
9016: if ($path_part eq $path) {
9017: $return_files{$file_part}= 'selected';
9018: }
9019: }
1.574 banghart 9020: close (IN);
9021: return (\%return_files);
1.572 banghart 9022: }
9023:
9024: # called in portfolio select mode, to show files selected NOT in current directory
9025: sub files_not_in_path {
9026: my ($user, $path) = @_;
9027: my $filename = $user."savedfiles";
9028: my @return_files;
9029: my $path_part;
1.1117 foxr 9030: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9031: while (my $line = <IN>) {
1.572 banghart 9032: #ok, I know it's clunky, but I want it to work
1.800 albertel 9033: my @paths_and_file = split(m|/|, $line);
9034: my $file_part = pop(@paths_and_file);
9035: chomp($file_part);
9036: my $path_part = join('/', @paths_and_file);
1.572 banghart 9037: $path_part .= '/';
9038: my $path_and_file = $path_part.$file_part;
9039: if ($path_part ne $path) {
1.800 albertel 9040: push(@return_files, ($path_and_file));
1.572 banghart 9041: }
9042: }
1.800 albertel 9043: close(OUT);
1.574 banghart 9044: return (@return_files);
1.572 banghart 9045: }
9046:
1.745 raeburn 9047: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9048:
1.745 raeburn 9049: sub get_portfile_permissions {
9050: my ($domain,$user) = @_;
1.613 albertel 9051: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9052: my ($tmp)=keys(%current_permissions);
9053: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9054: return \%current_permissions;
9055: }
9056:
9057: #---------------------------------------------Get portfolio file access controls
9058:
1.749 raeburn 9059: sub get_access_controls {
1.745 raeburn 9060: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9061: my %access;
9062: my $real_file = $file;
9063: $file =~ s/\.meta$//;
1.745 raeburn 9064: if (defined($file)) {
1.749 raeburn 9065: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9066: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9067: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9068: }
9069: }
1.745 raeburn 9070: } else {
1.749 raeburn 9071: foreach my $key (keys(%{$current_permissions})) {
9072: if ($key =~ /\0accesscontrol$/) {
9073: if (defined($group)) {
9074: if ($key !~ m-^\Q$group\E/-) {
9075: next;
9076: }
9077: }
9078: my ($fullpath) = split(/\0/,$key);
9079: if (ref($$current_permissions{$key}) eq 'HASH') {
9080: foreach my $control (keys(%{$$current_permissions{$key}})) {
9081: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9082: }
9083: }
9084: }
9085: }
9086: }
9087: return %access;
9088: }
9089:
9090: sub modify_access_controls {
9091: my ($file_name,$changes,$domain,$user)=@_;
9092: my ($outcome,$deloutcome);
9093: my %store_permissions;
9094: my %new_values;
9095: my %new_control;
9096: my %translation;
9097: my @deletions = ();
9098: my $now = time;
9099: if (exists($$changes{'activate'})) {
9100: if (ref($$changes{'activate'}) eq 'HASH') {
9101: my @newitems = sort(keys(%{$$changes{'activate'}}));
9102: my $numnew = scalar(@newitems);
9103: for (my $i=0; $i<$numnew; $i++) {
9104: my $newkey = $newitems[$i];
9105: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9106: if ($newkey =~ /^\d+:/) {
9107: $newkey =~ s/^(\d+)/$newid/;
9108: $translation{$1} = $newid;
9109: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9110: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9111: $translation{$1} = $newid;
9112: }
1.749 raeburn 9113: $new_values{$file_name."\0".$newkey} =
9114: $$changes{'activate'}{$newitems[$i]};
9115: $new_control{$newkey} = $now;
9116: }
9117: }
9118: }
9119: my %todelete;
9120: my %changed_items;
9121: foreach my $action ('delete','update') {
9122: if (exists($$changes{$action})) {
9123: if (ref($$changes{$action}) eq 'HASH') {
9124: foreach my $key (keys(%{$$changes{$action}})) {
9125: my ($itemnum) = ($key =~ /^([^:]+):/);
9126: if ($action eq 'delete') {
9127: $todelete{$itemnum} = 1;
9128: } else {
9129: $changed_items{$itemnum} = $key;
9130: }
9131: }
1.745 raeburn 9132: }
9133: }
1.749 raeburn 9134: }
9135: # get lock on access controls for file.
9136: my $lockhash = {
9137: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9138: ':'.$env{'user.domain'},
9139: };
9140: my $tries = 0;
9141: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9142:
9143: while (($gotlock ne 'ok') && $tries <3) {
9144: $tries ++;
9145: sleep 1;
9146: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9147: }
9148: if ($gotlock eq 'ok') {
9149: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9150: my ($tmp)=keys(%curr_permissions);
9151: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9152: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9153: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9154: if (ref($curr_controls) eq 'HASH') {
9155: foreach my $control_item (keys(%{$curr_controls})) {
9156: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9157: if (defined($todelete{$itemnum})) {
9158: push(@deletions,$file_name."\0".$control_item);
9159: } else {
9160: if (defined($changed_items{$itemnum})) {
9161: $new_control{$changed_items{$itemnum}} = $now;
9162: push(@deletions,$file_name."\0".$control_item);
9163: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9164: } else {
9165: $new_control{$control_item} = $$curr_controls{$control_item};
9166: }
9167: }
1.745 raeburn 9168: }
9169: }
9170: }
1.970 raeburn 9171: my ($group);
9172: if (&is_course($domain,$user)) {
9173: ($group,my $file) = split(/\//,$file_name,2);
9174: }
1.749 raeburn 9175: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9176: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9177: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9178: # remove lock
9179: my @del_lock = ($file_name."\0".'locked_access_records');
9180: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9181: my $sqlresult =
1.970 raeburn 9182: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9183: $group);
1.749 raeburn 9184: } else {
9185: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9186: }
1.749 raeburn 9187: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9188: }
9189:
1.827 raeburn 9190: sub make_public_indefinitely {
9191: my ($requrl) = @_;
9192: my $now = time;
9193: my $action = 'activate';
9194: my $aclnum = 0;
9195: if (&is_portfolio_url($requrl)) {
9196: my (undef,$udom,$unum,$file_name,$group) =
9197: &parse_portfolio_url($requrl);
9198: my $current_perms = &get_portfile_permissions($udom,$unum);
9199: my %access_controls = &get_access_controls($current_perms,
9200: $group,$file_name);
9201: foreach my $key (keys(%{$access_controls{$file_name}})) {
9202: my ($num,$scope,$end,$start) =
9203: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9204: if ($scope eq 'public') {
9205: if ($start <= $now && $end == 0) {
9206: $action = 'none';
9207: } else {
9208: $action = 'update';
9209: $aclnum = $num;
9210: }
9211: last;
9212: }
9213: }
9214: if ($action eq 'none') {
9215: return 'ok';
9216: } else {
9217: my %changes;
9218: my $newend = 0;
9219: my $newstart = $now;
9220: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9221: $changes{$action}{$newkey} = {
9222: type => 'public',
9223: time => {
9224: start => $newstart,
9225: end => $newend,
9226: },
9227: };
9228: my ($outcome,$deloutcome,$new_values,$translation) =
9229: &modify_access_controls($file_name,\%changes,$udom,$unum);
9230: return $outcome;
9231: }
9232: } else {
9233: return 'invalid';
9234: }
9235: }
9236:
1.745 raeburn 9237: #------------------------------------------------------Get Marked as Read Only
9238:
9239: sub get_marked_as_readonly {
9240: my ($domain,$user,$what,$group) = @_;
9241: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9242: my @readonly_files;
1.629 banghart 9243: my $cmp1=$what;
9244: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9245: while (my ($file_name,$value) = each(%{$current_permissions})) {
9246: if (defined($group)) {
9247: if ($file_name !~ m-^\Q$group\E/-) {
9248: next;
9249: }
9250: }
1.561 banghart 9251: if (ref($value) eq "ARRAY"){
9252: foreach my $stored_what (@{$value}) {
1.629 banghart 9253: my $cmp2=$stored_what;
1.759 albertel 9254: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9255: $cmp2=join('',@{$stored_what});
1.745 raeburn 9256: }
1.629 banghart 9257: if ($cmp1 eq $cmp2) {
1.561 banghart 9258: push(@readonly_files, $file_name);
1.745 raeburn 9259: last;
1.563 banghart 9260: } elsif (!defined($what)) {
9261: push(@readonly_files, $file_name);
1.745 raeburn 9262: last;
1.561 banghart 9263: }
9264: }
1.745 raeburn 9265: }
1.561 banghart 9266: }
9267: return @readonly_files;
9268: }
1.577 banghart 9269: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9270:
1.577 banghart 9271: sub get_marked_as_readonly_hash {
1.745 raeburn 9272: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9273: my %readonly_files;
1.745 raeburn 9274: while (my ($file_name,$value) = each(%{$current_permissions})) {
9275: if (defined($group)) {
9276: if ($file_name !~ m-^\Q$group\E/-) {
9277: next;
9278: }
9279: }
1.577 banghart 9280: if (ref($value) eq "ARRAY"){
9281: foreach my $stored_what (@{$value}) {
1.745 raeburn 9282: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9283: foreach my $lock_descriptor(@{$stored_what}) {
9284: if ($lock_descriptor eq 'graded') {
9285: $readonly_files{$file_name} = 'graded';
9286: } elsif ($lock_descriptor eq 'handback') {
9287: $readonly_files{$file_name} = 'handback';
9288: } else {
9289: if (!exists($readonly_files{$file_name})) {
9290: $readonly_files{$file_name} = 'locked';
9291: }
9292: }
1.745 raeburn 9293: }
1.750 banghart 9294: }
1.577 banghart 9295: }
9296: }
9297: }
9298: return %readonly_files;
9299: }
1.559 banghart 9300: # ------------------------------------------------------------ Unmark as Read Only
9301:
9302: sub unmark_as_readonly {
1.629 banghart 9303: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9304: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9305: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9306: $file_name = &declutter_portfile($file_name);
1.634 albertel 9307: my $symb_crs = $what;
9308: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9309: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9310: my ($tmp)=keys(%current_permissions);
9311: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9312: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9313: foreach my $file (@readonly_files) {
1.759 albertel 9314: my $clean_file = &declutter_portfile($file);
9315: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9316: my $current_locks = $current_permissions{$file};
1.563 banghart 9317: my @new_locks;
9318: my @del_keys;
9319: if (ref($current_locks) eq "ARRAY"){
9320: foreach my $locker (@{$current_locks}) {
1.632 albertel 9321: my $compare=$locker;
1.749 raeburn 9322: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9323: $compare=join('',@{$locker});
1.746 raeburn 9324: if ($compare ne $symb_crs) {
9325: push(@new_locks, $locker);
9326: }
1.563 banghart 9327: }
9328: }
1.650 albertel 9329: if (scalar(@new_locks) > 0) {
1.563 banghart 9330: $current_permissions{$file} = \@new_locks;
9331: } else {
9332: push(@del_keys, $file);
1.613 albertel 9333: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9334: delete($current_permissions{$file});
1.563 banghart 9335: }
9336: }
1.561 banghart 9337: }
1.613 albertel 9338: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9339: return;
9340: }
1.512 banghart 9341:
1.17 www 9342: # ------------------------------------------------------------ Directory lister
9343:
9344: sub dirlist {
1.955 raeburn 9345: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9346: $uri=~s/^\///;
9347: $uri=~s/\/$//;
1.253 stredwic 9348: my ($udom, $uname);
1.955 raeburn 9349: if ($getuserdir) {
1.253 stredwic 9350: $udom = $userdomain;
9351: $uname = $username;
1.955 raeburn 9352: } else {
9353: (undef,$udom,$uname)=split(/\//,$uri);
9354: if(defined($userdomain)) {
9355: $udom = $userdomain;
9356: }
9357: if(defined($username)) {
9358: $uname = $username;
9359: }
1.253 stredwic 9360: }
1.955 raeburn 9361: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9362:
1.955 raeburn 9363: $dirRoot = $perlvar{'lonDocRoot'};
9364: if (defined($getpropath)) {
9365: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9366: $dirRoot =~ s/\/$//;
1.955 raeburn 9367: } elsif (defined($getuserdir)) {
9368: my $subdir=$uname.'__';
9369: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9370: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9371: ."/$udom/$subdir/$uname";
9372: } elsif (defined($alternateRoot)) {
9373: $dirRoot = $alternateRoot;
1.751 banghart 9374: }
1.253 stredwic 9375:
9376: if($udom) {
9377: if($uname) {
1.1135 raeburn 9378: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9379: if ($uhome eq 'no_host') {
9380: return ([],'no_host');
9381: }
1.955 raeburn 9382: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9383: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9384: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9385: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9386: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9387: } else {
9388: @listing_results = map { &unescape($_); } split(/:/,$listing);
9389: }
1.605 matthew 9390: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9391: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9392: @listing_results = split(/:/,$listing);
9393: } else {
9394: @listing_results = map { &unescape($_); } split(/:/,$listing);
9395: }
1.1135 raeburn 9396: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9397: ($listing eq 'rejected') || ($listing eq 'refused') ||
9398: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9399: return ([],$listing);
9400: } else {
9401: return (\@listing_results);
1.1135 raeburn 9402: }
1.955 raeburn 9403: } elsif(!$alternateRoot) {
1.1136 raeburn 9404: my (%allusers,%listerror);
1.841 albertel 9405: my %servers = &get_servers($udom,'library');
1.955 raeburn 9406: foreach my $tryserver (keys(%servers)) {
9407: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9408: &escape($udom),$tryserver);
9409: if ($listing eq 'unknown_cmd') {
9410: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9411: $udom, $tryserver);
9412: } else {
9413: @listing_results = map { &unescape($_); } split(/:/,$listing);
9414: }
1.841 albertel 9415: if ($listing eq 'unknown_cmd') {
9416: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9417: $udom, $tryserver);
9418: @listing_results = split(/:/,$listing);
9419: } else {
9420: @listing_results =
9421: map { &unescape($_); } split(/:/,$listing);
9422: }
1.1136 raeburn 9423: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9424: ($listing eq 'rejected') || ($listing eq 'refused') ||
9425: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9426: $listerror{$tryserver} = $listing;
9427: } else {
1.841 albertel 9428: foreach my $line (@listing_results) {
9429: my ($entry) = split(/&/,$line,2);
9430: $allusers{$entry} = 1;
9431: }
9432: }
1.253 stredwic 9433: }
1.1136 raeburn 9434: my @alluserslist=();
1.800 albertel 9435: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9436: push(@alluserslist,$user.'&user');
1.253 stredwic 9437: }
1.1136 raeburn 9438: return (\@alluserslist);
1.253 stredwic 9439: } else {
1.1136 raeburn 9440: return ([],'missing username');
1.253 stredwic 9441: }
1.955 raeburn 9442: } elsif(!defined($getpropath)) {
1.1136 raeburn 9443: my $path = $perlvar{'lonDocRoot'}.'/res/';
9444: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9445: return (\@all_domains);
1.955 raeburn 9446: } else {
1.1136 raeburn 9447: return ([],'missing domain');
1.275 stredwic 9448: }
9449: }
9450:
9451: # --------------------------------------------- GetFileTimestamp
9452: # This function utilizes dirlist and returns the date stamp for
9453: # when it was last modified. It will also return an error of -1
9454: # if an error occurs
9455:
9456: sub GetFileTimestamp {
1.955 raeburn 9457: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9458: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9459: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9460: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9461: undef,$getuserdir);
9462: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9463: return -1;
9464: }
9465: if (ref($fileref) eq 'ARRAY') {
9466: my @stats = split('&',$fileref->[0]);
1.375 matthew 9467: # @stats contains first the filename, then the stat output
9468: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9469: } else {
9470: return -1;
1.253 stredwic 9471: }
1.26 www 9472: }
9473:
1.712 albertel 9474: sub stat_file {
9475: my ($uri) = @_;
1.787 albertel 9476: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9477:
1.955 raeburn 9478: my ($udom,$uname,$file);
1.712 albertel 9479: if ($uri =~ m-^/(uploaded|editupload)/-) {
9480: ($udom,$uname,$file) =
1.811 albertel 9481: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9482: $file = 'userfiles/'.$file;
9483: }
9484: if ($uri =~ m-^/res/-) {
9485: ($udom,$uname) =
1.807 albertel 9486: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9487: $file = $uri;
9488: }
9489:
9490: if (!$udom || !$uname || !$file) {
9491: # unable to handle the uri
9492: return ();
9493: }
1.956 raeburn 9494: my $getpropath;
9495: if ($file =~ /^userfiles\//) {
9496: $getpropath = 1;
9497: }
1.1136 raeburn 9498: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9499: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9500: return ();
9501: } else {
9502: if (ref($listref) eq 'ARRAY') {
9503: my @stats = split('&',$listref->[0]);
9504: shift(@stats); #filename is first
9505: return @stats;
9506: }
1.712 albertel 9507: }
9508: return ();
9509: }
9510:
1.26 www 9511: # -------------------------------------------------------- Value of a Condition
9512:
1.713 albertel 9513: # gets the value of a specific preevaluated condition
9514: # stored in the string $env{user.state.<cid>}
9515: # or looks up a condition reference in the bighash and if if hasn't
9516: # already been evaluated recurses into docondval to get the value of
9517: # the condition, then memoizing it to
9518: # $env{user.state.<cid>.<condition>}
1.40 www 9519: sub directcondval {
9520: my $number=shift;
1.620 albertel 9521: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9522: &Apache::lonuserstate::evalstate();
9523: }
1.713 albertel 9524: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9525: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9526: } elsif ($number =~ /^_/) {
9527: my $sub_condition;
9528: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9529: &GDBM_READER(),0640)) {
9530: $sub_condition=$bighash{'conditions'.$number};
9531: untie(%bighash);
9532: }
9533: my $value = &docondval($sub_condition);
1.949 raeburn 9534: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9535: return $value;
9536: }
1.620 albertel 9537: if ($env{'user.state.'.$env{'request.course.id'}}) {
9538: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9539: } else {
9540: return 2;
9541: }
9542: }
9543:
1.713 albertel 9544: # get the collection of conditions for this resource
1.26 www 9545: sub condval {
9546: my $condidx=shift;
1.54 www 9547: my $allpathcond='';
1.713 albertel 9548: foreach my $cond (split(/\|/,$condidx)) {
9549: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9550: $allpathcond.=
9551: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9552: }
1.191 harris41 9553: }
1.54 www 9554: $allpathcond=~s/\|$//;
1.713 albertel 9555: return &docondval($allpathcond);
9556: }
9557:
9558: #evaluates an expression of conditions
9559: sub docondval {
9560: my ($allpathcond) = @_;
9561: my $result=0;
9562: if ($env{'request.course.id'}
9563: && defined($allpathcond)) {
9564: my $operand='|';
9565: my @stack;
9566: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9567: if ($chunk eq '(') {
9568: push @stack,($operand,$result);
9569: } elsif ($chunk eq ')') {
9570: my $before=pop @stack;
9571: if (pop @stack eq '&') {
9572: $result=$result>$before?$before:$result;
9573: } else {
9574: $result=$result>$before?$result:$before;
9575: }
9576: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9577: $operand=$chunk;
9578: } else {
9579: my $new=directcondval($chunk);
9580: if ($operand eq '&') {
9581: $result=$result>$new?$new:$result;
9582: } else {
9583: $result=$result>$new?$result:$new;
9584: }
9585: }
9586: }
1.26 www 9587: }
9588: return $result;
1.421 albertel 9589: }
9590:
9591: # ---------------------------------------------------- Devalidate courseresdata
9592:
9593: sub devalidatecourseresdata {
9594: my ($coursenum,$coursedomain)=@_;
9595: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9596: &devalidate_cache_new('courseres',$hashid);
1.28 www 9597: }
9598:
1.763 www 9599:
1.200 www 9600: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9601: #
9602: # Parameters:
9603: # $coursenum - Number of the course.
9604: # $coursedomain - Domain at which the course was created.
9605: # Returns:
9606: # A hash of the course parameters along (I think) with timestamps
9607: # and version info.
1.877 foxr 9608:
1.624 albertel 9609: sub get_courseresdata {
9610: my ($coursenum,$coursedomain)=@_;
1.200 www 9611: my $coursehom=&homeserver($coursenum,$coursedomain);
9612: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9613: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9614: my %dumpreply;
1.417 albertel 9615: unless (defined($cached)) {
1.624 albertel 9616: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9617: $result=\%dumpreply;
1.251 albertel 9618: my ($tmp) = keys(%dumpreply);
9619: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9620: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9621: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9622: return $tmp;
1.416 albertel 9623: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9624: $result=undef;
1.599 albertel 9625: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9626: }
9627: }
1.624 albertel 9628: return $result;
9629: }
9630:
1.633 albertel 9631: sub devalidateuserresdata {
9632: my ($uname,$udom)=@_;
9633: my $hashid="$udom:$uname";
9634: &devalidate_cache_new('userres',$hashid);
9635: }
9636:
1.624 albertel 9637: sub get_userresdata {
9638: my ($uname,$udom)=@_;
9639: #most student don\'t have any data set, check if there is some data
9640: if (&EXT_cache_status($udom,$uname)) { return undef; }
9641:
9642: my $hashid="$udom:$uname";
9643: my ($result,$cached)=&is_cached_new('userres',$hashid);
9644: if (!defined($cached)) {
9645: my %resourcedata=&dump('resourcedata',$udom,$uname);
9646: $result=\%resourcedata;
9647: &do_cache_new('userres',$hashid,$result,600);
9648: }
9649: my ($tmp)=keys(%$result);
9650: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9651: return $result;
9652: }
9653: #error 2 occurs when the .db doesn't exist
9654: if ($tmp!~/error: 2 /) {
1.672 albertel 9655: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9656: " Trying to get resource data for ".
9657: $uname." at ".$udom.": ".
9658: $tmp."</font>");
9659: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9660: #&EXT_cache_set($udom,$uname);
9661: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9662: undef($tmp); # not really an error so don't send it back
1.624 albertel 9663: }
9664: return $tmp;
9665: }
1.879 foxr 9666: #----------------------------------------------- resdata - return resource data
9667: # Purpose:
9668: # Return resource data for either users or for a course.
9669: # Parameters:
9670: # $name - Course/user name.
9671: # $domain - Name of the domain the user/course is registered on.
9672: # $type - Type of thing $name is (must be 'course' or 'user'
9673: # @which - Array of names of resources desired.
9674: # Returns:
9675: # The value of the first reasource in @which that is found in the
9676: # resource hash.
9677: # Exceptional Conditions:
9678: # If the $type passed in is not valid (not the string 'course' or
9679: # 'user', an undefined reference is returned.
9680: # If none of the resources are found, an undef is returned
1.624 albertel 9681: sub resdata {
9682: my ($name,$domain,$type,@which)=@_;
9683: my $result;
9684: if ($type eq 'course') {
9685: $result=&get_courseresdata($name,$domain);
9686: } elsif ($type eq 'user') {
9687: $result=&get_userresdata($name,$domain);
9688: }
9689: if (!ref($result)) { return $result; }
1.251 albertel 9690: foreach my $item (@which) {
1.927 albertel 9691: if (defined($result->{$item->[0]})) {
9692: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9693: }
1.250 albertel 9694: }
1.291 albertel 9695: return undef;
1.200 www 9696: }
9697:
1.1236 raeburn 9698: sub get_numsuppfiles {
9699: my ($cnum,$cdom,$ignorecache)=@_;
9700: my $hashid=$cnum.':'.$cdom;
9701: my ($suppcount,$cached);
9702: unless ($ignorecache) {
9703: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9704: }
9705: unless (defined($cached)) {
9706: my $chome=&homeserver($cnum,$cdom);
9707: unless ($chome eq 'no_host') {
9708: ($suppcount,my $errors) = (0,0);
9709: my $suppmap = 'supplemental.sequence';
9710: ($suppcount,$errors) =
9711: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9712: }
9713: &do_cache_new('suppcount',$hashid,$suppcount,600);
9714: }
9715: return $suppcount;
9716: }
9717:
1.379 matthew 9718: #
9719: # EXT resource caching routines
9720: #
9721:
9722: sub clear_EXT_cache_status {
1.383 albertel 9723: &delenv('cache.EXT.');
1.379 matthew 9724: }
9725:
9726: sub EXT_cache_status {
9727: my ($target_domain,$target_user) = @_;
1.383 albertel 9728: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9729: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9730: # We know already the user has no data
9731: return 1;
9732: } else {
9733: return 0;
9734: }
9735: }
9736:
9737: sub EXT_cache_set {
9738: my ($target_domain,$target_user) = @_;
1.383 albertel 9739: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9740: #&appenv({$cachename => time});
1.379 matthew 9741: }
9742:
1.28 www 9743: # --------------------------------------------------------- Value of a Variable
1.58 www 9744: sub EXT {
1.715 albertel 9745:
1.1228 raeburn 9746: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9747: unless ($varname) { return ''; }
1.218 albertel 9748: #get real user name/domain, courseid and symb
9749: my $courseid;
1.359 albertel 9750: my $publicuser;
1.427 www 9751: if ($symbparm) {
9752: $symbparm=&get_symb_from_alias($symbparm);
9753: }
1.218 albertel 9754: if (!($uname && $udom)) {
1.790 albertel 9755: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9756: if (!$symbparm) { $symbparm=$cursymb; }
9757: } else {
1.620 albertel 9758: $courseid=$env{'request.course.id'};
1.218 albertel 9759: }
1.48 www 9760: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9761: my $rest;
1.320 albertel 9762: if (defined($therest[0])) {
1.48 www 9763: $rest=join('.',@therest);
9764: } else {
9765: $rest='';
9766: }
1.320 albertel 9767:
1.57 www 9768: my $qualifierrest=$qualifier;
9769: if ($rest) { $qualifierrest.='.'.$rest; }
9770: my $spacequalifierrest=$space;
9771: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9772: if ($realm eq 'user') {
1.48 www 9773: # --------------------------------------------------------------- user.resource
9774: if ($space eq 'resource') {
1.651 albertel 9775: if ( (defined($Apache::lonhomework::parsing_a_problem)
9776: || defined($Apache::lonhomework::parsing_a_task))
9777: &&
1.744 albertel 9778: ($symbparm eq &symbread()) ) {
9779: # if we are in the middle of processing the resource the
9780: # get the value we are planning on committing
9781: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9782: return $Apache::lonhomework::results{$qualifierrest};
9783: } else {
9784: return $Apache::lonhomework::history{$qualifierrest};
9785: }
1.335 albertel 9786: } else {
1.359 albertel 9787: my %restored;
1.620 albertel 9788: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9789: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9790: } else {
9791: %restored=&restore($symbparm,$courseid,$udom,$uname);
9792: }
1.335 albertel 9793: return $restored{$qualifierrest};
9794: }
1.48 www 9795: # ----------------------------------------------------------------- user.access
9796: } elsif ($space eq 'access') {
1.218 albertel 9797: # FIXME - not supporting calls for a specific user
1.48 www 9798: return &allowed($qualifier,$rest);
9799: # ------------------------------------------ user.preferences, user.environment
9800: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9801: if (($uname eq $env{'user.name'}) &&
9802: ($udom eq $env{'user.domain'})) {
9803: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9804: } else {
1.359 albertel 9805: my %returnhash;
9806: if (!$publicuser) {
9807: %returnhash=&userenvironment($udom,$uname,
9808: $qualifierrest);
9809: }
1.218 albertel 9810: return $returnhash{$qualifierrest};
9811: }
1.48 www 9812: # ----------------------------------------------------------------- user.course
9813: } elsif ($space eq 'course') {
1.218 albertel 9814: # FIXME - not supporting calls for a specific user
1.620 albertel 9815: return $env{join('.',('request.course',$qualifier))};
1.48 www 9816: # ------------------------------------------------------------------- user.role
9817: } elsif ($space eq 'role') {
1.218 albertel 9818: # FIXME - not supporting calls for a specific user
1.620 albertel 9819: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9820: if ($qualifier eq 'value') {
9821: return $role;
9822: } elsif ($qualifier eq 'extent') {
9823: return $where;
9824: }
9825: # ----------------------------------------------------------------- user.domain
9826: } elsif ($space eq 'domain') {
1.218 albertel 9827: return $udom;
1.48 www 9828: # ------------------------------------------------------------------- user.name
9829: } elsif ($space eq 'name') {
1.218 albertel 9830: return $uname;
1.48 www 9831: # ---------------------------------------------------- Any other user namespace
1.29 www 9832: } else {
1.359 albertel 9833: my %reply;
9834: if (!$publicuser) {
9835: %reply=&get($space,[$qualifierrest],$udom,$uname);
9836: }
9837: return $reply{$qualifierrest};
1.48 www 9838: }
1.236 www 9839: } elsif ($realm eq 'query') {
9840: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9841: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9842: [$spacequalifierrest]);
1.620 albertel 9843: return $env{'form.'.$spacequalifierrest};
1.236 www 9844: } elsif ($realm eq 'request') {
1.48 www 9845: # ------------------------------------------------------------- request.browser
9846: if ($space eq 'browser') {
1.1145 bisitz 9847: return $env{'browser.'.$qualifier};
1.57 www 9848: # ------------------------------------------------------------ request.filename
9849: } else {
1.620 albertel 9850: return $env{'request.'.$spacequalifierrest};
1.29 www 9851: }
1.28 www 9852: } elsif ($realm eq 'course') {
1.48 www 9853: # ---------------------------------------------------------- course.description
1.620 albertel 9854: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9855: } elsif ($realm eq 'resource') {
1.165 www 9856:
1.620 albertel 9857: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9858: if (!$symbparm) { $symbparm=&symbread(); }
9859: }
1.693 albertel 9860:
1.1232 raeburn 9861: if ($qualifier eq '') {
9862: if ($space eq 'title') {
9863: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9864: return &gettitle($symbparm);
9865: }
1.693 albertel 9866:
1.1232 raeburn 9867: if ($space eq 'map') {
9868: my ($map) = &decode_symb($symbparm);
9869: return &symbread($map);
9870: }
9871: if ($space eq 'maptitle') {
9872: my ($map) = &decode_symb($symbparm);
9873: return &gettitle($map);
9874: }
9875: if ($space eq 'filename') {
9876: if ($symbparm) {
9877: return &clutter((&decode_symb($symbparm))[2]);
9878: }
9879: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9880: }
1.1232 raeburn 9881:
1.1233 raeburn 9882: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9883: if ($space eq 'visibleparts') {
9884: my $navmap = Apache::lonnavmaps::navmap->new();
9885: my $item;
9886: if (ref($navmap)) {
9887: my $res = $navmap->getBySymb($symbparm);
9888: my $parts = $res->parts();
9889: if (ref($parts) eq 'ARRAY') {
9890: $item = join(',',@{$parts});
9891: }
9892: undef($navmap);
1.1232 raeburn 9893: }
1.1233 raeburn 9894: return $item;
1.1232 raeburn 9895: }
9896: }
9897: }
1.693 albertel 9898:
9899: my ($section, $group, @groups);
1.593 albertel 9900: my ($courselevelm,$courselevel);
1.1228 raeburn 9901: if (($courseid eq '') && ($cid)) {
9902: $courseid = $cid;
9903: }
9904: if (($symbparm && $courseid) &&
9905: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9906:
1.218 albertel 9907: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9908:
1.60 www 9909: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9910: my $symbp=$symbparm;
1.735 albertel 9911: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9912:
9913: my $symbparm=$symbp.'.'.$spacequalifierrest;
9914: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9915:
1.620 albertel 9916: if (($env{'user.name'} eq $uname) &&
9917: ($env{'user.domain'} eq $udom)) {
9918: $section=$env{'request.course.sec'};
1.733 raeburn 9919: @groups = split(/:/,$env{'request.course.groups'});
9920: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9921: } else {
1.539 albertel 9922: if (! defined($usection)) {
1.551 albertel 9923: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9924: } else {
9925: $section = $usection;
9926: }
1.733 raeburn 9927: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9928: }
9929:
9930: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9931: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9932: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9933:
1.593 albertel 9934: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9935: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9936: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9937:
1.60 www 9938: # ----------------------------------------------------------- first, check user
1.624 albertel 9939:
9940: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9941: ([$courselevelr,'resource'],
9942: [$courselevelm,'map' ],
9943: [$courselevel, 'course' ]));
1.931 albertel 9944: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9945:
1.594 albertel 9946: # ------------------------------------------------ second, check some of course
1.684 raeburn 9947: my $coursereply;
1.691 raeburn 9948: if (@groups > 0) {
9949: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9950: $mapparm,$spacequalifierrest);
1.927 albertel 9951: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9952: }
1.96 www 9953:
1.684 raeburn 9954: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9955: $env{'course.'.$courseid.'.domain'},
9956: 'course',
9957: ([$seclevelr, 'resource'],
9958: [$seclevelm, 'map' ],
9959: [$seclevel, 'course' ],
9960: [$courselevelr,'resource']));
9961: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9962:
1.60 www 9963: # ------------------------------------------------------ third, check map parms
1.218 albertel 9964: my %parmhash=();
9965: my $thisparm='';
9966: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9967: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9968: &GDBM_READER(),0640)) {
1.218 albertel 9969: $thisparm=$parmhash{$symbparm};
9970: untie(%parmhash);
9971: }
1.927 albertel 9972: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9973: }
1.594 albertel 9974: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9975:
1.218 albertel 9976: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9977: my $filename;
9978: if (!$symbparm) { $symbparm=&symbread(); }
9979: if ($symbparm) {
1.409 www 9980: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9981: } else {
1.620 albertel 9982: $filename=$env{'request.filename'};
1.282 albertel 9983: }
9984: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9985: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9986: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9987: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9988:
1.927 albertel 9989: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9990: if ($symbparm && defined($courseid) &&
1.620 albertel 9991: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9992: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9993: $env{'course.'.$courseid.'.domain'},
9994: 'course',
1.927 albertel 9995: ([$courselevelm,'map' ],
9996: [$courselevel, 'course']));
9997: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9998: }
1.145 www 9999: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10000: unless ($space eq '0') {
1.336 albertel 10001: my @parts=split(/_/,$space);
10002: my $id=pop(@parts);
10003: my $part=join('_',@parts);
10004: if ($part eq '') { $part='0'; }
1.927 albertel 10005: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10006: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10007: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10008: }
1.395 albertel 10009: if ($recurse) { return undef; }
10010: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10011: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10012: # ---------------------------------------------------- Any other user namespace
10013: } elsif ($realm eq 'environment') {
10014: # ----------------------------------------------------------------- environment
1.620 albertel 10015: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10016: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10017: } else {
1.770 albertel 10018: if ($uname eq 'anonymous' && $udom eq '') {
10019: return '';
10020: }
1.219 albertel 10021: my %returnhash=&userenvironment($udom,$uname,
10022: $spacequalifierrest);
10023: return $returnhash{$spacequalifierrest};
10024: }
1.28 www 10025: } elsif ($realm eq 'system') {
1.48 www 10026: # ----------------------------------------------------------------- system.time
10027: if ($space eq 'time') {
10028: return time;
10029: }
1.696 albertel 10030: } elsif ($realm eq 'server') {
10031: # ----------------------------------------------------------------- system.time
10032: if ($space eq 'name') {
10033: return $ENV{'SERVER_NAME'};
10034: }
1.28 www 10035: }
1.48 www 10036: return '';
1.61 www 10037: }
10038:
1.927 albertel 10039: sub get_reply {
10040: my ($reply_value) = @_;
1.940 raeburn 10041: if (ref($reply_value) eq 'ARRAY') {
10042: if (wantarray) {
10043: return @$reply_value;
10044: }
10045: return $reply_value->[0];
10046: } else {
10047: return $reply_value;
1.927 albertel 10048: }
10049: }
10050:
1.691 raeburn 10051: sub check_group_parms {
10052: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10053: my @groupitems = ();
10054: my $resultitem;
1.927 albertel 10055: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10056: foreach my $group (@{$groups}) {
10057: foreach my $level (@levels) {
1.927 albertel 10058: my $item = $courseid.'.['.$group.'].'.$level->[0];
10059: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10060: }
10061: }
10062: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10063: $env{'course.'.$courseid.'.domain'},
10064: 'course',@groupitems);
10065: return $coursereply;
10066: }
10067:
10068: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10069: my ($courseid,@groups) = @_;
10070: @groups = sort(@groups);
1.691 raeburn 10071: return @groups;
10072: }
10073:
1.395 albertel 10074: sub packages_tab_default {
10075: my ($uri,$varname)=@_;
10076: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10077:
10078: my (@extension,@specifics,$do_default);
10079: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10080: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10081: if ($pack_type eq 'default') {
10082: $do_default=1;
10083: } elsif ($pack_type eq 'extension') {
10084: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10085: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10086: # only look at packages defaults for packages that this id is
1.738 albertel 10087: push(@specifics,[$package,$pack_type,$pack_part]);
10088: }
10089: }
10090: # first look for a package that matches the requested part id
10091: foreach my $package (@specifics) {
10092: my (undef,$pack_type,$pack_part)=@{$package};
10093: next if ($pack_part ne $part);
10094: if (defined($packagetab{"$pack_type&$name&default"})) {
10095: return $packagetab{"$pack_type&$name&default"};
10096: }
10097: }
10098: # look for any possible matching non extension_ package
10099: foreach my $package (@specifics) {
10100: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10101: if (defined($packagetab{"$pack_type&$name&default"})) {
10102: return $packagetab{"$pack_type&$name&default"};
10103: }
1.585 albertel 10104: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10105: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10106: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10107: }
10108: }
1.738 albertel 10109: # look for any posible extension_ match
10110: foreach my $package (@extension) {
10111: my ($package,$pack_type)=@{$package};
10112: if (defined($packagetab{"$pack_type&$name&default"})) {
10113: return $packagetab{"$pack_type&$name&default"};
10114: }
10115: if (defined($packagetab{$package."&$name&default"})) {
10116: return $packagetab{$package."&$name&default"};
10117: }
10118: }
10119: # look for a global default setting
10120: if ($do_default && defined($packagetab{"default&$name&default"})) {
10121: return $packagetab{"default&$name&default"};
10122: }
1.395 albertel 10123: return undef;
10124: }
10125:
1.334 albertel 10126: sub add_prefix_and_part {
10127: my ($prefix,$part)=@_;
10128: my $keyroot;
10129: if (defined($prefix) && $prefix !~ /^__/) {
10130: # prefix that has a part already
10131: $keyroot=$prefix;
10132: } elsif (defined($prefix)) {
10133: # prefix that is missing a part
10134: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10135: } else {
10136: # no prefix at all
10137: if (defined($part)) { $keyroot='_'.$part; }
10138: }
10139: return $keyroot;
10140: }
10141:
1.71 www 10142: # ---------------------------------------------------------------- Get metadata
10143:
1.599 albertel 10144: my %metaentry;
1.1070 www 10145: my %importedpartids;
1.71 www 10146: sub metadata {
1.176 www 10147: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10148: $uri=&declutter($uri);
1.288 albertel 10149: # if it is a non metadata possible uri return quickly
1.529 albertel 10150: if (($uri eq '') ||
10151: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10152: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10153: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10154: return undef;
10155: }
1.1140 www 10156: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10157: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10158: return undef;
1.288 albertel 10159: }
1.73 www 10160: my $filename=$uri;
10161: $uri=~s/\.meta$//;
1.172 www 10162: #
10163: # Is the metadata already cached?
1.177 www 10164: # Look at timestamp of caching
1.172 www 10165: # Everything is cached by the main uri, libraries are never directly cached
10166: #
1.428 albertel 10167: if (!defined($liburi)) {
1.599 albertel 10168: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10169: if (defined($cached)) { return $result->{':'.$what}; }
10170: }
10171: {
1.1069 www 10172: # Imported parts would go here
1.1070 www 10173: my %importedids=();
10174: my @origfileimportpartids=();
1.1069 www 10175: my $importedparts=0;
1.172 www 10176: #
10177: # Is this a recursive call for a library?
10178: #
1.599 albertel 10179: # if (! exists($metacache{$uri})) {
10180: # $metacache{$uri}={};
10181: # }
1.924 albertel 10182: my $cachetime = 60*60;
1.171 www 10183: if ($liburi) {
10184: $liburi=&declutter($liburi);
10185: $filename=$liburi;
1.401 bowersj2 10186: } else {
1.599 albertel 10187: &devalidate_cache_new('meta',$uri);
10188: undef(%metaentry);
1.401 bowersj2 10189: }
1.140 www 10190: my %metathesekeys=();
1.73 www 10191: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10192: my $metastring;
1.1140 www 10193: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10194: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10195: $metastring =
1.929 albertel 10196: &Apache::lonnet::ssi_body($which,
1.924 albertel 10197: ('grade_target' => 'meta'));
10198: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10199: } elsif (($uri !~ m -^(editupload)/-) &&
10200: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10201: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10202: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10203: $metastring=&getfile($file);
1.489 albertel 10204: }
1.208 albertel 10205: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10206: my $token;
1.140 www 10207: undef %metathesekeys;
1.71 www 10208: while ($token=$parser->get_token) {
1.339 albertel 10209: if ($token->[0] eq 'S') {
10210: if (defined($token->[2]->{'package'})) {
1.172 www 10211: #
10212: # This is a package - get package info
10213: #
1.339 albertel 10214: my $package=$token->[2]->{'package'};
10215: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10216: if (defined($token->[2]->{'id'})) {
10217: $keyroot.='_'.$token->[2]->{'id'};
10218: }
1.599 albertel 10219: if ($metaentry{':packages'}) {
10220: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10221: } else {
1.599 albertel 10222: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10223: }
1.736 albertel 10224: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10225: my $part=$keyroot;
10226: $part=~s/^\_//;
1.736 albertel 10227: if ($pack_entry=~/^\Q$package\E\&/ ||
10228: $pack_entry=~/^\Q$package\E_0\&/) {
10229: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10230: # ignore package.tab specified default values
10231: # here &package_tab_default() will fetch those
10232: if ($subp eq 'default') { next; }
1.736 albertel 10233: my $value=$packagetab{$pack_entry};
1.432 albertel 10234: my $unikey;
10235: if ($pack =~ /_0$/) {
10236: $unikey='parameter_0_'.$name;
10237: $part=0;
10238: } else {
10239: $unikey='parameter'.$keyroot.'_'.$name;
10240: }
1.339 albertel 10241: if ($subp eq 'display') {
10242: $value.=' [Part: '.$part.']';
10243: }
1.599 albertel 10244: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10245: $metathesekeys{$unikey}=1;
1.599 albertel 10246: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10247: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10248: }
1.599 albertel 10249: if (defined($metaentry{':'.$unikey.'.default'})) {
10250: $metaentry{':'.$unikey}=
10251: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10252: }
1.339 albertel 10253: }
10254: }
10255: } else {
1.172 www 10256: #
10257: # This is not a package - some other kind of start tag
1.339 albertel 10258: #
10259: my $entry=$token->[1];
1.1068 www 10260: my $unikey='';
1.175 www 10261:
1.339 albertel 10262: if ($entry eq 'import') {
1.175 www 10263: #
10264: # Importing a library here
1.339 albertel 10265: #
1.1067 www 10266: my $location=$parser->get_text('/import');
10267: my $dir=$filename;
10268: $dir=~s|[^/]*$||;
10269: $location=&filelocation($dir,$location);
1.1069 www 10270:
1.1068 www 10271: my $importmode=$token->[2]->{'importmode'};
10272: if ($importmode eq 'problem') {
1.1069 www 10273: # Import as problem/response
1.1068 www 10274: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10275: } elsif ($importmode eq 'part') {
10276: # Import as part(s)
1.1069 www 10277: $importedparts=1;
10278: # We need to get the original file and the imported file to get the part order correct
10279: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10280: # Load and inspect original file
1.1070 www 10281: if ($#origfileimportpartids<0) {
10282: undef(%importedpartids);
10283: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10284: my $origfile=&getfile($origfilelocation);
10285: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10286: }
10287:
1.1069 www 10288: # Load and inspect imported file
10289: my $impfile=&getfile($location);
10290: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10291: if ($#impfilepartids>=0) {
10292: # This problem had parts
1.1070 www 10293: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10294: } else {
10295: # Importing by turning a single problem into a problem part
10296: # It gets the import-tags ID as part-ID
10297: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10298: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10299: }
1.1068 www 10300: } else {
10301: # Normal import
10302: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10303: if (defined($token->[2]->{'id'})) {
10304: $unikey.='_'.$token->[2]->{'id'};
10305: }
1.1067 www 10306: }
10307:
1.339 albertel 10308: if ($depthcount<20) {
1.736 albertel 10309: my $metadata =
10310: &metadata($uri,'keys', $location,$unikey,
10311: $depthcount+1);
10312: foreach my $meta (split(',',$metadata)) {
10313: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10314: $metathesekeys{$meta}=1;
1.339 albertel 10315: }
1.1068 www 10316:
10317: }
1.1067 www 10318: } else {
10319: #
10320: # Not importing, some other kind of non-package, non-library start tag
10321: #
10322: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10323: if (defined($token->[2]->{'id'})) {
10324: $unikey.='_'.$token->[2]->{'id'};
10325: }
1.339 albertel 10326: if (defined($token->[2]->{'name'})) {
10327: $unikey.='_'.$token->[2]->{'name'};
10328: }
10329: $metathesekeys{$unikey}=1;
1.736 albertel 10330: foreach my $param (@{$token->[3]}) {
10331: $metaentry{':'.$unikey.'.'.$param} =
10332: $token->[2]->{$param};
1.339 albertel 10333: }
10334: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10335: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10336: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10337: # only ws inside the tag, and not in default, so use default
10338: # as value
1.599 albertel 10339: $metaentry{':'.$unikey}=$default;
1.908 albertel 10340: } elsif ( $internaltext =~ /\S/ ) {
10341: # something interesting inside the tag
10342: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10343: } else {
1.908 albertel 10344: # no interesting values, don't set a default
1.339 albertel 10345: }
1.172 www 10346: # end of not-a-package not-a-library import
1.339 albertel 10347: }
1.172 www 10348: # end of not-a-package start tag
1.339 albertel 10349: }
1.172 www 10350: # the next is the end of "start tag"
1.339 albertel 10351: }
10352: }
1.483 albertel 10353: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10354: $extension = lc($extension);
10355: if ($extension eq 'htm') { $extension='html'; }
10356:
1.737 albertel 10357: foreach my $key (keys(%packagetab)) {
1.483 albertel 10358: #no specific packages #how's our extension
10359: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10360: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10361: \%metathesekeys);
10362: }
1.883 albertel 10363:
10364: if (!exists($metaentry{':packages'})
10365: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10366: foreach my $key (keys(%packagetab)) {
1.483 albertel 10367: #no specific packages well let's get default then
10368: if ($key!~/^default&/) { next; }
1.488 albertel 10369: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10370: \%metathesekeys);
10371: }
10372: }
1.338 www 10373: # are there custom rights to evaluate
1.599 albertel 10374: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10375:
1.338 www 10376: #
10377: # Importing a rights file here
1.339 albertel 10378: #
10379: unless ($depthcount) {
1.599 albertel 10380: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10381: my $dir=$filename;
10382: $dir=~s|[^/]*$||;
10383: $location=&filelocation($dir,$location);
1.736 albertel 10384: my $rights_metadata =
10385: &metadata($uri,'keys',$location,'_rights',
10386: $depthcount+1);
10387: foreach my $rights (split(',',$rights_metadata)) {
10388: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10389: $metathesekeys{$rights}=1;
1.339 albertel 10390: }
10391: }
10392: }
1.737 albertel 10393: # uniqifiy package listing
10394: my %seen;
10395: my @uniq_packages =
10396: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10397: $metaentry{':packages'} = join(',',@uniq_packages);
10398:
1.1070 www 10399: if ($importedparts) {
10400: # We had imported parts and need to rebuild partorder
10401: $metaentry{':partorder'}='';
10402: $metathesekeys{'partorder'}=1;
10403: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10404: if ($origfileimportpartids[$index] eq 'part') {
10405: # original part, part of the problem
10406: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10407: } else {
10408: # we have imported parts at this position
10409: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10410: }
10411: }
10412: $metaentry{':partorder'}=~s/^\,//;
10413: }
10414:
1.737 albertel 10415: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10416: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10417: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10418: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10419: # this is the end of "was not already recently cached
1.71 www 10420: }
1.599 albertel 10421: return $metaentry{':'.$what};
1.261 albertel 10422: }
10423:
1.488 albertel 10424: sub metadata_create_package_def {
1.483 albertel 10425: my ($uri,$key,$package,$metathesekeys)=@_;
10426: my ($pack,$name,$subp)=split(/\&/,$key);
10427: if ($subp eq 'default') { next; }
10428:
1.599 albertel 10429: if (defined($metaentry{':packages'})) {
10430: $metaentry{':packages'}.=','.$package;
1.483 albertel 10431: } else {
1.599 albertel 10432: $metaentry{':packages'}=$package;
1.483 albertel 10433: }
10434: my $value=$packagetab{$key};
10435: my $unikey;
10436: $unikey='parameter_0_'.$name;
1.599 albertel 10437: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10438: $$metathesekeys{$unikey}=1;
1.599 albertel 10439: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10440: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10441: }
1.599 albertel 10442: if (defined($metaentry{':'.$unikey.'.default'})) {
10443: $metaentry{':'.$unikey}=
10444: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10445: }
10446: }
10447:
1.261 albertel 10448: sub metadata_generate_part0 {
10449: my ($metadata,$metacache,$uri) = @_;
10450: my %allnames;
1.737 albertel 10451: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10452: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10453: my $part=$$metacache{':'.$metakey.'.part'};
10454: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10455: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10456: $allnames{$name}=$part;
10457: }
10458: }
10459: }
10460: foreach my $name (keys(%allnames)) {
10461: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10462: my $key=":parameter_0_$name";
1.261 albertel 10463: $$metacache{"$key.part"}='0';
10464: $$metacache{"$key.name"}=$name;
1.428 albertel 10465: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10466: $allnames{$name}.'_'.$name.
10467: '.type'};
1.428 albertel 10468: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10469: '.display'};
1.644 www 10470: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10471: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10472: $$metacache{"$key.display"}=$olddis;
10473: }
1.71 www 10474: }
10475:
1.764 albertel 10476: # ------------------------------------------------------ Devalidate title cache
10477:
10478: sub devalidate_title_cache {
10479: my ($url)=@_;
10480: if (!$env{'request.course.id'}) { return; }
10481: my $symb=&symbread($url);
10482: if (!$symb) { return; }
10483: my $key=$env{'request.course.id'}."\0".$symb;
10484: &devalidate_cache_new('title',$key);
10485: }
10486:
1.1014 droeschl 10487: # ------------------------------------------------- Get the title of a course
10488:
10489: sub current_course_title {
10490: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10491: }
1.301 www 10492: # ------------------------------------------------- Get the title of a resource
10493:
10494: sub gettitle {
10495: my $urlsymb=shift;
10496: my $symb=&symbread($urlsymb);
1.534 albertel 10497: if ($symb) {
1.620 albertel 10498: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10499: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10500: if (defined($cached)) {
10501: return $result;
10502: }
1.534 albertel 10503: my ($map,$resid,$url)=&decode_symb($symb);
10504: my $title='';
1.907 albertel 10505: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10506: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10507: } else {
10508: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10509: &GDBM_READER(),0640)) {
10510: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10511: $title=$bighash{'title_'.$mapid.'.'.$resid};
10512: untie(%bighash);
10513: }
1.534 albertel 10514: }
10515: $title=~s/\&colon\;/\:/gs;
10516: if ($title) {
1.1159 www 10517: # Remember both $symb and $title for dynamic metadata
10518: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10519: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10520: # Cache this title and then return it
1.599 albertel 10521: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10522: }
10523: $urlsymb=$url;
10524: }
10525: my $title=&metadata($urlsymb,'title');
10526: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10527: return $title;
1.301 www 10528: }
1.613 albertel 10529:
1.614 albertel 10530: sub get_slot {
10531: my ($which,$cnum,$cdom)=@_;
10532: if (!$cnum || !$cdom) {
1.790 albertel 10533: (undef,my $courseid)=&whichuser();
1.620 albertel 10534: $cdom=$env{'course.'.$courseid.'.domain'};
10535: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10536: }
1.703 albertel 10537: my $key=join("\0",'slots',$cdom,$cnum,$which);
10538: my %slotinfo;
10539: if (exists($remembered{$key})) {
10540: $slotinfo{$which} = $remembered{$key};
10541: } else {
10542: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10543: &Apache::lonhomework::showhash(%slotinfo);
10544: my ($tmp)=keys(%slotinfo);
10545: if ($tmp=~/^error:/) { return (); }
10546: $remembered{$key} = $slotinfo{$which};
10547: }
1.616 albertel 10548: if (ref($slotinfo{$which}) eq 'HASH') {
10549: return %{$slotinfo{$which}};
10550: }
10551: return $slotinfo{$which};
1.614 albertel 10552: }
1.1150 raeburn 10553:
10554: sub get_reservable_slots {
10555: my ($cnum,$cdom,$uname,$udom) = @_;
10556: my $now = time;
10557: my $reservable_info;
10558: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10559: if (exists($remembered{$key})) {
10560: $reservable_info = $remembered{$key};
10561: } else {
10562: my %resv;
10563: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10564: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10565: $reservable_info = \%resv;
10566: $remembered{$key} = $reservable_info;
10567: }
10568: return $reservable_info;
10569: }
10570:
10571: sub get_course_slots {
10572: my ($cnum,$cdom) = @_;
10573: my $hashid=$cnum.':'.$cdom;
10574: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10575: if (defined($cached)) {
10576: if (ref($result) eq 'HASH') {
10577: return %{$result};
10578: }
10579: } else {
10580: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10581: my ($tmp) = keys(%slots);
10582: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10583: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10584: return %slots;
10585: }
10586: }
10587: return;
10588: }
10589:
10590: sub devalidate_slots_cache {
10591: my ($cnum,$cdom)=@_;
10592: my $hashid=$cnum.':'.$cdom;
10593: &devalidate_cache_new('allslots',$hashid);
10594: }
10595:
1.1181 raeburn 10596: sub get_coursechange {
10597: my ($cdom,$cnum) = @_;
10598: if ($cdom eq '' || $cnum eq '') {
10599: return unless ($env{'request.course.id'});
10600: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10601: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10602: }
10603: my $hashid=$cdom.'_'.$cnum;
10604: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10605: if ((defined($cached)) && ($change ne '')) {
10606: return $change;
10607: } else {
10608: my %crshash;
10609: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10610: if ($crshash{'internal.contentchange'} eq '') {
10611: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10612: if ($change eq '') {
10613: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10614: $change = $crshash{'internal.created'};
10615: }
10616: } else {
10617: $change = $crshash{'internal.contentchange'};
10618: }
10619: my $cachetime = 600;
10620: &do_cache_new('crschange',$hashid,$change,$cachetime);
10621: }
10622: return $change;
10623: }
10624:
10625: sub devalidate_coursechange_cache {
10626: my ($cnum,$cdom)=@_;
10627: my $hashid=$cnum.':'.$cdom;
10628: &devalidate_cache_new('crschange',$hashid);
10629: }
10630:
1.31 www 10631: # ------------------------------------------------- Update symbolic store links
10632:
10633: sub symblist {
10634: my ($mapname,%newhash)=@_;
1.438 www 10635: $mapname=&deversion(&declutter($mapname));
1.31 www 10636: my %hash;
1.620 albertel 10637: if (($env{'request.course.fn'}) && (%newhash)) {
10638: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10639: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10640: foreach my $url (keys(%newhash)) {
1.711 albertel 10641: next if ($url eq 'last_known'
10642: && $env{'form.no_update_last_known'});
10643: $hash{declutter($url)}=&encode_symb($mapname,
10644: $newhash{$url}->[1],
10645: $newhash{$url}->[0]);
1.191 harris41 10646: }
1.31 www 10647: if (untie(%hash)) {
10648: return 'ok';
10649: }
10650: }
10651: }
10652: return 'error';
1.212 www 10653: }
10654:
10655: # --------------------------------------------------------------- Verify a symb
10656:
10657: sub symbverify {
1.1190 raeburn 10658: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10659: my $thisfn=$thisurl;
1.439 www 10660: $thisfn=&declutter($thisfn);
1.215 www 10661: # direct jump to resource in page or to a sequence - will construct own symbs
10662: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10663: # check URL part
1.409 www 10664: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10665:
1.431 www 10666: unless ($url eq $thisfn) { return 0; }
1.213 www 10667:
1.216 www 10668: $symb=&symbclean($symb);
1.510 www 10669: $thisurl=&deversion($thisurl);
1.439 www 10670: $thisfn=&deversion($thisfn);
1.213 www 10671:
10672: my %bighash;
10673: my $okay=0;
1.431 www 10674:
1.620 albertel 10675: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10676: &GDBM_READER(),0640)) {
1.1204 raeburn 10677: my $noclutter;
1.1032 raeburn 10678: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10679: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10680: if ($map =~ m{^uploaded/.+\.page$}) {
10681: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10682: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10683: $noclutter = 1;
10684: }
10685: }
10686: my $ids;
10687: if ($noclutter) {
10688: $ids=$bighash{'ids_'.$thisurl};
10689: } else {
10690: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10691: }
1.1102 raeburn 10692: unless ($ids) {
10693: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10694: $ids=$bighash{$idkey};
1.216 www 10695: }
10696: if ($ids) {
10697: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10698: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10699: $symb =~ s/\?.+$//;
1.1202 raeburn 10700: }
1.800 albertel 10701: foreach my $id (split(/\,/,$ids)) {
10702: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10703: if (
10704: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10705: eq $symb) {
10706: if (ref($encstate)) {
10707: $$encstate = $bighash{'encrypted_'.$id};
10708: }
1.620 albertel 10709: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10710: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10711: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10712: $okay=1;
1.1202 raeburn 10713: last;
1.582 albertel 10714: }
10715: }
1.216 www 10716: }
10717: }
1.213 www 10718: untie(%bighash);
10719: }
10720: return $okay;
1.31 www 10721: }
10722:
1.210 www 10723: # --------------------------------------------------------------- Clean-up symb
10724:
10725: sub symbclean {
10726: my $symb=shift;
1.568 albertel 10727: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10728: # remove version from map
10729: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10730:
1.210 www 10731: # remove version from URL
10732: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10733:
1.507 www 10734: # remove wrapper
10735:
1.510 www 10736: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10737: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10738: return $symb;
1.409 www 10739: }
10740:
10741: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10742:
10743: sub encode_symb {
10744: my ($map,$resid,$url)=@_;
10745: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10746: }
1.409 www 10747:
10748: sub decode_symb {
1.568 albertel 10749: my $symb=shift;
10750: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10751: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10752: return (&fixversion($map),$resid,&fixversion($url));
10753: }
10754:
10755: sub fixversion {
10756: my $fn=shift;
1.609 banghart 10757: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10758: my %bighash;
10759: my $uri=&clutter($fn);
1.620 albertel 10760: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10761: # is this cached?
1.599 albertel 10762: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10763: if (defined($cached)) { return $result; }
10764: # unfortunately not cached, or expired
1.620 albertel 10765: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10766: &GDBM_READER(),0640)) {
10767: if ($bighash{'version_'.$uri}) {
10768: my $version=$bighash{'version_'.$uri};
1.444 www 10769: unless (($version eq 'mostrecent') ||
10770: ($version==&getversion($uri))) {
1.440 www 10771: $uri=~s/\.(\w+)$/\.$version\.$1/;
10772: }
10773: }
10774: untie %bighash;
1.413 www 10775: }
1.599 albertel 10776: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10777: }
10778:
10779: sub deversion {
10780: my $url=shift;
10781: $url=~s/\.\d+\.(\w+)$/\.$1/;
10782: return $url;
1.210 www 10783: }
10784:
1.31 www 10785: # ------------------------------------------------------ Return symb list entry
10786:
10787: sub symbread {
1.249 www 10788: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10789: my $cache_str;
10790: if ($thisfn ne '') {
10791: $cache_str='request.symbread.cached.'.$thisfn;
10792: if ($env{$cache_str} ne '') {
1.1179 raeburn 10793: return $env{$cache_str};
10794: }
1.1206 raeburn 10795: } else {
1.242 www 10796: # no filename provided? try from environment
1.620 albertel 10797: if ($env{'request.symb'}) {
10798: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10799: }
1.620 albertel 10800: $thisfn=$env{'request.filename'};
1.44 www 10801: }
1.569 albertel 10802: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10803: # is that filename actually a symb? Verify, clean, and return
10804: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10805: if (&symbverify($thisfn,$1)) {
1.620 albertel 10806: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10807: }
1.242 www 10808: }
1.44 www 10809: $thisfn=declutter($thisfn);
1.31 www 10810: my %hash;
1.37 www 10811: my %bighash;
10812: my $syval='';
1.620 albertel 10813: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10814: my $targetfn = $thisfn;
1.609 banghart 10815: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10816: $targetfn = 'adm/wrapper/'.$thisfn;
10817: }
1.687 albertel 10818: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10819: $targetfn=$1;
10820: }
1.620 albertel 10821: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10822: &GDBM_READER(),0640)) {
1.481 raeburn 10823: $syval=$hash{$targetfn};
1.37 www 10824: untie(%hash);
10825: }
10826: # ---------------------------------------------------------- There was an entry
10827: if ($syval) {
1.601 albertel 10828: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10829: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10830: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10831: #return $env{$cache_str}='';
1.601 albertel 10832: #}
10833: #$syval.=$1;
10834: #}
1.37 www 10835: } else {
10836: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10837: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10838: &GDBM_READER(),0640)) {
1.37 www 10839: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10840: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10841: unless ($ids) {
10842: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10843: }
10844: unless ($ids) {
10845: # alias?
10846: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10847: }
1.37 www 10848: if ($ids) {
10849: # ------------------------------------------------------------------- Has ID(s)
10850: my @possibilities=split(/\,/,$ids);
1.39 www 10851: if ($#possibilities==0) {
10852: # ----------------------------------------------- There is only one possibility
1.37 www 10853: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10854: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10855: $resid,$thisfn);
1.249 www 10856: } elsif (!$donotrecurse) {
1.39 www 10857: # ------------------------------------------ There is more than one possibility
10858: my $realpossible=0;
1.800 albertel 10859: foreach my $id (@possibilities) {
10860: my $file=$bighash{'src_'.$id};
1.39 www 10861: if (&allowed('bre',$file)) {
1.800 albertel 10862: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10863: if ($bighash{'map_type_'.$mapid} ne 'page') {
10864: $realpossible++;
1.626 albertel 10865: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10866: $resid,$thisfn);
1.39 www 10867: }
10868: }
1.191 harris41 10869: }
1.39 www 10870: if ($realpossible!=1) { $syval=''; }
1.249 www 10871: } else {
10872: $syval='';
1.37 www 10873: }
10874: }
10875: untie(%bighash)
1.481 raeburn 10876: }
1.31 www 10877: }
1.62 www 10878: if ($syval) {
1.620 albertel 10879: return $env{$cache_str}=$syval;
1.62 www 10880: }
1.31 www 10881: }
1.949 raeburn 10882: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10883: return $env{$cache_str}='';
1.31 www 10884: }
10885:
10886: # ---------------------------------------------------------- Return random seed
10887:
1.32 www 10888: sub numval {
10889: my $txt=shift;
10890: $txt=~tr/A-J/0-9/;
10891: $txt=~tr/a-j/0-9/;
10892: $txt=~tr/K-T/0-9/;
10893: $txt=~tr/k-t/0-9/;
10894: $txt=~tr/U-Z/0-5/;
10895: $txt=~tr/u-z/0-5/;
10896: $txt=~s/\D//g;
1.564 albertel 10897: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10898: return int($txt);
1.368 albertel 10899: }
10900:
1.484 albertel 10901: sub numval2 {
10902: my $txt=shift;
10903: $txt=~tr/A-J/0-9/;
10904: $txt=~tr/a-j/0-9/;
10905: $txt=~tr/K-T/0-9/;
10906: $txt=~tr/k-t/0-9/;
10907: $txt=~tr/U-Z/0-5/;
10908: $txt=~tr/u-z/0-5/;
10909: $txt=~s/\D//g;
10910: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10911: my $total;
10912: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10913: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10914: return int($total);
10915: }
10916:
1.575 albertel 10917: sub numval3 {
10918: use integer;
10919: my $txt=shift;
10920: $txt=~tr/A-J/0-9/;
10921: $txt=~tr/a-j/0-9/;
10922: $txt=~tr/K-T/0-9/;
10923: $txt=~tr/k-t/0-9/;
10924: $txt=~tr/U-Z/0-5/;
10925: $txt=~tr/u-z/0-5/;
10926: $txt=~s/\D//g;
10927: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10928: my $total;
10929: foreach my $val (@txts) { $total+=$val; }
10930: if ($_64bit) { $total=(($total<<32)>>32); }
10931: return $total;
10932: }
10933:
1.675 albertel 10934: sub digest {
10935: my ($data)=@_;
10936: my $digest=&Digest::MD5::md5($data);
10937: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10938: my ($e,$f);
10939: {
10940: use integer;
10941: $e=($a+$b);
10942: $f=($c+$d);
10943: if ($_64bit) {
10944: $e=(($e<<32)>>32);
10945: $f=(($f<<32)>>32);
10946: }
10947: }
10948: if (wantarray) {
10949: return ($e,$f);
10950: } else {
10951: my $g;
10952: {
10953: use integer;
10954: $g=($e+$f);
10955: if ($_64bit) {
10956: $g=(($g<<32)>>32);
10957: }
10958: }
10959: return $g;
10960: }
10961: }
10962:
1.368 albertel 10963: sub latest_rnd_algorithm_id {
1.675 albertel 10964: return '64bit5';
1.366 albertel 10965: }
1.32 www 10966:
1.503 albertel 10967: sub get_rand_alg {
10968: my ($courseid)=@_;
1.790 albertel 10969: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10970: if ($courseid) {
1.620 albertel 10971: return $env{"course.$courseid.rndseed"};
1.503 albertel 10972: }
10973: return &latest_rnd_algorithm_id();
10974: }
10975:
1.562 albertel 10976: sub validCODE {
10977: my ($CODE)=@_;
10978: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10979: return 0;
10980: }
10981:
1.491 albertel 10982: sub getCODE {
1.620 albertel 10983: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10984: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10985: defined($Apache::lonhomework::parsing_a_task) ) &&
10986: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10987: return $Apache::lonhomework::history{'resource.CODE'};
10988: }
10989: return undef;
10990: }
1.1133 foxr 10991: #
10992: # Determines the random seed for a specific context:
10993: #
10994: # parameters:
10995: # symb - in course context the symb for the seed.
10996: # course_id - The course id of the form domain_coursenum.
10997: # domain - Domain for the user.
10998: # course - Course for the user.
10999: # cenv - environment of the course.
11000: #
11001: # NOTE:
11002: # All parameters are picked out of the environment if missing
11003: # or not defined.
11004: # If a symb cannot be determined the current time is used instead.
11005: #
11006: # For a given well defined symb, courside, domain, username,
11007: # and course environment, the seed is reproducible.
11008: #
1.31 www 11009: sub rndseed {
1.1133 foxr 11010: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11011: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11012: if (!defined($symb)) {
1.366 albertel 11013: unless ($symb=$wsymb) { return time; }
11014: }
1.1146 foxr 11015: if (!defined $courseid) {
11016: $courseid=$wcourseid;
11017: }
11018: if (!defined $domain) { $domain=$wdomain; }
11019: if (!defined $username) { $username=$wusername }
1.1133 foxr 11020:
11021: my $which;
11022: if (defined($cenv->{'rndseed'})) {
11023: $which = $cenv->{'rndseed'};
11024: } else {
11025: $which =&get_rand_alg($courseid);
11026: }
1.491 albertel 11027: if (defined(&getCODE())) {
1.1133 foxr 11028:
1.675 albertel 11029: if ($which eq '64bit5') {
11030: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11031: } elsif ($which eq '64bit4') {
1.575 albertel 11032: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11033: } else {
11034: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11035: }
1.675 albertel 11036: } elsif ($which eq '64bit5') {
11037: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11038: } elsif ($which eq '64bit4') {
11039: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11040: } elsif ($which eq '64bit3') {
11041: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11042: } elsif ($which eq '64bit2') {
11043: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11044: } elsif ($which eq '64bit') {
11045: return &rndseed_64bit($symb,$courseid,$domain,$username);
11046: }
11047: return &rndseed_32bit($symb,$courseid,$domain,$username);
11048: }
11049:
11050: sub rndseed_32bit {
11051: my ($symb,$courseid,$domain,$username)=@_;
11052: {
11053: use integer;
11054: my $symbchck=unpack("%32C*",$symb) << 27;
11055: my $symbseed=numval($symb) << 22;
11056: my $namechck=unpack("%32C*",$username) << 17;
11057: my $nameseed=numval($username) << 12;
11058: my $domainseed=unpack("%32C*",$domain) << 7;
11059: my $courseseed=unpack("%32C*",$courseid);
11060: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11061: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11062: #&logthis("rndseed :$num:$symb");
1.564 albertel 11063: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11064: return $num;
11065: }
11066: }
11067:
11068: sub rndseed_64bit {
11069: my ($symb,$courseid,$domain,$username)=@_;
11070: {
11071: use integer;
11072: my $symbchck=unpack("%32S*",$symb) << 21;
11073: my $symbseed=numval($symb) << 10;
11074: my $namechck=unpack("%32S*",$username);
11075:
11076: my $nameseed=numval($username) << 21;
11077: my $domainseed=unpack("%32S*",$domain) << 10;
11078: my $courseseed=unpack("%32S*",$courseid);
11079:
11080: my $num1=$symbchck+$symbseed+$namechck;
11081: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11082: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11083: #&logthis("rndseed :$num:$symb");
1.564 albertel 11084: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11085: return "$num1,$num2";
1.155 albertel 11086: }
1.366 albertel 11087: }
11088:
1.443 albertel 11089: sub rndseed_64bit2 {
11090: my ($symb,$courseid,$domain,$username)=@_;
11091: {
11092: use integer;
11093: # strings need to be an even # of cahracters long, it it is odd the
11094: # last characters gets thrown away
11095: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11096: my $symbseed=numval($symb) << 10;
11097: my $namechck=unpack("%32S*",$username.' ');
11098:
11099: my $nameseed=numval($username) << 21;
1.501 albertel 11100: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11101: my $courseseed=unpack("%32S*",$courseid.' ');
11102:
11103: my $num1=$symbchck+$symbseed+$namechck;
11104: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11105: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11106: #&logthis("rndseed :$num:$symb");
1.803 albertel 11107: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11108: return "$num1,$num2";
11109: }
11110: }
11111:
11112: sub rndseed_64bit3 {
11113: my ($symb,$courseid,$domain,$username)=@_;
11114: {
11115: use integer;
11116: # strings need to be an even # of cahracters long, it it is odd the
11117: # last characters gets thrown away
11118: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11119: my $symbseed=numval2($symb) << 10;
11120: my $namechck=unpack("%32S*",$username.' ');
11121:
11122: my $nameseed=numval2($username) << 21;
1.443 albertel 11123: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11124: my $courseseed=unpack("%32S*",$courseid.' ');
11125:
11126: my $num1=$symbchck+$symbseed+$namechck;
11127: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11128: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11129: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11130: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11131:
1.503 albertel 11132: return "$num1:$num2";
1.443 albertel 11133: }
11134: }
11135:
1.575 albertel 11136: sub rndseed_64bit4 {
11137: my ($symb,$courseid,$domain,$username)=@_;
11138: {
11139: use integer;
11140: # strings need to be an even # of cahracters long, it it is odd the
11141: # last characters gets thrown away
11142: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11143: my $symbseed=numval3($symb) << 10;
11144: my $namechck=unpack("%32S*",$username.' ');
11145:
11146: my $nameseed=numval3($username) << 21;
11147: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11148: my $courseseed=unpack("%32S*",$courseid.' ');
11149:
11150: my $num1=$symbchck+$symbseed+$namechck;
11151: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11152: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11153: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11154: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11155:
1.575 albertel 11156: return "$num1:$num2";
11157: }
11158: }
11159:
1.675 albertel 11160: sub rndseed_64bit5 {
11161: my ($symb,$courseid,$domain,$username)=@_;
11162: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11163: return "$num1:$num2";
11164: }
11165:
1.366 albertel 11166: sub rndseed_CODE_64bit {
11167: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11168: {
1.366 albertel 11169: use integer;
1.443 albertel 11170: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11171: my $symbseed=numval2($symb);
1.491 albertel 11172: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11173: my $CODEseed=numval(&getCODE());
1.443 albertel 11174: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11175: my $num1=$symbseed+$CODEchck;
11176: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11177: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11178: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11179: if ($_64bit) { $num1=(($num1<<32)>>32); }
11180: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11181: return "$num1:$num2";
1.366 albertel 11182: }
11183: }
11184:
1.575 albertel 11185: sub rndseed_CODE_64bit4 {
11186: my ($symb,$courseid,$domain,$username)=@_;
11187: {
11188: use integer;
11189: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11190: my $symbseed=numval3($symb);
11191: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11192: my $CODEseed=numval3(&getCODE());
11193: my $courseseed=unpack("%32S*",$courseid.' ');
11194: my $num1=$symbseed+$CODEchck;
11195: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11196: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11197: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11198: if ($_64bit) { $num1=(($num1<<32)>>32); }
11199: if ($_64bit) { $num2=(($num2<<32)>>32); }
11200: return "$num1:$num2";
11201: }
11202: }
11203:
1.675 albertel 11204: sub rndseed_CODE_64bit5 {
11205: my ($symb,$courseid,$domain,$username)=@_;
11206: my $code = &getCODE();
11207: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11208: return "$num1:$num2";
11209: }
11210:
1.366 albertel 11211: sub setup_random_from_rndseed {
11212: my ($rndseed)=@_;
1.503 albertel 11213: if ($rndseed =~/([,:])/) {
11214: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11215: &Math::Random::random_set_seed(abs($num1),abs($num2));
11216: } else {
11217: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11218: }
1.36 albertel 11219: }
11220:
1.474 albertel 11221: sub latest_receipt_algorithm_id {
1.835 albertel 11222: return 'receipt3';
1.474 albertel 11223: }
11224:
1.480 www 11225: sub recunique {
11226: my $fucourseid=shift;
11227: my $unique;
1.835 albertel 11228: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11229: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11230: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11231: } else {
11232: $unique=$perlvar{'lonReceipt'};
11233: }
11234: return unpack("%32C*",$unique);
11235: }
11236:
11237: sub recprefix {
11238: my $fucourseid=shift;
11239: my $prefix;
1.835 albertel 11240: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11241: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11242: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11243: } else {
11244: $prefix=$perlvar{'lonHostID'};
11245: }
11246: return unpack("%32C*",$prefix);
11247: }
11248:
1.76 www 11249: sub ireceipt {
1.474 albertel 11250: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11251:
11252: my $return =&recprefix($fucourseid).'-';
11253:
11254: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11255: $env{'request.state'} eq 'construct') {
11256: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11257: return $return;
11258: }
11259:
1.76 www 11260: my $cuname=unpack("%32C*",$funame);
11261: my $cudom=unpack("%32C*",$fudom);
11262: my $cucourseid=unpack("%32C*",$fucourseid);
11263: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11264: my $cunique=&recunique($fucourseid);
1.474 albertel 11265: my $cpart=unpack("%32S*",$part);
1.835 albertel 11266: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11267:
1.790 albertel 11268: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11269:
11270: $return.= ($cunique%$cuname+
11271: $cunique%$cudom+
11272: $cusymb%$cuname+
11273: $cusymb%$cudom+
11274: $cucourseid%$cuname+
11275: $cucourseid%$cudom+
11276: $cpart%$cuname+
11277: $cpart%$cudom);
11278: } else {
11279: $return.= ($cunique%$cuname+
11280: $cunique%$cudom+
11281: $cusymb%$cuname+
11282: $cusymb%$cudom+
11283: $cucourseid%$cuname+
11284: $cucourseid%$cudom);
11285: }
11286: return $return;
1.76 www 11287: }
11288:
11289: sub receipt {
1.474 albertel 11290: my ($part)=@_;
1.790 albertel 11291: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11292: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11293: }
1.260 ng 11294:
1.790 albertel 11295: sub whichuser {
11296: my ($passedsymb)=@_;
11297: my ($symb,$courseid,$domain,$name,$publicuser);
11298: if (defined($env{'form.grade_symb'})) {
11299: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11300: my $allowed=&allowed('vgr',$tmp_courseid);
11301: if (!$allowed &&
11302: exists($env{'request.course.sec'}) &&
11303: $env{'request.course.sec'} !~ /^\s*$/) {
11304: $allowed=&allowed('vgr',$tmp_courseid.
11305: '/'.$env{'request.course.sec'});
11306: }
11307: if ($allowed) {
11308: ($symb)=&get_env_multiple('form.grade_symb');
11309: $courseid=$tmp_courseid;
11310: ($domain)=&get_env_multiple('form.grade_domain');
11311: ($name)=&get_env_multiple('form.grade_username');
11312: return ($symb,$courseid,$domain,$name,$publicuser);
11313: }
11314: }
11315: if (!$passedsymb) {
11316: $symb=&symbread();
11317: } else {
11318: $symb=$passedsymb;
11319: }
11320: $courseid=$env{'request.course.id'};
11321: $domain=$env{'user.domain'};
11322: $name=$env{'user.name'};
11323: if ($name eq 'public' && $domain eq 'public') {
11324: if (!defined($env{'form.username'})) {
11325: $env{'form.username'}.=time.rand(10000000);
11326: }
11327: $name.=$env{'form.username'};
11328: }
11329: return ($symb,$courseid,$domain,$name,$publicuser);
11330:
11331: }
11332:
1.36 albertel 11333: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11334: # returns either the contents of the file or
11335: # -1 if the file doesn't exist
1.481 raeburn 11336: #
11337: # if the target is a file that was uploaded via DOCS,
11338: # a check will be made to see if a current copy exists on the local server,
11339: # if it does this will be served, otherwise a copy will be retrieved from
11340: # the home server for the course and stored in /home/httpd/html/userfiles on
11341: # the local server.
1.472 albertel 11342:
1.36 albertel 11343: sub getfile {
1.538 albertel 11344: my ($file) = @_;
1.609 banghart 11345: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11346: &repcopy($file);
11347: return &readfile($file);
11348: }
11349:
11350: sub repcopy_userfile {
11351: my ($file)=@_;
1.1142 raeburn 11352: my $londocroot = $perlvar{'lonDocRoot'};
11353: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11354: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11355: my ($cdom,$cnum,$filename) =
1.811 albertel 11356: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11357: my $uri="/uploaded/$cdom/$cnum/$filename";
11358: if (-e "$file") {
1.828 www 11359: # we already have a local copy, check it out
1.538 albertel 11360: my @fileinfo = stat($file);
1.828 www 11361: my $rtncode;
11362: my $info;
1.538 albertel 11363: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11364: if ($lwpresp ne 'ok') {
1.828 www 11365: # there is no such file anymore, even though we had a local copy
1.482 albertel 11366: if ($rtncode eq '404') {
1.538 albertel 11367: unlink($file);
1.482 albertel 11368: }
11369: return -1;
11370: }
11371: if ($info < $fileinfo[9]) {
1.828 www 11372: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11373: return 'ok';
1.828 www 11374: } else {
11375: # the file is outdated, get rid of it
11376: unlink($file);
1.482 albertel 11377: }
1.828 www 11378: }
11379: # one way or the other, at this point, we don't have the file
11380: # construct the correct path for the file
11381: my @parts = ($cdom,$cnum);
11382: if ($filename =~ m|^(.+)/[^/]+$|) {
11383: push @parts, split(/\//,$1);
11384: }
11385: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11386: foreach my $part (@parts) {
11387: $path .= '/'.$part;
11388: if (!-e $path) {
11389: mkdir($path,0770);
1.482 albertel 11390: }
11391: }
1.828 www 11392: # now the path exists for sure
11393: # get a user agent
11394: my $ua=new LWP::UserAgent;
11395: my $transferfile=$file.'.in.transfer';
11396: # FIXME: this should flock
11397: if (-e $transferfile) { return 'ok'; }
11398: my $request;
11399: $uri=~s/^\///;
1.980 raeburn 11400: my $homeserver = &homeserver($cnum,$cdom);
11401: my $protocol = $protocol{$homeserver};
11402: $protocol = 'http' if ($protocol ne 'https');
11403: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11404: my $response=$ua->request($request,$transferfile);
11405: # did it work?
11406: if ($response->is_error()) {
11407: unlink($transferfile);
11408: &logthis("Userfile repcopy failed for $uri");
11409: return -1;
11410: }
11411: # worked, rename the transfer file
11412: rename($transferfile,$file);
1.607 raeburn 11413: return 'ok';
1.481 raeburn 11414: }
11415:
1.517 albertel 11416: sub tokenwrapper {
11417: my $uri=shift;
1.980 raeburn 11418: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11419: $uri=~s|^/||;
1.620 albertel 11420: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11421: my $token=$1;
1.552 albertel 11422: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11423: if ($udom && $uname && $file) {
11424: $file=~s|(\?\.*)*$||;
1.949 raeburn 11425: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11426: my $homeserver = &homeserver($uname,$udom);
11427: my $protocol = $protocol{$homeserver};
11428: $protocol = 'http' if ($protocol ne 'https');
11429: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11430: (($uri=~/\?/)?'&':'?').'token='.$token.
11431: '&tokenissued='.$perlvar{'lonHostID'};
11432: } else {
11433: return '/adm/notfound.html';
11434: }
11435: }
11436:
1.828 www 11437: # call with reqtype HEAD: get last modification time
11438: # call with reqtype GET: get the file contents
11439: # Do not call this with reqtype GET for large files! It loads everything into memory
11440: #
1.481 raeburn 11441: sub getuploaded {
11442: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11443: $uri=~s/^\///;
1.980 raeburn 11444: my $homeserver = &homeserver($cnum,$cdom);
11445: my $protocol = $protocol{$homeserver};
11446: $protocol = 'http' if ($protocol ne 'https');
11447: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11448: my $ua=new LWP::UserAgent;
11449: my $request=new HTTP::Request($reqtype,$uri);
11450: my $response=$ua->request($request);
11451: $$rtncode = $response->code;
1.482 albertel 11452: if (! $response->is_success()) {
11453: return 'failed';
11454: }
11455: if ($reqtype eq 'HEAD') {
1.486 www 11456: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11457: } elsif ($reqtype eq 'GET') {
11458: $$info = $response->content;
1.472 albertel 11459: }
1.482 albertel 11460: return 'ok';
1.36 albertel 11461: }
11462:
1.481 raeburn 11463: sub readfile {
11464: my $file = shift;
11465: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11466: my $fh;
11467: open($fh,"<$file");
11468: my $a='';
1.800 albertel 11469: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11470: return $a;
11471: }
11472:
1.36 albertel 11473: sub filelocation {
1.590 banghart 11474: my ($dir,$file) = @_;
11475: my $location;
11476: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11477:
11478: if ($file =~ m-^/adm/-) {
11479: $file=~s-^/adm/wrapper/-/-;
11480: $file=~s-^/adm/coursedocs/showdoc/-/-;
11481: }
1.882 albertel 11482:
1.1139 www 11483: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11484: $location = $file;
1.609 banghart 11485: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11486: my ($udom,$uname,$filename)=
1.811 albertel 11487: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11488: my $home=&homeserver($uname,$udom);
11489: my $is_me=0;
11490: my @ids=¤t_machine_ids();
11491: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11492: if ($is_me) {
1.1117 foxr 11493: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11494: } else {
11495: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11496: $udom.'/'.$uname.'/'.$filename;
11497: }
1.882 albertel 11498: } elsif ($file =~ m-^/adm/-) {
11499: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11500: } else {
11501: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11502: $file=~s:^/(res|priv)/:/:;
11503: my $space=$1;
1.590 banghart 11504: if ( !( $file =~ m:^/:) ) {
11505: $location = $dir. '/'.$file;
11506: } else {
1.1142 raeburn 11507: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11508: }
1.59 albertel 11509: }
1.590 banghart 11510: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11511: while ($location=~m{/\.\./}) {
11512: if ($location =~ m{/[^/]+/\.\./}) {
11513: $location=~ s{/[^/]+/\.\./}{/}g;
11514: } else {
11515: $location=~ s{/\.\./}{/}g;
11516: }
11517: } #remove dir/..
1.590 banghart 11518: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11519: return $location;
1.46 www 11520: }
1.36 albertel 11521:
1.46 www 11522: sub hreflocation {
11523: my ($dir,$file)=@_;
1.980 raeburn 11524: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11525: $file=filelocation($dir,$file);
1.700 albertel 11526: } elsif ($file=~m-^/adm/-) {
11527: $file=~s-^/adm/wrapper/-/-;
11528: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11529: }
11530: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11531: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11532: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11533: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11534: {/uploaded/$1/$2/}x;
1.46 www 11535: }
1.913 albertel 11536: if ($file=~ m{^/userfiles/}) {
11537: $file =~ s{^/userfiles/}{/uploaded/};
11538: }
1.462 albertel 11539: return $file;
1.465 albertel 11540: }
11541:
1.1139 www 11542:
11543:
11544:
11545:
1.465 albertel 11546: sub current_machine_domains {
1.853 albertel 11547: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11548: }
11549:
11550: sub machine_domains {
11551: my ($hostname) = @_;
1.465 albertel 11552: my @domains;
1.838 albertel 11553: my %hostname = &all_hostnames();
1.465 albertel 11554: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11555: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11556: if ($hostname eq $name) {
1.844 albertel 11557: push(@domains,&host_domain($id));
1.465 albertel 11558: }
11559: }
11560: return @domains;
11561: }
11562:
11563: sub current_machine_ids {
1.853 albertel 11564: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11565: }
11566:
11567: sub machine_ids {
11568: my ($hostname) = @_;
11569: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11570: my @ids;
1.888 albertel 11571: my %name_to_host = &all_names();
1.889 albertel 11572: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11573: return @{ $name_to_host{$hostname} };
11574: }
11575: return;
1.31 www 11576: }
11577:
1.824 raeburn 11578: sub additional_machine_domains {
11579: my @domains;
11580: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11581: while( my $line = <$fh>) {
11582: $line =~ s/\s//g;
11583: push(@domains,$line);
11584: }
11585: return @domains;
11586: }
11587:
11588: sub default_login_domain {
11589: my $domain = $perlvar{'lonDefDomain'};
11590: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11591: foreach my $posdom (¤t_machine_domains(),
11592: &additional_machine_domains()) {
11593: if (lc($posdom) eq lc($testdomain)) {
11594: $domain=$posdom;
11595: last;
11596: }
11597: }
11598: return $domain;
11599: }
11600:
1.31 www 11601: # ------------------------------------------------------------- Declutters URLs
11602:
11603: sub declutter {
11604: my $thisfn=shift;
1.569 albertel 11605: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11606: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11607: $thisfn=~s/^\///;
1.697 albertel 11608: $thisfn=~s|^adm/wrapper/||;
11609: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11610: $thisfn=~s/^res\///;
1.1172 bisitz 11611: $thisfn=~s/^priv\///;
1.1032 raeburn 11612: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11613: $thisfn=~s/\?.+$//;
11614: }
1.268 www 11615: return $thisfn;
11616: }
11617:
11618: # ------------------------------------------------------------- Clutter up URLs
11619:
11620: sub clutter {
11621: my $thisfn='/'.&declutter(shift);
1.887 albertel 11622: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11623: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11624: $thisfn='/res'.$thisfn;
11625: }
1.1031 raeburn 11626: if ($thisfn !~m|^/adm|) {
11627: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11628: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11629: } else {
11630: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11631: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11632: if ($embstyle eq 'ssi'
11633: || ($embstyle eq 'hdn')
11634: || ($embstyle eq 'rat')
11635: || ($embstyle eq 'prv')
11636: || ($embstyle eq 'ign')) {
11637: #do nothing with these
11638: } elsif (($embstyle eq 'img')
1.695 albertel 11639: || ($embstyle eq 'emb')
11640: || ($embstyle eq 'wrp')) {
11641: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11642: } elsif ($embstyle eq 'unk'
11643: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11644: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11645: } else {
1.718 www 11646: # &logthis("Got a blank emb style");
1.695 albertel 11647: }
1.694 albertel 11648: }
11649: }
1.31 www 11650: return $thisfn;
1.12 www 11651: }
11652:
1.787 albertel 11653: sub clutter_with_no_wrapper {
11654: my $uri = &clutter(shift);
11655: if ($uri =~ m-^/adm/-) {
11656: $uri =~ s-^/adm/wrapper/-/-;
11657: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11658: }
11659: return $uri;
11660: }
11661:
1.557 albertel 11662: sub freeze_escape {
11663: my ($value)=@_;
11664: if (ref($value)) {
11665: $value=&nfreeze($value);
11666: return '__FROZEN__'.&escape($value);
11667: }
11668: return &escape($value);
11669: }
11670:
1.11 www 11671:
1.557 albertel 11672: sub thaw_unescape {
11673: my ($value)=@_;
11674: if ($value =~ /^__FROZEN__/) {
11675: substr($value,0,10,undef);
11676: $value=&unescape($value);
11677: return &thaw($value);
11678: }
11679: return &unescape($value);
11680: }
11681:
1.436 albertel 11682: sub correct_line_ends {
11683: my ($result)=@_;
11684: $$result =~s/\r\n/\n/mg;
11685: $$result =~s/\r/\n/mg;
1.415 albertel 11686: }
1.1 albertel 11687: # ================================================================ Main Program
11688:
1.184 www 11689: sub goodbye {
1.204 albertel 11690: &logthis("Starting Shut down");
1.443 albertel 11691: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11692: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11693: #converted
1.599 albertel 11694: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11695: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11696: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11697: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11698: #1.1 only
1.870 albertel 11699: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11700: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11701: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11702: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11703: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11704: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11705: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11706: &flushcourselogs();
11707: &logthis("Shutting down");
11708: }
11709:
1.852 albertel 11710: sub get_dns {
1.1210 raeburn 11711: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11712: if (!$ignore_cache) {
11713: my ($content,$cached)=
11714: &Apache::lonnet::is_cached_new('dns',$url);
11715: if ($cached) {
1.1210 raeburn 11716: &$func($content,$hashref);
1.869 albertel 11717: return;
11718: }
11719: }
11720:
11721: my %alldns;
1.852 albertel 11722: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11723: foreach my $dns (<$config>) {
11724: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11725: my $line = $1;
11726: my ($host,$protocol) = split(/:/,$line);
11727: if ($protocol ne 'https') {
11728: $protocol = 'http';
11729: }
11730: $alldns{$host} = $protocol;
1.869 albertel 11731: }
11732: while (%alldns) {
11733: my ($dns) = keys(%alldns);
1.852 albertel 11734: my $ua=new LWP::UserAgent;
1.1134 raeburn 11735: $ua->timeout(30);
1.979 raeburn 11736: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11737: my $response=$ua->request($request);
1.979 raeburn 11738: delete($alldns{$dns});
1.852 albertel 11739: next if ($response->is_error());
11740: my @content = split("\n",$response->content);
1.1210 raeburn 11741: unless ($nocache) {
1.1219 raeburn 11742: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11743: }
11744: &$func(\@content,$hashref);
1.869 albertel 11745: return;
1.852 albertel 11746: }
11747: close($config);
1.871 albertel 11748: my $which = (split('/',$url))[3];
11749: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11750: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11751: my @content = <$config>;
1.1210 raeburn 11752: &$func(\@content,$hashref);
11753: return;
11754: }
11755:
11756: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11757: sub parse_dns_checksums_tab {
1.1210 raeburn 11758: my ($lines,$hashref) = @_;
11759: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11760: my $loncaparev = &get_server_loncaparev($machine_dom);
11761: my ($release,$timestamp) = split(/\-/,$loncaparev);
11762: my (%chksum,%revnum);
11763: if (ref($lines) eq 'ARRAY') {
11764: chomp(@{$lines});
1.1238 raeburn 11765: my $version = shift(@{$lines});
11766: if ($version eq $release) {
1.1210 raeburn 11767: foreach my $line (@{$lines}) {
1.1238 raeburn 11768: my ($file,$version,$shasum) = split(/,/,$line);
11769: $chksum{$file} = $shasum;
11770: $revnum{$file} = $version;
1.1210 raeburn 11771: }
11772: if (ref($hashref) eq 'HASH') {
11773: %{$hashref} = (
11774: sums => \%chksum,
11775: versions => \%revnum,
11776: );
11777: }
11778: }
11779: }
1.869 albertel 11780: return;
1.852 albertel 11781: }
1.1210 raeburn 11782:
11783: sub fetch_dns_checksums {
1.1238 raeburn 11784: my %checksums;
11785: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11786: my $loncaparev = &get_server_loncaparev($machine_dom);
11787: my ($release,$timestamp) = split(/\-/,$loncaparev);
11788: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11789: \%checksums);
1.1210 raeburn 11790: return \%checksums;
11791: }
11792:
1.327 albertel 11793: # ------------------------------------------------------------ Read domain file
11794: {
1.852 albertel 11795: my $loaded;
1.846 albertel 11796: my %domain;
11797:
1.852 albertel 11798: sub parse_domain_tab {
11799: my ($lines) = @_;
11800: foreach my $line (@$lines) {
11801: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11802:
1.846 albertel 11803: chomp($line);
1.852 albertel 11804: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11805: my %this_domain;
11806: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11807: 'lang_def', 'city', 'longi', 'lati',
11808: 'primary') {
11809: $this_domain{$field} = shift(@elements);
11810: }
11811: $domain{$name} = \%this_domain;
1.852 albertel 11812: }
11813: }
1.864 albertel 11814:
11815: sub reset_domain_info {
11816: undef($loaded);
11817: undef(%domain);
11818: }
11819:
1.852 albertel 11820: sub load_domain_tab {
1.869 albertel 11821: my ($ignore_cache) = @_;
11822: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11823: my $fh;
11824: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11825: my @lines = <$fh>;
11826: &parse_domain_tab(\@lines);
1.448 albertel 11827: }
1.852 albertel 11828: close($fh);
11829: $loaded = 1;
1.327 albertel 11830: }
1.846 albertel 11831:
11832: sub domain {
1.852 albertel 11833: &load_domain_tab() if (!$loaded);
11834:
1.846 albertel 11835: my ($name,$what) = @_;
11836: return if ( !exists($domain{$name}) );
11837:
11838: if (!$what) {
11839: return $domain{$name}{'description'};
11840: }
11841: return $domain{$name}{$what};
11842: }
1.974 raeburn 11843:
11844: sub domain_info {
11845: &load_domain_tab() if (!$loaded);
11846: return %domain;
11847: }
11848:
1.327 albertel 11849: }
11850:
11851:
1.1 albertel 11852: # ------------------------------------------------------------- Read hosts file
11853: {
1.838 albertel 11854: my %hostname;
1.844 albertel 11855: my %hostdom;
1.845 albertel 11856: my %libserv;
1.852 albertel 11857: my $loaded;
1.888 albertel 11858: my %name_to_host;
1.1074 raeburn 11859: my %internetdom;
1.1107 raeburn 11860: my %LC_dns_serv;
1.852 albertel 11861:
11862: sub parse_hosts_tab {
11863: my ($file) = @_;
11864: foreach my $configline (@$file) {
11865: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11866: chomp($configline);
11867: if ($configline =~ /^\^/) {
11868: if ($configline =~ /^\^([\w.\-]+)/) {
11869: $LC_dns_serv{$1} = 1;
11870: }
11871: next;
11872: }
1.1074 raeburn 11873: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11874: $name=~s/\s//g;
11875: if ($id && $domain && $role && $name) {
11876: $hostname{$id}=$name;
1.888 albertel 11877: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11878: $hostdom{$id}=$domain;
11879: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11880: if (defined($protocol)) {
11881: if ($protocol eq 'https') {
11882: $protocol{$id} = $protocol;
11883: } else {
11884: $protocol{$id} = 'http';
11885: }
1.968 raeburn 11886: } else {
1.969 raeburn 11887: $protocol{$id} = 'http';
1.968 raeburn 11888: }
1.1074 raeburn 11889: if (defined($intdom)) {
11890: $internetdom{$id} = $intdom;
11891: }
1.852 albertel 11892: }
11893: }
11894: }
1.864 albertel 11895:
11896: sub reset_hosts_info {
1.897 albertel 11897: &purge_remembered();
1.864 albertel 11898: &reset_domain_info();
11899: &reset_hosts_ip_info();
1.892 albertel 11900: undef(%name_to_host);
1.864 albertel 11901: undef(%hostname);
11902: undef(%hostdom);
11903: undef(%libserv);
11904: undef($loaded);
11905: }
1.1 albertel 11906:
1.852 albertel 11907: sub load_hosts_tab {
1.869 albertel 11908: my ($ignore_cache) = @_;
11909: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11910: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11911: my @config = <$config>;
11912: &parse_hosts_tab(\@config);
11913: close($config);
11914: $loaded=1;
1.1 albertel 11915: }
1.852 albertel 11916:
1.838 albertel 11917: sub hostname {
1.852 albertel 11918: &load_hosts_tab() if (!$loaded);
11919:
1.838 albertel 11920: my ($lonid) = @_;
11921: return $hostname{$lonid};
11922: }
1.845 albertel 11923:
1.838 albertel 11924: sub all_hostnames {
1.852 albertel 11925: &load_hosts_tab() if (!$loaded);
11926:
1.838 albertel 11927: return %hostname;
11928: }
1.845 albertel 11929:
1.888 albertel 11930: sub all_names {
11931: &load_hosts_tab() if (!$loaded);
11932:
11933: return %name_to_host;
11934: }
11935:
1.974 raeburn 11936: sub all_host_domain {
11937: &load_hosts_tab() if (!$loaded);
11938: return %hostdom;
11939: }
11940:
1.845 albertel 11941: sub is_library {
1.852 albertel 11942: &load_hosts_tab() if (!$loaded);
11943:
1.845 albertel 11944: return exists($libserv{$_[0]});
11945: }
11946:
11947: sub all_library {
1.852 albertel 11948: &load_hosts_tab() if (!$loaded);
11949:
1.845 albertel 11950: return %libserv;
11951: }
11952:
1.1062 droeschl 11953: sub unique_library {
11954: #2x reverse removes all hostnames that appear more than once
11955: my %unique = reverse &all_library();
11956: return reverse %unique;
11957: }
11958:
1.841 albertel 11959: sub get_servers {
1.852 albertel 11960: &load_hosts_tab() if (!$loaded);
11961:
1.841 albertel 11962: my ($domain,$type) = @_;
11963: my %possible_hosts = ($type eq 'library') ? %libserv
11964: : %hostname;
11965: my %result;
1.842 albertel 11966: if (ref($domain) eq 'ARRAY') {
11967: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11968: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11969: $result{$host} = $hostname;
11970: }
11971: }
11972: } else {
11973: while ( my ($host,$hostname) = each(%possible_hosts)) {
11974: if ($hostdom{$host} eq $domain) {
11975: $result{$host} = $hostname;
11976: }
1.841 albertel 11977: }
11978: }
11979: return %result;
11980: }
1.845 albertel 11981:
1.1062 droeschl 11982: sub get_unique_servers {
11983: my %unique = reverse &get_servers(@_);
11984: return reverse %unique;
11985: }
11986:
1.844 albertel 11987: sub host_domain {
1.852 albertel 11988: &load_hosts_tab() if (!$loaded);
11989:
1.844 albertel 11990: my ($lonid) = @_;
11991: return $hostdom{$lonid};
11992: }
11993:
1.841 albertel 11994: sub all_domains {
1.852 albertel 11995: &load_hosts_tab() if (!$loaded);
11996:
1.841 albertel 11997: my %seen;
11998: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11999: return @uniq;
12000: }
1.1074 raeburn 12001:
12002: sub internet_dom {
12003: &load_hosts_tab() if (!$loaded);
12004:
12005: my ($lonid) = @_;
12006: return $internetdom{$lonid};
12007: }
1.1107 raeburn 12008:
12009: sub is_LC_dns {
12010: &load_hosts_tab() if (!$loaded);
12011:
12012: my ($hostname) = @_;
12013: return exists($LC_dns_serv{$hostname});
12014: }
12015:
1.1 albertel 12016: }
12017:
1.847 albertel 12018: {
12019: my %iphost;
1.856 albertel 12020: my %name_to_ip;
12021: my %lonid_to_ip;
1.869 albertel 12022:
1.847 albertel 12023: sub get_hosts_from_ip {
12024: my ($ip) = @_;
12025: my %iphosts = &get_iphost();
12026: if (ref($iphosts{$ip})) {
12027: return @{$iphosts{$ip}};
12028: }
12029: return;
1.839 albertel 12030: }
1.864 albertel 12031:
12032: sub reset_hosts_ip_info {
12033: undef(%iphost);
12034: undef(%name_to_ip);
12035: undef(%lonid_to_ip);
12036: }
1.856 albertel 12037:
12038: sub get_host_ip {
12039: my ($lonid) = @_;
12040: if (exists($lonid_to_ip{$lonid})) {
12041: return $lonid_to_ip{$lonid};
12042: }
12043: my $name=&hostname($lonid);
12044: my $ip = gethostbyname($name);
12045: return if (!$ip || length($ip) ne 4);
12046: $ip=inet_ntoa($ip);
12047: $name_to_ip{$name} = $ip;
12048: $lonid_to_ip{$lonid} = $ip;
12049: return $ip;
12050: }
1.847 albertel 12051:
12052: sub get_iphost {
1.869 albertel 12053: my ($ignore_cache) = @_;
1.894 albertel 12054:
1.869 albertel 12055: if (!$ignore_cache) {
12056: if (%iphost) {
12057: return %iphost;
12058: }
12059: my ($ip_info,$cached)=
12060: &Apache::lonnet::is_cached_new('iphost','iphost');
12061: if ($cached) {
12062: %iphost = %{$ip_info->[0]};
12063: %name_to_ip = %{$ip_info->[1]};
12064: %lonid_to_ip = %{$ip_info->[2]};
12065: return %iphost;
12066: }
12067: }
1.894 albertel 12068:
12069: # get yesterday's info for fallback
12070: my %old_name_to_ip;
12071: my ($ip_info,$cached)=
12072: &Apache::lonnet::is_cached_new('iphost','iphost');
12073: if ($cached) {
12074: %old_name_to_ip = %{$ip_info->[1]};
12075: }
12076:
1.888 albertel 12077: my %name_to_host = &all_names();
12078: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12079: my $ip;
12080: if (!exists($name_to_ip{$name})) {
12081: $ip = gethostbyname($name);
12082: if (!$ip || length($ip) ne 4) {
1.894 albertel 12083: if (defined($old_name_to_ip{$name})) {
12084: $ip = $old_name_to_ip{$name};
12085: &logthis("Can't find $name defaulting to old $ip");
12086: } else {
12087: &logthis("Name $name no IP found");
12088: next;
12089: }
12090: } else {
12091: $ip=inet_ntoa($ip);
1.847 albertel 12092: }
12093: $name_to_ip{$name} = $ip;
12094: } else {
12095: $ip = $name_to_ip{$name};
1.653 albertel 12096: }
1.888 albertel 12097: foreach my $id (@{ $name_to_host{$name} }) {
12098: $lonid_to_ip{$id} = $ip;
12099: }
12100: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12101: }
1.1219 raeburn 12102: &do_cache_new('iphost','iphost',
12103: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12104: 48*60*60);
1.869 albertel 12105:
1.847 albertel 12106: return %iphost;
1.598 albertel 12107: }
12108:
1.992 raeburn 12109: #
12110: # Given a DNS returns the loncapa host name for that DNS
12111: #
12112: sub host_from_dns {
12113: my ($dns) = @_;
12114: my @hosts;
12115: my $ip;
12116:
1.993 raeburn 12117: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12118: $ip = $name_to_ip{$dns};
12119: }
12120: if (!$ip) {
12121: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12122: if (length($ip) == 4) {
12123: $ip = &IO::Socket::inet_ntoa($ip);
12124: }
12125: }
12126: if ($ip) {
12127: @hosts = get_hosts_from_ip($ip);
12128: return $hosts[0];
12129: }
12130: return undef;
1.986 foxr 12131: }
1.992 raeburn 12132:
1.1074 raeburn 12133: sub get_internet_names {
12134: my ($lonid) = @_;
12135: return if ($lonid eq '');
12136: my ($idnref,$cached)=
12137: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12138: if ($cached) {
12139: return $idnref;
12140: }
12141: my $ip = &get_host_ip($lonid);
12142: my @hosts = &get_hosts_from_ip($ip);
12143: my %iphost = &get_iphost();
12144: my (@idns,%seen);
12145: foreach my $id (@hosts) {
12146: my $dom = &host_domain($id);
12147: my $prim_id = &domain($dom,'primary');
12148: my $prim_ip = &get_host_ip($prim_id);
12149: next if ($seen{$prim_ip});
12150: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12151: foreach my $id (@{$iphost{$prim_ip}}) {
12152: my $intdom = &internet_dom($id);
12153: unless (grep(/^\Q$intdom\E$/,@idns)) {
12154: push(@idns,$intdom);
12155: }
12156: }
12157: }
12158: $seen{$prim_ip} = 1;
12159: }
1.1219 raeburn 12160: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12161: }
12162:
1.986 foxr 12163: }
12164:
1.1079 raeburn 12165: sub all_loncaparevs {
1.1249 ! raeburn 12166: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
1.1079 raeburn 12167: }
12168:
1.1227 raeburn 12169: # ---------------------------------------------------------- Read loncaparev table
12170: {
12171: sub load_loncaparevs {
12172: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12173: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12174: while (my $configline=<$config>) {
12175: chomp($configline);
12176: my ($hostid,$loncaparev)=split(/:/,$configline);
12177: $loncaparevs{$hostid}=$loncaparev;
12178: }
12179: close($config);
12180: }
12181: }
12182: }
12183: }
12184:
12185: # ---------------------------------------------------------- Read serverhostID table
12186: {
12187: sub load_serverhomeIDs {
12188: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12189: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12190: while (my $configline=<$config>) {
12191: chomp($configline);
12192: my ($name,$id)=split(/:/,$configline);
12193: $serverhomeIDs{$name}=$id;
12194: }
12195: close($config);
12196: }
12197: }
12198: }
12199: }
12200:
12201:
1.862 albertel 12202: BEGIN {
12203:
12204: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12205: unless ($readit) {
12206: {
12207: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12208: %perlvar = (%perlvar,%{$configvars});
12209: }
12210:
12211:
1.1 albertel 12212: # ------------------------------------------------------ Read spare server file
12213: {
1.448 albertel 12214: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12215:
12216: while (my $configline=<$config>) {
12217: chomp($configline);
1.284 matthew 12218: if ($configline) {
1.784 albertel 12219: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12220: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12221: push(@{ $spareid{$type} }, $host);
1.1 albertel 12222: }
12223: }
1.448 albertel 12224: close($config);
1.1 albertel 12225: }
1.11 www 12226: # ------------------------------------------------------------ Read permissions
12227: {
1.448 albertel 12228: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12229:
12230: while (my $configline=<$config>) {
1.448 albertel 12231: chomp($configline);
12232: if ($configline) {
12233: my ($role,$perm)=split(/ /,$configline);
12234: if ($perm ne '') { $pr{$role}=$perm; }
12235: }
1.11 www 12236: }
1.448 albertel 12237: close($config);
1.11 www 12238: }
12239:
12240: # -------------------------------------------- Read plain texts for permissions
12241: {
1.448 albertel 12242: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12243:
12244: while (my $configline=<$config>) {
1.448 albertel 12245: chomp($configline);
12246: if ($configline) {
1.742 raeburn 12247: my ($short,@plain)=split(/:/,$configline);
12248: %{$prp{$short}} = ();
12249: if (@plain > 0) {
12250: $prp{$short}{'std'} = $plain[0];
12251: for (my $i=1; $i<@plain; $i++) {
12252: $prp{$short}{'alt'.$i} = $plain[$i];
12253: }
12254: }
1.448 albertel 12255: }
1.135 www 12256: }
1.448 albertel 12257: close($config);
1.135 www 12258: }
12259:
12260: # ---------------------------------------------------------- Read package table
12261: {
1.448 albertel 12262: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12263:
12264: while (my $configline=<$config>) {
1.483 albertel 12265: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12266: chomp($configline);
12267: my ($short,$plain)=split(/:/,$configline);
12268: my ($pack,$name)=split(/\&/,$short);
12269: if ($plain ne '') {
12270: $packagetab{$pack.'&'.$name.'&name'}=$name;
12271: $packagetab{$short}=$plain;
12272: }
1.11 www 12273: }
1.448 albertel 12274: close($config);
1.329 matthew 12275: }
12276:
1.1073 raeburn 12277: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12278:
12279: &load_loncaparevs();
1.1073 raeburn 12280:
1.1074 raeburn 12281: # ---------------------------------------------------------- Read serverhostID table
12282:
1.1227 raeburn 12283: &load_serverhomeIDs();
12284:
12285: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12286: {
12287: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12288: if (-e $file) {
12289: my $parser = HTML::LCParser->new($file);
12290: while (my $token = $parser->get_token()) {
12291: if ($token->[0] eq 'S') {
12292: my $item = $token->[1];
12293: my $name = $token->[2]{'name'};
12294: my $value = $token->[2]{'value'};
12295: if ($item ne '' && $name ne '' && $value ne '') {
12296: my $release = $parser->get_text();
12297: $release =~ s/(^\s*|\s*$ )//gx;
12298: $needsrelease{$item.':'.$name.':'.$value} = $release;
12299: }
12300: }
12301: }
12302: }
1.1073 raeburn 12303: }
12304:
1.1138 raeburn 12305: # ---------------------------------------------------------- Read managers table
12306: {
12307: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12308: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12309: while (my $configline=<$config>) {
12310: chomp($configline);
12311: next if ($configline =~ /^\#/);
12312: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12313: $managerstab{$configline} = 1;
12314: }
12315: }
12316: close($config);
12317: }
12318: }
12319: }
12320:
1.329 matthew 12321: # ------------- set up temporary directory
12322: {
1.1117 foxr 12323: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12324:
1.11 www 12325: }
12326:
1.794 albertel 12327: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12328: 'compress_threshold'=> 20_000,
12329: });
1.185 www 12330:
1.281 www 12331: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12332: $dumpcount=0;
1.958 www 12333: $locknum=0;
1.22 www 12334:
1.163 harris41 12335: &logtouch();
1.672 albertel 12336: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12337: $readit=1;
1.564 albertel 12338: {
12339: use integer;
12340: my $test=(2**32)+1;
1.568 albertel 12341: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12342: &logthis(" Detected 64bit platform ($_64bit)");
12343: }
1.195 www 12344: }
1.1 albertel 12345: }
1.179 www 12346:
1.1 albertel 12347: 1;
1.191 harris41 12348: __END__
12349:
1.243 albertel 12350: =pod
12351:
1.191 harris41 12352: =head1 NAME
12353:
1.243 albertel 12354: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12355:
12356: =head1 SYNOPSIS
12357:
1.243 albertel 12358: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12359:
12360: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12361:
1.243 albertel 12362: Common parameters:
12363:
12364: =over 4
12365:
12366: =item *
12367:
12368: $uname : an internal username (if $cname expecting a course Id specifically)
12369:
12370: =item *
12371:
12372: $udom : a domain (if $cdom expecting a course's domain specifically)
12373:
12374: =item *
12375:
12376: $symb : a resource instance identifier
12377:
12378: =item *
12379:
12380: $namespace : the name of a .db file that contains the data needed or
12381: being set.
12382:
12383: =back
12384:
1.394 bowersj2 12385: =head1 OVERVIEW
1.191 harris41 12386:
1.394 bowersj2 12387: lonnet provides subroutines which interact with the
12388: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12389: about classes, users, and resources.
1.243 albertel 12390:
12391: For many of these objects you can also use this to store data about
12392: them or modify them in various ways.
1.191 harris41 12393:
1.394 bowersj2 12394: =head2 Symbs
1.191 harris41 12395:
1.394 bowersj2 12396: To identify a specific instance of a resource, LON-CAPA uses symbols
12397: or "symbs"X<symb>. These identifiers are built from the URL of the
12398: map, the resource number of the resource in the map, and the URL of
12399: the resource itself. The latter is somewhat redundant, but might help
12400: if maps change.
12401:
12402: An example is
12403:
12404: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12405:
12406: The respective map entry is
12407:
12408: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12409: title="Problem 2">
12410: </resource>
12411:
12412: Symbs are used by the random number generator, as well as to store and
12413: restore data specific to a certain instance of for example a problem.
12414:
12415: =head2 Storing And Retrieving Data
12416:
12417: X<store()>X<cstore()>X<restore()>Three of the most important functions
12418: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12419: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12420: is is the non-critical message twin of cstore. These functions are for
12421: handlers to store a perl hash to a user's permanent data space in an
12422: easy manner, and to retrieve it again on another call. It is expected
12423: that a handler would use this once at the beginning to retrieve data,
12424: and then again once at the end to send only the new data back.
12425:
12426: The data is stored in the user's data directory on the user's
12427: homeserver under the ID of the course.
12428:
12429: The hash that is returned by restore will have all of the previous
12430: value for all of the elements of the hash.
12431:
12432: Example:
12433:
12434: #creating a hash
12435: my %hash;
12436: $hash{'foo'}='bar';
12437:
12438: #storing it
12439: &Apache::lonnet::cstore(\%hash);
12440:
12441: #changing a value
12442: $hash{'foo'}='notbar';
12443:
12444: #adding a new value
12445: $hash{'bar'}='foo';
12446: &Apache::lonnet::cstore(\%hash);
12447:
12448: #retrieving the hash
12449: my %history=&Apache::lonnet::restore();
12450:
12451: #print the hash
12452: foreach my $key (sort(keys(%history))) {
12453: print("\%history{$key} = $history{$key}");
12454: }
12455:
12456: Will print out:
1.191 harris41 12457:
1.394 bowersj2 12458: %history{1:foo} = bar
12459: %history{1:keys} = foo:timestamp
12460: %history{1:timestamp} = 990455579
12461: %history{2:bar} = foo
12462: %history{2:foo} = notbar
12463: %history{2:keys} = foo:bar:timestamp
12464: %history{2:timestamp} = 990455580
12465: %history{bar} = foo
12466: %history{foo} = notbar
12467: %history{timestamp} = 990455580
12468: %history{version} = 2
12469:
12470: Note that the special hash entries C<keys>, C<version> and
12471: C<timestamp> were added to the hash. C<version> will be equal to the
12472: total number of versions of the data that have been stored. The
12473: C<timestamp> attribute will be the UNIX time the hash was
12474: stored. C<keys> is available in every historical section to list which
12475: keys were added or changed at a specific historical revision of a
12476: hash.
12477:
12478: B<Warning>: do not store the hash that restore returns directly. This
12479: will cause a mess since it will restore the historical keys as if the
12480: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12481:
1.394 bowersj2 12482: Calling convention:
1.191 harris41 12483:
1.1225 raeburn 12484: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12485: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12486:
1.394 bowersj2 12487: For more detailed information, see lonnet specific documentation.
1.191 harris41 12488:
1.394 bowersj2 12489: =head1 RETURN MESSAGES
1.191 harris41 12490:
1.394 bowersj2 12491: =over 4
1.191 harris41 12492:
1.394 bowersj2 12493: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12494:
1.394 bowersj2 12495: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12496: when the connection is brought back up
1.191 harris41 12497:
1.394 bowersj2 12498: =item * B<con_failed>: unable to contact remote host and unable to save message
12499: for later delivery
1.191 harris41 12500:
1.967 bisitz 12501: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12502:
1.394 bowersj2 12503: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12504: that was requested
1.191 harris41 12505:
1.243 albertel 12506: =back
1.191 harris41 12507:
1.243 albertel 12508: =head1 PUBLIC SUBROUTINES
1.191 harris41 12509:
1.243 albertel 12510: =head2 Session Environment Functions
1.191 harris41 12511:
1.243 albertel 12512: =over 4
1.191 harris41 12513:
1.394 bowersj2 12514: =item *
12515: X<appenv()>
1.949 raeburn 12516: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12517: the user envirnoment file, and will be restored for each access this
1.620 albertel 12518: user makes during this session, also modifies the %env for the current
1.949 raeburn 12519: process. Optional rolesarrayref - if defined contains a reference to an array
12520: of roles which are exempt from the restriction on modifying user.role entries
12521: in the user's environment.db and in %env.
1.191 harris41 12522:
12523: =item *
1.394 bowersj2 12524: X<delenv()>
1.987 raeburn 12525: B<delenv($delthis,$regexp)>: removes all items from the session
12526: environment file that begin with $delthis. If the
12527: optional second arg - $regexp - is true, $delthis is treated as a
12528: regular expression, otherwise \Q$delthis\E is used.
12529: The values are also deleted from the current processes %env.
1.191 harris41 12530:
1.795 albertel 12531: =item * get_env_multiple($name)
12532:
12533: gets $name from the %env hash, it seemlessly handles the cases where multiple
12534: values may be defined and end up as an array ref.
12535:
12536: returns an array of values
12537:
1.243 albertel 12538: =back
12539:
12540: =head2 User Information
1.191 harris41 12541:
1.243 albertel 12542: =over 4
1.191 harris41 12543:
12544: =item *
1.394 bowersj2 12545: X<queryauthenticate()>
12546: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12547: authentication scheme
12548:
12549: =item *
1.394 bowersj2 12550: X<authenticate()>
1.1073 raeburn 12551: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12552: authenticate user from domain's lib servers (first use the current
12553: one). C<$upass> should be the users password.
1.1073 raeburn 12554: $checkdefauth is optional (value is 1 if a check should be made to
12555: authenticate user using default authentication method, and allow
12556: account creation if username does not have account in the domain).
12557: $clientcancheckhost is optional (value is 1 if checking whether the
12558: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12559:
12560: =item *
1.394 bowersj2 12561: X<homeserver()>
12562: B<homeserver($uname,$udom)>: find the server which has
12563: the user's directory and files (there must be only one), this caches
12564: the answer, and also caches if there is a borken connection.
1.191 harris41 12565:
12566: =item *
1.394 bowersj2 12567: X<idget()>
12568: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12569: (IDs are a unique resource in a domain, there must be only 1 ID per
12570: username, and only 1 username per ID in a specific domain) (returns
12571: hash: id=>name,id=>name)
1.191 harris41 12572:
12573: =item *
1.394 bowersj2 12574: X<idrget()>
12575: B<idrget($udom,@unames)>: find the IDs behind a list of
12576: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12577:
12578: =item *
1.394 bowersj2 12579: X<idput()>
12580: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12581:
12582: =item *
1.394 bowersj2 12583: X<rolesinit()>
1.1169 droeschl 12584: B<rolesinit($udom,$username)>: get user privileges.
12585: returns user role, first access and timer interval hashes
1.243 albertel 12586:
12587: =item *
1.1171 droeschl 12588: X<privileged()>
12589: B<privileged($username,$domain)>: returns a true if user has a
12590: privileged and active role (i.e. su or dc), false otherwise.
12591:
12592: =item *
1.551 albertel 12593: X<getsection()>
12594: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12595: course $cname, return section name/number or '' for "not in course"
12596: and '-1' for "no section"
12597:
12598: =item *
1.394 bowersj2 12599: X<userenvironment()>
12600: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12601: passed in @what from the requested user's environment, returns a hash
12602:
1.858 raeburn 12603: =item *
12604: X<userlog_query()>
1.859 albertel 12605: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12606: activity.log file. %filters defines filters applied when parsing the
12607: log file. These can be start or end timestamps, or the type of action
12608: - log to look for Login or Logout events, check for Checkin or
12609: Checkout, role for role selection. The response is in the form
12610: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12611: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12612:
1.243 albertel 12613: =back
12614:
12615: =head2 User Roles
12616:
12617: =over 4
12618:
12619: =item *
12620:
1.810 raeburn 12621: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12622: F: full access
12623: U,I,K: authentication modes (cxx only)
12624: '': forbidden
12625: 1: user needs to choose course
12626: 2: browse allowed
1.766 albertel 12627: A: passphrase authentication needed
1.243 albertel 12628:
12629: =item *
12630:
1.1192 raeburn 12631: constructaccess($url,$setpriv) : check for access to construction space URL
12632:
12633: See if the owner domain and name in the URL match those in the
12634: expected environment. If so, return three element list
12635: ($ownername,$ownerdomain,$ownerhome).
12636:
12637: Otherwise return the null string.
12638:
12639: If second argument 'setpriv' is true, it assigns the privileges,
12640: and returns the same three element list, unless the owner has
12641: blocked "ad hoc" Domain Coordinator access to the Author Space,
12642: in which case the null string is returned.
12643:
12644: =item *
12645:
1.243 albertel 12646: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12647: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12648: and course level
12649:
12650: =item *
12651:
1.988 raeburn 12652: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12653: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12654: $type is Course (default) or Community.
1.988 raeburn 12655: If $forcedefault evaluates to true, text returned will be default
12656: text for $type. Otherwise, if this is a course, the text returned
12657: will be a custom name for the role (if defined in the course's
12658: environment). If no custom name is defined the default is returned.
12659:
1.832 raeburn 12660: =item *
12661:
1.1219 raeburn 12662: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12663: All arguments are optional. Returns a hash of a roles, either for
12664: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12665: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12666: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12667: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12668: For each key, value is set to colon-separated start and end times for
12669: the role. If no username and domain are specified, will default to
1.934 raeburn 12670: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12671: of role statuses (active, future or previous), roles
12672: (e.g., cc,in, st etc.) and domains of the roles which can be used
12673: to restrict the list of roles reported. If no array ref is
12674: provided for types, will default to return only active roles.
1.834 albertel 12675:
1.1195 raeburn 12676: =item *
12677:
12678: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12679: user: $uname:$udom has a role in the course: $cdom_$cnum.
12680:
12681: Additional optional arguments are: $type (if role checking is to be restricted
12682: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12683: available roles) or future (roles available in the future), and
12684: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12685: have active Domain Coordinator role in course's domain or in additional
12686: domains (specified in 'Domains to check for privileged users' in course
12687: environment -- set via: Course Settings -> Classlists and staff listing).
12688:
12689: =item *
12690:
12691: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12692: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12693: $possdomains and $possroles are optional array refs -- to domains to check and
12694: roles to check. If $possdomains is not specified, a dump will be done of the
12695: users' roles.db to check for a dc or su role in any domain. This can be
12696: time consuming if &privileged is called repeatedly (e.g., when displaying a
12697: classlist), so in such cases, supplying a $possdomains array is preferred, as
12698: this then allows &privileged_by_domain() to be used, which caches the identity
12699: of privileged users, eliminating the need for repeated calls to &dump().
12700:
12701: =item *
12702:
12703: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12704: where the outer hash keys are domains specified in the $possdomains array ref,
12705: next inner hash keys are privileged roles specified in the $roles array ref,
12706: and the innermost hash contains key = value pairs for username:domain = end:start
12707: for active or future "privileged" users with that role in that domain. To avoid
12708: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12709: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12710:
1.243 albertel 12711: =back
12712:
12713: =head2 User Modification
12714:
12715: =over 4
12716:
12717: =item *
12718:
1.957 raeburn 12719: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12720: user for the level given by URL. Optional start and end dates (leave empty
12721: string or zero for "no date")
1.191 harris41 12722:
12723: =item *
12724:
1.243 albertel 12725: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12726: change a users, password, possible return values are: ok,
12727: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12728: refused
1.191 harris41 12729:
12730: =item *
12731:
1.243 albertel 12732: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12733:
12734: =item *
12735:
1.1058 raeburn 12736: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12737: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12738:
12739: will update user information (firstname,middlename,lastname,generation,
12740: permanentemail), and if forceid is true, student/employee ID also.
12741: A user's institutional affiliation(s) can also be updated.
12742: User information fields will not be overwritten with empty entries
12743: unless the field is included in the $candelete array reference.
12744: This array is included when a single user is modified via "Manage Users",
12745: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12746:
12747: =item *
12748:
1.286 matthew 12749: modifystudent
12750:
1.957 raeburn 12751: modify a student's enrollment and identification information.
1.1235 raeburn 12752: The course id is resolved based on the current user's environment.
12753: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12754: associated with a course.
12755:
1.297 matthew 12756: This call is essentially a wrapper for lonnet::modifyuser and
12757: lonnet::modify_student_enrollment
1.286 matthew 12758:
12759: Inputs:
12760:
12761: =over 4
12762:
1.957 raeburn 12763: =item B<$udom> Student's loncapa domain
1.286 matthew 12764:
1.957 raeburn 12765: =item B<$uname> Student's loncapa login name
1.286 matthew 12766:
1.964 bisitz 12767: =item B<$uid> Student/Employee ID
1.286 matthew 12768:
1.957 raeburn 12769: =item B<$umode> Student's authentication mode
1.286 matthew 12770:
1.957 raeburn 12771: =item B<$upass> Student's password
1.286 matthew 12772:
1.957 raeburn 12773: =item B<$first> Student's first name
1.286 matthew 12774:
1.957 raeburn 12775: =item B<$middle> Student's middle name
1.286 matthew 12776:
1.957 raeburn 12777: =item B<$last> Student's last name
1.286 matthew 12778:
1.957 raeburn 12779: =item B<$gene> Student's generation
1.286 matthew 12780:
1.957 raeburn 12781: =item B<$usec> Student's section in course
1.286 matthew 12782:
12783: =item B<$end> Unix time of the roles expiration
12784:
12785: =item B<$start> Unix time of the roles start date
12786:
12787: =item B<$forceid> If defined, allow $uid to be changed
12788:
12789: =item B<$desiredhome> server to use as home server for student
12790:
1.957 raeburn 12791: =item B<$email> Student's permanent e-mail address
12792:
12793: =item B<$type> Type of enrollment (auto or manual)
12794:
1.963 raeburn 12795: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12796:
12797: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12798:
1.963 raeburn 12799: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12800:
1.963 raeburn 12801: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12802:
1.1216 raeburn 12803: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12804:
12805: =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 12806:
1.286 matthew 12807: =back
1.297 matthew 12808:
12809: =item *
12810:
12811: modify_student_enrollment
12812:
1.1235 raeburn 12813: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12814: 'role.request.course' must be defined for this function to proceed.
12815:
12816: Inputs:
12817:
12818: =over 4
12819:
1.1235 raeburn 12820: =item $udom, student's domain
1.297 matthew 12821:
1.1235 raeburn 12822: =item $uname, student's name
1.297 matthew 12823:
1.1235 raeburn 12824: =item $uid, student's user id
1.297 matthew 12825:
1.1235 raeburn 12826: =item $first, student's first name
1.297 matthew 12827:
12828: =item $middle
12829:
12830: =item $last
12831:
12832: =item $gene
12833:
12834: =item $usec
12835:
12836: =item $end
12837:
12838: =item $start
12839:
1.957 raeburn 12840: =item $type
12841:
12842: =item $locktype
12843:
12844: =item $cid
12845:
12846: =item $selfenroll
12847:
12848: =item $context
12849:
1.1216 raeburn 12850: =item $credits, number of credits student will earn from this class
12851:
1.297 matthew 12852: =back
12853:
1.191 harris41 12854:
12855: =item *
12856:
1.243 albertel 12857: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12858: custom role; give a custom role to a user for the level given by URL. Specify
12859: name and domain of role author, and role name
1.191 harris41 12860:
12861: =item *
12862:
1.243 albertel 12863: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12864:
12865: =item *
12866:
1.243 albertel 12867: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12868:
12869: =back
12870:
12871: =head2 Course Infomation
12872:
12873: =over 4
1.191 harris41 12874:
12875: =item *
12876:
1.1118 foxr 12877: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12878: specified course id, including all environment settings for the
12879: course, the description of the course will be in the hash under the
12880: key 'description'
1.191 harris41 12881:
1.1118 foxr 12882: $options is an optional parameter that if supplied is a hash reference that controls
12883: what how this function works. It has the following key/values:
12884:
12885: =over 4
12886:
12887: =item freshen_cache
12888:
12889: If defined, and the environment cache for the course is valid, it is
12890: returned in the returned hash.
12891:
12892: =item one_time
12893:
12894: If defined, the last cache time is set to _now_
12895:
12896: =item user
12897:
12898: If defined, the supplied username is used instead of the current user.
12899:
12900:
12901: =back
12902:
1.191 harris41 12903: =item *
12904:
1.624 albertel 12905: resdata($name,$domain,$type,@which) : request for current parameter
12906: setting for a specific $type, where $type is either 'course' or 'user',
12907: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12908: answers for 10 minutes.
1.243 albertel 12909:
1.877 foxr 12910: =item *
12911:
12912: get_courseresdata($courseid, $domain) : dump the entire course resource
12913: data base, returning a hash that is keyed by the resource name and has
12914: values that are the resource value. I believe that the timestamps and
12915: versions are also returned.
12916:
1.1236 raeburn 12917: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12918: supplemental content area. This routine caches the number of files for
12919: 10 minutes.
12920:
1.243 albertel 12921: =back
12922:
12923: =head2 Course Modification
12924:
12925: =over 4
1.191 harris41 12926:
12927: =item *
12928:
1.243 albertel 12929: writecoursepref($courseid,%prefs) : write preferences (environment
12930: database) for a course
1.191 harris41 12931:
12932: =item *
12933:
1.1011 raeburn 12934: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12935:
12936: =item *
12937:
1.1038 raeburn 12938: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12939:
1.1167 droeschl 12940: =item *
12941:
12942: is_course($courseid), is_course($cdom, $cnum)
12943:
12944: Accepts either a combined $courseid (in the form of domain_courseid) or the
12945: two component version $cdom, $cnum. It checks if the specified course exists.
12946:
12947: Returns:
12948: undef if the course doesn't exist, otherwise
12949: in scalar context the combined courseid.
12950: in list context the two components of the course identifier, domain and
12951: courseid.
12952:
1.243 albertel 12953: =back
12954:
12955: =head2 Resource Subroutines
12956:
12957: =over 4
1.191 harris41 12958:
12959: =item *
12960:
1.243 albertel 12961: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12962:
12963: =item *
12964:
1.243 albertel 12965: repcopy($filename) : subscribes to the requested file, and attempts to
12966: replicate from the owning library server, Might return
1.607 raeburn 12967: 'unavailable', 'not_found', 'forbidden', 'ok', or
12968: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12969: resource. Expects the local filesystem pathname
12970: (/home/httpd/html/res/....)
12971:
12972: =back
12973:
12974: =head2 Resource Information
12975:
12976: =over 4
1.191 harris41 12977:
12978: =item *
12979:
1.1228 raeburn 12980: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12981: and returns the value of a variety of different possible values,
12982: $varname should be a request string, and the other parameters can be
12983: used to specify who and what one is asking about. Ordinarily, $cid
12984: does not need to be specified, as it is retrived from
12985: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12986: within lonuserstate::loadmap() when initializing a course, before
12987: $env{'request.course.id'} has been set, so it needs to be provided
12988: in that one case.
1.243 albertel 12989:
12990: Possible values for $varname are environment.lastname (or other item
12991: from the envirnment hash), user.name (or someother aspect about the
12992: user), resource.0.maxtries (or some other part and parameter of a
12993: resource)
1.204 albertel 12994:
12995: =item *
12996:
1.243 albertel 12997: directcondval($number) : get current value of a condition; reads from a state
12998: string
1.204 albertel 12999:
13000: =item *
13001:
1.243 albertel 13002: condval($condidx) : value of condition index based on state
1.204 albertel 13003:
13004: =item *
13005:
1.243 albertel 13006: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13007: resource's metadata, $what should be either a specific key, or either
13008: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13009: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13010:
13011: this function automatically caches all requests
1.191 harris41 13012:
13013: =item *
13014:
1.243 albertel 13015: metadata_query($query,$custom,$customshow) : make a metadata query against the
13016: network of library servers; returns file handle of where SQL and regex results
13017: will be stored for query
1.191 harris41 13018:
13019: =item *
13020:
1.243 albertel 13021: symbread($filename) : return symbolic list entry (filename argument optional);
13022: returns the data handle
1.191 harris41 13023:
13024: =item *
13025:
1.1190 raeburn 13026: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13027: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13028: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13029: on failure, user must be in a course, as it assumes the existence of
13030: the course initial hash, and uses $env('request.course.id'}. The third
13031: arg is an optional reference to a scalar. If this arg is passed in the
13032: call to symbverify, it will be set to 1 if the symb has been set to be
13033: encrypted; otherwise it will be null.
1.191 harris41 13034:
13035: =item *
13036:
1.243 albertel 13037: symbclean($symb) : removes versions numbers from a symb, returns the
13038: cleaned symb
1.191 harris41 13039:
13040: =item *
13041:
1.243 albertel 13042: is_on_map($uri) : checks if the $uri is somewhere on the current
13043: course map, user must be in a course for it to work.
1.191 harris41 13044:
13045: =item *
13046:
1.243 albertel 13047: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13048:
13049: =item *
13050:
1.243 albertel 13051: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13052: a random seed, all arguments are optional, if they aren't sent it uses the
13053: environment to derive them. Note: if symb isn't sent and it can't get one
13054: from &symbread it will use the current time as its return value
1.191 harris41 13055:
13056: =item *
13057:
1.243 albertel 13058: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13059: unfakeable, receipt
1.191 harris41 13060:
13061: =item *
13062:
1.620 albertel 13063: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13064:
13065: =item *
13066:
1.243 albertel 13067: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13068:
13069: =item *
13070:
1.243 albertel 13071: 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 13072:
13073: =item *
13074:
1.243 albertel 13075: 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 13076:
13077: =item *
13078:
1.243 albertel 13079: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13080:
13081: =item *
13082:
1.243 albertel 13083: devalidate($symb) : devalidate temporary spreadsheet calculations,
13084: forcing spreadsheet to reevaluate the resource scores next time.
13085:
1.1195 raeburn 13086: =item *
13087:
1.1196 raeburn 13088: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13089: when viewing in course context.
1.1195 raeburn 13090:
1.1196 raeburn 13091: input: six args -- filename (decluttered), course number, course domain,
13092: url, symb (if registered) and group (if this is a
13093: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13094:
1.1196 raeburn 13095: output: array of five scalars --
1.1195 raeburn 13096: $cfile -- url for file editing if editable on current server
13097: $home -- homeserver of resource (i.e., for author if published,
13098: or course if uploaded.).
13099: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13100: $forceedit -- 1 if icon/link should be to go to edit mode
13101: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13102:
13103: =item *
13104:
13105: is_course_upload($file,$cnum,$cdom)
13106:
13107: Used in course context to determine if current file was uploaded to
13108: the course (i.e., would be found in /userfiles/docs on the course's
13109: homeserver.
13110:
13111: input: 3 args -- filename (decluttered), course number and course domain.
13112: output: boolean -- 1 if file was uploaded.
13113:
1.243 albertel 13114: =back
13115:
13116: =head2 Storing/Retreiving Data
13117:
13118: =over 4
1.191 harris41 13119:
13120: =item *
13121:
1.243 albertel 13122: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13123: for this url; hashref needs to be given and should be a \%hashname; the
13124: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13125: be derived from the env
1.191 harris41 13126:
13127: =item *
13128:
1.243 albertel 13129: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13130: uses critical subroutine
1.191 harris41 13131:
13132: =item *
13133:
1.243 albertel 13134: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13135: all args are optional
1.191 harris41 13136:
13137: =item *
13138:
1.717 albertel 13139: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13140: dumps the complete (or key matching regexp) namespace into a hash
13141: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13142: normally &store()ed into
13143:
13144: $range should be either an integer '100' (give me the first 100
13145: matching records)
13146: or be two integers sperated by a - with no spaces
13147: '30-50' (give me the 30th through the 50th matching
13148: records)
13149:
13150:
13151: =item *
13152:
13153: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13154: replaces a &store() version of data with a replacement set of data
13155: for a particular resource in a namespace passed in the $storehash hash
13156: reference
13157:
13158: =item *
13159:
1.243 albertel 13160: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13161: works very similar to store/cstore, but all data is stored in a
13162: temporary location and can be reset using tmpreset, $storehash should
13163: be a hash reference, returns nothing on success
1.191 harris41 13164:
13165: =item *
13166:
1.243 albertel 13167: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13168: similar to restore, but all data is stored in a temporary location and
13169: can be reset using tmpreset. Returns a hash of values on success,
13170: error string otherwise.
1.191 harris41 13171:
13172: =item *
13173:
1.243 albertel 13174: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13175: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13176:
13177: =item *
13178:
1.243 albertel 13179: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13180: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13181:
13182: =item *
13183:
1.243 albertel 13184: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13185: namesp ($udom and $uname are optional)
1.191 harris41 13186:
13187: =item *
13188:
1.702 albertel 13189: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13190: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13191: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13192:
1.702 albertel 13193: $range should be either an integer '100' (give me the first 100
13194: matching records)
13195: or be two integers sperated by a - with no spaces
13196: '30-50' (give me the 30th through the 50th matching
13197: records)
1.449 matthew 13198: =item *
13199:
13200: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13201: $store can be a scalar, an array reference, or if the amount to be
13202: incremented is > 1, a hash reference.
13203:
13204: ($udom and $uname are optional)
1.191 harris41 13205:
13206: =item *
13207:
1.243 albertel 13208: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13209: ($udom and $uname are optional)
1.191 harris41 13210:
13211: =item *
13212:
1.243 albertel 13213: cput($namespace,$storehash,$udom,$uname) : critical put
13214: ($udom and $uname are optional)
1.191 harris41 13215:
13216: =item *
13217:
1.748 albertel 13218: newput($namespace,$storehash,$udom,$uname) :
13219:
13220: Attempts to store the items in the $storehash, but only if they don't
13221: currently exist, if this succeeds you can be certain that you have
13222: successfully created a new key value pair in the $namespace db.
13223:
13224:
13225: Args:
13226: $namespace: name of database to store values to
13227: $storehash: hashref to store to the db
13228: $udom: (optional) domain of user containing the db
13229: $uname: (optional) name of user caontaining the db
13230:
13231: Returns:
13232: 'ok' -> succeeded in storing all keys of $storehash
13233: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13234: least <key> already existed in the db (other
13235: requested keys may also already exist)
1.967 bisitz 13236: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13237: 'con_lost' -> unable to contact request server
13238: 'refused' -> action was not allowed by remote machine
13239:
13240:
13241: =item *
13242:
1.243 albertel 13243: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13244: reference filled in from namesp (encrypts the return communication)
13245: ($udom and $uname are optional)
1.191 harris41 13246:
13247: =item *
13248:
1.243 albertel 13249: log($udom,$name,$home,$message) : write to permanent log for user; use
13250: critical subroutine
13251:
1.806 raeburn 13252: =item *
13253:
1.860 raeburn 13254: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13255: array reference filled in from namespace found in domain level on either
13256: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13257:
13258: =item *
13259:
1.860 raeburn 13260: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13261: domain level either on specified domain server ($uhome) or primary domain
13262: server ($udom and $uhome are optional)
1.806 raeburn 13263:
1.943 raeburn 13264: =item *
13265:
1.1240 raeburn 13266: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13267: for: authentication, language, quotas, timezone, date locale, and portal URL in
13268: the target domain.
13269:
13270: May also include additional key => value pairs for the following groups:
13271:
13272: =over
13273:
13274: =item
13275: disk quotas (MB allocated by default to portfolios and authoring spaces).
13276:
13277: =over
13278:
13279: =item defaultquota, authorquota
13280:
13281: =back
13282:
13283: =item
13284: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13285: portfolio for users).
13286:
13287: =over
13288:
13289: =item
13290: aboutme, blog, webdav, portfolio
13291:
13292: =back
13293:
13294: =item
13295: requestcourses: ability to request courses, and how requests are processed.
13296:
13297: =over
13298:
13299: =item
1.1246 raeburn 13300: official, unofficial, community, textbook
1.1240 raeburn 13301:
13302: =back
13303:
13304: =item
13305: inststatus: types of institutional affiliation, and order in which they are displayed.
13306:
13307: =over
13308:
13309: =item
13310: inststatustypes, inststatusorder
13311:
13312: =back
13313:
13314: =item
13315: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13316: for course's uploaded content.
13317:
13318: =over
13319:
13320: =item
1.1246 raeburn 13321: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13322: communityquota, textbookquota
1.1240 raeburn 13323:
13324: =back
13325:
13326: =item
13327: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13328: on your servers.
13329:
13330: =over
13331:
13332: =item
13333: remotesessions, hostedsessions
13334:
13335: =back
13336:
13337: =back
13338:
13339: In cases where a domain coordinator has never used the "Set Domain Configuration"
13340: utility to create a configuration.db file on a domain's primary library server
13341: only the following domain defaults: auth_def, auth_arg_def, lang_def
13342: -- corresponding values are authentication type (internal, krb4, krb5,
13343: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13344: will be available. Values are retrieved from cache (if current), unless the
13345: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13346: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13347:
13348: Typical usage:
1.943 raeburn 13349:
1.1240 raeburn 13350: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13351:
1.243 albertel 13352: =back
13353:
13354: =head2 Network Status Functions
13355:
13356: =over 4
1.191 harris41 13357:
13358: =item *
13359:
1.1137 raeburn 13360: dirlist() : return directory list based on URI (first arg).
13361:
13362: Inputs: 1 required, 5 optional.
13363:
13364: =over
13365:
13366: =item
13367: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13368:
13369: =item
13370: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13371:
13372: =item
13373: $username - username of user/course to be listed. Extracted from $uri if absent.
13374:
13375: =item
13376: $getpropath - boolean: 1 if prepend path using &propath().
13377:
13378: =item
13379: $getuserdir - boolean: 1 if prepend path for "userfiles".
13380:
13381: =item
13382: $alternateRoot - path to prepend in place of path from $uri.
13383:
13384: =back
13385:
13386: Returns: Array of up to two items.
13387:
13388: =over
13389:
13390: a reference to an array of files/subdirectories
13391:
13392: =over
13393:
13394: Each element in the array of files/subdirectories is a & separated list of
13395: item name and the result of running stat on the item. If dirlist was requested
13396: for a file instead of a directory, the item name will be ''. For a directory
13397: listing, if the item is a metadata file, the element will end &N&M
13398: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13399: default copyright set (1).
13400:
13401: =back
13402:
13403: a scalar containing error condition (if encountered).
13404:
13405: =over
13406:
13407: =item
13408: no_host (no homeserver identified for $username:$domain).
13409:
13410: =item
13411: no_such_host (server contacted for listing not identified as valid host).
13412:
13413: =item
13414: con_lost (connection to remote server failed).
13415:
13416: =item
13417: refused (invalid $username:$domain received on lond side).
13418:
13419: =item
13420: no_such_dir (directory at specified path on lond side does not exist).
13421:
13422: =item
13423: empty (directory at specified path on lond side is empty).
13424:
13425: =over
13426:
13427: This is currently not encountered because the &ls3, &ls2,
13428: &ls (_handler) routines on the lond side do not filter out
13429: . and .. from a directory listing.
13430:
13431: =back
13432:
13433: =back
13434:
13435: =back
1.191 harris41 13436:
13437: =item *
13438:
1.243 albertel 13439: spareserver() : find server with least workload from spare.tab
13440:
1.986 foxr 13441:
13442: =item *
13443:
13444: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13445: if there is no corresponding loncapa host.
13446:
1.243 albertel 13447: =back
13448:
1.986 foxr 13449:
1.243 albertel 13450: =head2 Apache Request
13451:
13452: =over 4
1.191 harris41 13453:
13454: =item *
13455:
1.243 albertel 13456: ssi($url,%hash) : server side include, does a complete request cycle on url to
13457: localhost, posts hash
13458:
13459: =back
13460:
13461: =head2 Data to String to Data
13462:
13463: =over 4
1.191 harris41 13464:
13465: =item *
13466:
1.243 albertel 13467: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13468: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13469:
13470: =item *
13471:
1.243 albertel 13472: hashref2str($hashref) : convert a hashref into a string complete with
13473: escaping and '=' and '&' separators, supports elements that are
13474: arrayrefs and hashrefs
1.191 harris41 13475:
13476: =item *
13477:
1.243 albertel 13478: arrayref2str($arrayref) : convert an arrayref into a string complete
13479: with escaping and '&' separators, supports elements that are arrayrefs
13480: and hashrefs
1.191 harris41 13481:
13482: =item *
13483:
1.243 albertel 13484: str2hash($string) : convert string to hash using unescaping and
13485: splitting on '=' and '&', supports elements that are arrayrefs and
13486: hashrefs
1.191 harris41 13487:
13488: =item *
13489:
1.243 albertel 13490: str2array($string) : convert string to hash using unescaping and
13491: splitting on '&', supports elements that are arrayrefs and hashrefs
13492:
13493: =back
13494:
13495: =head2 Logging Routines
13496:
13497:
13498: These routines allow one to make log messages in the lonnet.log and
13499: lonnet.perm logfiles.
1.191 harris41 13500:
1.1119 foxr 13501: =over 4
13502:
1.191 harris41 13503: =item *
13504:
1.243 albertel 13505: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: logthis() : append message to the normal lonnet.log file, it gets
13510: preiodically rolled over and deleted.
1.191 harris41 13511:
13512: =item *
13513:
1.243 albertel 13514: logperm() : append a permanent message to lonnet.perm.log, this log
13515: file never gets deleted by any automated portion of the system, only
13516: messages of critical importance should go in here.
13517:
1.1119 foxr 13518:
1.243 albertel 13519: =back
13520:
13521: =head2 General File Helper Routines
13522:
13523: =over 4
1.191 harris41 13524:
13525: =item *
13526:
1.481 raeburn 13527: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13528: (a) files in /uploaded
13529: (i) If a local copy of the file exists -
13530: compares modification date of local copy with last-modified date for
13531: definitive version stored on home server for course. If local copy is
13532: stale, requests a new version from the home server and stores it.
13533: If the original has been removed from the home server, then local copy
13534: is unlinked.
13535: (ii) If local copy does not exist -
13536: requests the file from the home server and stores it.
13537:
13538: If $caller is 'uploadrep':
13539: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13540: for request for files originally uploaded via DOCS.
13541: - returns 'ok' if fresh local copy now available, -1 otherwise.
13542:
13543: Otherwise:
13544: This indicates a call from the content generation phase of the request.
13545: - returns the entire contents of the file or -1.
13546:
13547: (b) files in /res
13548: - returns the entire contents of a file or -1;
13549: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13550:
1.712 albertel 13551:
13552: =item *
13553:
13554: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13555: reference
13556:
13557: returns either a stat() list of data about the file or an empty list
13558: if the file doesn't exist or couldn't find out about it (connection
13559: problems or user unknown)
13560:
1.191 harris41 13561: =item *
13562:
1.243 albertel 13563: filelocation($dir,$file) : returns file system location of a file
13564: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13565: directory that relative $file lookups are to looked in ($dir of /a/dir
13566: and a file of ../bob will become /a/bob)
1.191 harris41 13567:
13568: =item *
13569:
13570: hreflocation($dir,$file) : returns file system location or a URL; same as
13571: filelocation except for hrefs
13572:
13573: =item *
13574:
13575: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13576:
1.243 albertel 13577: =back
13578:
1.608 albertel 13579: =head2 Usererfile file routines (/uploaded*)
13580:
13581: =over 4
13582:
13583: =item *
13584:
13585: userfileupload(): main rotine for putting a file in a user or course's
13586: filespace, arguments are,
13587:
1.620 albertel 13588: formname - required - this is the name of the element in $env where the
1.608 albertel 13589: filename, and the contents of the file to create/modifed exist
1.620 albertel 13590: the filename is in $env{'form.'.$formname.'.filename'} and the
13591: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13592: context - if coursedoc, store the file in the course of the active role
13593: of the current user;
13594: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13595: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13596: subdir - required - subdirectory to put the file in under ../userfiles/
13597: if undefined, it will be placed in "unknown"
13598:
13599: (This routine calls clean_filename() to remove any dangerous
13600: characters from the filename, and then calls finuserfileupload() to
13601: complete the transaction)
13602:
13603: returns either the url of the uploaded file (/uploaded/....) if successful
13604: and /adm/notfound.html if unsuccessful
13605:
13606: =item *
13607:
13608: clean_filename(): routine for cleaing a filename up for storage in
13609: userfile space, argument is:
13610:
13611: filename - proposed filename
13612:
13613: returns: the new clean filename
13614:
13615: =item *
13616:
1.1090 raeburn 13617: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13618: userspace, probably shouldn't be called directly
13619:
13620: docuname: username or courseid of destination for the file
13621: docudom: domain of user/course of destination for the file
13622: formname: same as for userfileupload()
1.1090 raeburn 13623: fname: filename (including subdirectories) for the file
13624: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13625: allfiles: reference to hash used to store objects found by parser
13626: codebase: reference to hash used for codebases of java objects found by parser
13627: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13628: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13629: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13630: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13631: context: if 'overwrite', will move the uploaded file from its temporary location to
13632: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13633: mimetype: reference to scalar to accommodate mime type determined
13634: from File::MMagic if $parser = parse.
1.608 albertel 13635:
13636: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13637: and /adm/notfound.html if unsuccessful (or an error message if context
13638: was 'overwrite').
13639:
1.608 albertel 13640:
13641: =item *
13642:
13643: renameuserfile(): renames an existing userfile to a new name
13644:
13645: Args:
13646: docuname: username or courseid of destination for the file
13647: docudom: domain of user/course of destination for the file
13648: old: current file name (including any subdirs under userfiles)
13649: new: desired file name (including any subdirs under userfiles)
13650:
13651: =item *
13652:
13653: mkdiruserfile(): creates a directory is a userfiles dir
13654:
13655: Args:
13656: docuname: username or courseid of destination for the file
13657: docudom: domain of user/course of destination for the file
13658: dir: dir to create (including any subdirs under userfiles)
13659:
13660: =item *
13661:
13662: removeuserfile(): removes a file that exists in userfiles
13663:
13664: Args:
13665: docuname: username or courseid of destination for the file
13666: docudom: domain of user/course of destination for the file
13667: fname: filname to delete (including any subdirs under userfiles)
13668:
13669: =item *
13670:
13671: removeuploadedurl(): convience function for removeuserfile()
13672:
13673: Args:
13674: url: a full /uploaded/... url to delete
13675:
1.747 albertel 13676: =item *
13677:
13678: get_portfile_permissions():
13679: Args:
13680: domain: domain of user or course contain the portfolio files
13681: user: name of user or num of course contain the portfolio files
13682: Returns:
13683: hashref of a dump of the proper file_permissions.db
13684:
13685:
13686: =item *
13687:
13688: get_access_controls():
13689:
13690: Args:
13691: current_permissions: the hash ref returned from get_portfile_permissions()
13692: group: (optional) the group you want the files associated with
13693: file: (optional) the file you want access info on
13694:
13695: Returns:
1.749 raeburn 13696: a hash (keys are file names) of hashes containing
13697: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13698: values are XML containing access control settings (see below)
1.747 albertel 13699:
13700: Internal notes:
13701:
1.749 raeburn 13702: access controls are stored in file_permissions.db as key=value pairs.
13703: key -> path to file/file_name\0uniqueID:scope_end_start
13704: where scope -> public,guest,course,group,domains or users.
13705: end -> UNIX time for end of access (0 -> no end date)
13706: start -> UNIX time for start of access
13707:
13708: value -> XML description of access control
13709: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13710: <start></start>
13711: <end></end>
13712:
13713: <password></password> for scope type = guest
13714:
13715: <domain></domain> for scope type = course or group
13716: <number></number>
13717: <roles id="">
13718: <role></role>
13719: <access></access>
13720: <section></section>
13721: <group></group>
13722: </roles>
13723:
13724: <dom></dom> for scope type = domains
13725:
13726: <users> for scope type = users
13727: <user>
13728: <uname></uname>
13729: <udom></udom>
13730: </user>
13731: </users>
13732: </scope>
13733:
13734: Access data is also aggregated for each file in an additional key=value pair:
13735: key -> path to file/file_name\0accesscontrol
13736: value -> reference to hash
13737: hash contains key = value pairs
13738: where key = uniqueID:scope_end_start
13739: value = UNIX time record was last updated
13740:
13741: Used to improve speed of look-ups of access controls for each file.
13742:
13743: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13744:
1.1198 raeburn 13745: =item *
13746:
1.749 raeburn 13747: modify_access_controls():
13748:
13749: Modifies access controls for a portfolio file
13750: Args
13751: 1. file name
13752: 2. reference to hash of required changes,
13753: 3. domain
13754: 4. username
13755: where domain,username are the domain of the portfolio owner
13756: (either a user or a course)
13757:
13758: Returns:
13759: 1. result of additions or updates ('ok' or 'error', with error message).
13760: 2. result of deletions ('ok' or 'error', with error message).
13761: 3. reference to hash of any new or updated access controls.
13762: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13763: key = integer (inbound ID)
1.1198 raeburn 13764: value = uniqueID
13765:
13766: =item *
13767:
13768: get_timebased_id():
13769:
13770: Attempts to get a unique timestamp-based suffix for use with items added to a
13771: course via the Course Editor (e.g., folders, composite pages,
13772: group bulletin boards).
13773:
13774: Args: (first three required; six others optional)
13775:
13776: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13777: docssequence, or name of group
13778:
13779: 2. keyid (alphanumeric): name of temporary locking key in hash,
13780: e.g., num, boardids
13781:
13782: 3. namespace: name of gdbm file used to store suffixes already assigned;
13783: file will be named nohist_namespace.db
13784:
13785: 4. cdom: domain of course; default is current course domain from %env
13786:
13787: 5. cnum: course number; default is current course number from %env
13788:
13789: 6. idtype: set to concat if an additional digit is to be appended to the
13790: unix timestamp to form the suffix, if the plain timestamp is already
13791: in use. Default is to not do this, but simply increment the unix
13792: timestamp by 1 until a unique key is obtained.
13793:
13794: 7. who: holder of locking key; defaults to user:domain for user.
13795:
13796: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13797: retrying); default is 3.
13798:
13799: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13800:
13801: Returns:
13802:
13803: 1. suffix obtained (numeric)
13804:
13805: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13806:
13807: 3. error: contains (localized) error message if an error occurred.
13808:
1.747 albertel 13809:
1.608 albertel 13810: =back
13811:
1.243 albertel 13812: =head2 HTTP Helper Routines
13813:
13814: =over 4
13815:
1.191 harris41 13816: =item *
13817:
13818: escape() : unpack non-word characters into CGI-compatible hex codes
13819:
13820: =item *
13821:
13822: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13823:
1.243 albertel 13824: =back
13825:
13826: =head1 PRIVATE SUBROUTINES
13827:
13828: =head2 Underlying communication routines (Shouldn't call)
13829:
13830: =over 4
13831:
13832: =item *
13833:
13834: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13835:
13836: =item *
13837:
13838: reply() : uses subreply to send a message to remote machine, logs all failures
13839:
13840: =item *
13841:
13842: critical() : passes a critical message to another server; if cannot
13843: get through then place message in connection buffer directory and
13844: returns con_delayed, if incapable of saving message, returns
13845: con_failed
13846:
13847: =item *
13848:
13849: reconlonc() : tries to reconnect lonc client processes.
13850:
13851: =back
13852:
13853: =head2 Resource Access Logging
13854:
13855: =over 4
13856:
13857: =item *
13858:
13859: flushcourselogs() : flush (save) buffer logs and access logs
13860:
13861: =item *
13862:
13863: courselog($what) : save message for course in hash
13864:
13865: =item *
13866:
13867: courseacclog($what) : save message for course using &courselog(). Perform
13868: special processing for specific resource types (problems, exams, quizzes, etc).
13869:
1.191 harris41 13870: =item *
13871:
13872: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13873: as a PerlChildExitHandler
1.243 albertel 13874:
13875: =back
13876:
13877: =head2 Other
13878:
13879: =over 4
13880:
13881: =item *
13882:
13883: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13884:
13885: =back
13886:
13887: =cut
1.877 foxr 13888:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>